Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from CiscoConnection import ComConnection
- import sys
- import os
- import subprocess as sb
- #----------------------------------------------------------------------------------------------------------------------------------------------
- # all constants in code are here
- allConfigsPath = "C:\Program Files\Tftpd32\conf\\"
- possibleAvaliableHostIp = ["10.72.191.51","10.72.191.52","10.72.191.53","10.72.191.54","10.72.191.55"]
- lanRouterConnectionFilePath = "C:\Program Files\Tftpd32\other\connection.txt"
- computerIp = "10.72.191.50"
- def ereaseRouter(con):
- response = con.readResponse()
- countEmptyResponse = 0
- countTrys = 0
- defaultLoginAndPassword = "cisco"
- isYourNameState = False
- while "Username:" in response or "Password:" in response or not "Router>" in response or not "Router#" in response:
- print(response,"<--------------- response")
- if "yourname#" in response:
- isYourNameState = True
- break
- if len(response) == 0:
- con.sendCommand("")
- countEmptyResponse+= 1
- if countEmptyResponse == 2:
- print("Step 1 'eraseRouter' breaked while doing this process")
- print("Most probably router is already configured")
- break
- elif "Username:" in response or "Password:" in response:
- con.sendCommand(defaultLoginAndPassword)
- countTrys += 1
- if countTrys == 5:
- print("Function eraserRouter get stucked in a loop\nAbort")
- print("Probably router already configured")
- sys.exit()
- response = con.readResponse()
- con.lastCommandEnterned()
- con.sendCommand("")
- response = con.readResponse()
- con.lastCommandEnterned()
- print("-------------------------------")
- print(response)
- print("-----------------------------")
- print("yourname#" not in response)
- if "yourname#" not in response or not isYourNameState:
- print("'yourname#' not in response after leaving login in loop\nDafuq abort")
- sys.exit()
- con.sendCommand("erase startup-config")
- con.lastCommandEnterned
- con.sendCommand("\r")
- con.sendCommand("write erase")
- con.lastCommandEnterned
- con.sendCommand("\r")
- con.sendCommand("reload")
- con.lastCommandEnterned
- if "yes/no" in con.readResponse():
- con.sendCommand("yes")
- con.lastCommandEnterned()
- con.sendCommand("\r")
- else:
- con.sendCommand("reload\r")
- #----------------------------------------------------------------------------------------------------------------------------------------------
- def loadConfigFromTftp(connection):
- print("Preparing for load config function")
- # check if in enable mode
- boolValue, item = connection.readAndCheckIfTextPresent(["Router>","Router#"])
- print("Cheking if router is in Router> or Router# state")
- if not boolValue:
- print("Router not in a valid state")
- print("Last state of router was")
- print(item)
- print("\nEnding script here")
- sys.exit()
- if ">" in item:
- connection.sendCommand("en")
- # check which ip can be used
- ipHost = ""
- for ip in possibleAvaliableHostIp:
- result = sb.run(str("ping "+ip +" -n 2").split())
- if "0%" in result or "50%" in result:
- ipHost = ip
- if len(ipHost) == 0:
- print("No ip from avaliable ip list was avaliable or something else xD")
- sys.exit()
- # load basic config
- # iterate thought
- # insert every command
- for line in open(file=lanRouterConnectionFilePath,mode="r").readlines():
- connection.sendCommand(line.replace("hostIp",ipHost),deley=0.2)
- # roiter should be now in #(en) mode
- res = connection.sendCommandAndReturnResponse("ping "+computerIp+" repeat 2")
- if not "!" in res:
- print("Attempt of configuration was not successful")
- sys.exit()
- connection.sendCommand"#copy tftp: running-config"
- print("Interface configured")
- #----------------------------------------------------------------------------------------------------------------------------------------------
- def main():
- # first let's check if there are starting value
- values = sys.argv
- #values = ["","Com5","file.txt"]
- if len(values) != 3:
- # num of passed values
- num = len(values) -1
- print(f"\nTo small number of parameters {num}, first should be number/name of com port\nand second "
- +f"should be full name of config file inside directory -> {allConfigsPath[:-1]}")
- sys.exit(0)
- # remove all not needed chars
- comPort = str(values[1]).upper().replace("\s","").replace("\n","").replace("\r","")
- print("comPort port ->", comPort)
- configFileName = values[2]
- configFilePath = allConfigsPath+configFileName
- # if contains com in value
- if "COM" in comPort[:3]:
- # check if number value is correct
- try:
- portNumber = int(comPort.split("COM")[1])
- except Exception:
- print(f"Given value is incorrect {comPort}\nTry for example 'COM1' or '1'")
- sys.exit(0)
- else:
- try:
- portNumber = int(comPort.split("COM")[1])
- comPort = "COM"+str(portNumber)
- except ValueError:
- print("Port number is wrong\nShould be just an integer")
- sys.exit(0)
- print("portNumber",portNumber)
- # check if second passed value is correct
- try:
- if not os.path.isfile(fname):
- print("Config file is in a worng place, move file to "+allConfigsPath)
- sys.exit(0)
- except Exception:
- print("Passed file name was probably a directory")
- try:
- # make a connection
- connection = ComConnection(comPort)
- except Exception as e:
- print(e)
- print("Wrong port or connection is already open in maybe putty or other sscript session")
- sys.exit()
- # Step number 1 is reset device
- ereaseRouter(connection)
- # Step number 2 is basic lan configuration and loading configuration
- loadConfigFromTftp(connection)
- # if router not erased
- # Test
- # erase startup-configuration
- # write erease
- # reload
- # if router erased
- # load configuration throught tftp
- # if router configured
- # check config and adjust changes
- #----------------------------------------------------------------------------------------------------------------------------------------------
- class ConfigManager:
- import re
- def __init__(self,pathToFile):
- try:
- with open(pathToFile,"r") as file:
- self.configFileAsList = file.readlines()
- except Exception as e:
- print(e)
- print("Configuration file could not be open dou to:\nNo write to access a file\nFile does not exist\rFile is corrupted")
- sys.exit(0)
- self.hostName = self.getHostname()
- self.asaNum = ""
- self.ipWan = ""
- self.ipLan = ""
- def getHostname(self):
- for x in self.configFileAsList:
- if "hostname" in x:
- return x.split("hostname")[1].replace("\s", "")
- return None
- #----------------------------------------------------------------------------------------------------------------------------------------------
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement