Advertisement
Guest User

Untitled

a guest
Jan 29th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.41 KB | None | 0 0
  1. from CiscoConnection import ComConnection
  2. import sys
  3. import os
  4. import subprocess as sb
  5.  
  6. #----------------------------------------------------------------------------------------------------------------------------------------------
  7. # all constants in code are here
  8. allConfigsPath = "C:\Program Files\Tftpd32\conf\\"
  9. possibleAvaliableHostIp = ["10.72.191.51","10.72.191.52","10.72.191.53","10.72.191.54","10.72.191.55"]
  10. lanRouterConnectionFilePath = "C:\Program Files\Tftpd32\other\connection.txt"
  11. computerIp = "10.72.191.50"
  12.  
  13. def ereaseRouter(con):
  14. response = con.readResponse()
  15. countEmptyResponse = 0
  16. countTrys = 0
  17. defaultLoginAndPassword = "cisco"
  18. isYourNameState = False
  19. while "Username:" in response or "Password:" in response or not "Router>" in response or not "Router#" in response:
  20. print(response,"<--------------- response")
  21. if "yourname#" in response:
  22. isYourNameState = True
  23. break
  24. if len(response) == 0:
  25. con.sendCommand("")
  26. countEmptyResponse+= 1
  27. if countEmptyResponse == 2:
  28. print("Step 1 'eraseRouter' breaked while doing this process")
  29. print("Most probably router is already configured")
  30. break
  31. elif "Username:" in response or "Password:" in response:
  32. con.sendCommand(defaultLoginAndPassword)
  33. countTrys += 1
  34. if countTrys == 5:
  35. print("Function eraserRouter get stucked in a loop\nAbort")
  36. print("Probably router already configured")
  37. sys.exit()
  38. response = con.readResponse()
  39. con.lastCommandEnterned()
  40. con.sendCommand("")
  41. response = con.readResponse()
  42. con.lastCommandEnterned()
  43. print("-------------------------------")
  44. print(response)
  45. print("-----------------------------")
  46. print("yourname#" not in response)
  47. if "yourname#" not in response or not isYourNameState:
  48. print("'yourname#' not in response after leaving login in loop\nDafuq abort")
  49. sys.exit()
  50. con.sendCommand("erase startup-config")
  51. con.lastCommandEnterned
  52. con.sendCommand("\r")
  53. con.sendCommand("write erase")
  54. con.lastCommandEnterned
  55. con.sendCommand("\r")
  56. con.sendCommand("reload")
  57. con.lastCommandEnterned
  58. if "yes/no" in con.readResponse():
  59. con.sendCommand("yes")
  60. con.lastCommandEnterned()
  61. con.sendCommand("\r")
  62. else:
  63. con.sendCommand("reload\r")
  64. #----------------------------------------------------------------------------------------------------------------------------------------------
  65. def loadConfigFromTftp(connection):
  66. print("Preparing for load config function")
  67. # check if in enable mode
  68. boolValue, item = connection.readAndCheckIfTextPresent(["Router>","Router#"])
  69. print("Cheking if router is in Router> or Router# state")
  70. if not boolValue:
  71. print("Router not in a valid state")
  72. print("Last state of router was")
  73. print(item)
  74. print("\nEnding script here")
  75. sys.exit()
  76. if ">" in item:
  77. connection.sendCommand("en")
  78. # check which ip can be used
  79. ipHost = ""
  80. for ip in possibleAvaliableHostIp:
  81. result = sb.run(str("ping "+ip +" -n 2").split())
  82. if "0%" in result or "50%" in result:
  83. ipHost = ip
  84. if len(ipHost) == 0:
  85. print("No ip from avaliable ip list was avaliable or something else xD")
  86. sys.exit()
  87.  
  88. # load basic config
  89. # iterate thought
  90. # insert every command
  91. for line in open(file=lanRouterConnectionFilePath,mode="r").readlines():
  92. connection.sendCommand(line.replace("hostIp",ipHost),deley=0.2)
  93. # roiter should be now in #(en) mode
  94. res = connection.sendCommandAndReturnResponse("ping "+computerIp+" repeat 2")
  95. if not "!" in res:
  96. print("Attempt of configuration was not successful")
  97. sys.exit()
  98. connection.sendCommand"#copy tftp: running-config"
  99. print("Interface configured")
  100. #----------------------------------------------------------------------------------------------------------------------------------------------
  101. def main():
  102. # first let's check if there are starting value
  103. values = sys.argv
  104. #values = ["","Com5","file.txt"]
  105. if len(values) != 3:
  106. # num of passed values
  107. num = len(values) -1
  108. print(f"\nTo small number of parameters {num}, first should be number/name of com port\nand second "
  109. +f"should be full name of config file inside directory -> {allConfigsPath[:-1]}")
  110. sys.exit(0)
  111. # remove all not needed chars
  112. comPort = str(values[1]).upper().replace("\s","").replace("\n","").replace("\r","")
  113. print("comPort port ->", comPort)
  114. configFileName = values[2]
  115. configFilePath = allConfigsPath+configFileName
  116. # if contains com in value
  117. if "COM" in comPort[:3]:
  118. # check if number value is correct
  119. try:
  120. portNumber = int(comPort.split("COM")[1])
  121. except Exception:
  122. print(f"Given value is incorrect {comPort}\nTry for example 'COM1' or '1'")
  123. sys.exit(0)
  124. else:
  125. try:
  126. portNumber = int(comPort.split("COM")[1])
  127. comPort = "COM"+str(portNumber)
  128. except ValueError:
  129. print("Port number is wrong\nShould be just an integer")
  130. sys.exit(0)
  131.  
  132. print("portNumber",portNumber)
  133.  
  134. # check if second passed value is correct
  135. try:
  136. if not os.path.isfile(fname):
  137. print("Config file is in a worng place, move file to "+allConfigsPath)
  138. sys.exit(0)
  139. except Exception:
  140. print("Passed file name was probably a directory")
  141. try:
  142. # make a connection
  143. connection = ComConnection(comPort)
  144. except Exception as e:
  145. print(e)
  146. print("Wrong port or connection is already open in maybe putty or other sscript session")
  147. sys.exit()
  148. # Step number 1 is reset device
  149. ereaseRouter(connection)
  150. # Step number 2 is basic lan configuration and loading configuration
  151. loadConfigFromTftp(connection)
  152. # if router not erased
  153. # Test
  154. # erase startup-configuration
  155. # write erease
  156. # reload
  157. # if router erased
  158. # load configuration throught tftp
  159. # if router configured
  160. # check config and adjust changes
  161. #----------------------------------------------------------------------------------------------------------------------------------------------
  162. class ConfigManager:
  163. import re
  164. def __init__(self,pathToFile):
  165. try:
  166. with open(pathToFile,"r") as file:
  167. self.configFileAsList = file.readlines()
  168. except Exception as e:
  169. print(e)
  170. print("Configuration file could not be open dou to:\nNo write to access a file\nFile does not exist\rFile is corrupted")
  171. sys.exit(0)
  172.  
  173. self.hostName = self.getHostname()
  174. self.asaNum = ""
  175. self.ipWan = ""
  176. self.ipLan = ""
  177.  
  178. def getHostname(self):
  179. for x in self.configFileAsList:
  180. if "hostname" in x:
  181. return x.split("hostname")[1].replace("\s", "")
  182. return None
  183.  
  184.  
  185.  
  186.  
  187.  
  188.  
  189. #----------------------------------------------------------------------------------------------------------------------------------------------
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197. if __name__ == "__main__":
  198. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement