Hello
We finished part 1 where the config generator produced a test.txt file on the Window desktop. Now it’s time for another script to upload the config through a telnet connection. To do that, we need pexpect, and it’s not possible to install pexpect on windows. Fortunately, Windows 10 provides the windows subsystem for linux. I’ve installed Ubuntu using powershell.
Because the script doesn’t know the username, it needs to get the username folder from path.home. Once it has it, it reaches out to Windows, copies the test.txt config to its own c.txt file. Then it creates a telnet connection to the console server and uploads the config line by line.
import pexpect import os import sys from pathlib import Path def createall(ip,port,consoleserver): #getting the username and copying the config myarraypath = str(Path.home()).split('/') table = { 39 : None } myfinaluser = myarraypath[2].translate(table) print(myfinaluser) #if c.txt exists, contents should be deleted clearcommand = "truncate -s 0 c.txt" os.system(clearcommand) command = "tail --lines=+1 /mnt/c/Users/" + myfinaluser + "/Desktop/test.txt >> /home/" + myfinaluser + "/c.txt" os.system(command) #spawning a connection child = pexpect.spawn('telnet ' + ip + ' ' + port) child.logfile = sys.stdout.buffer child.timeout = 14 child.delaybeforesend = 1.0 myconsoleserver = consoleserver child.expect(consoleserver + ' login:') child.sendline('yourlogin') child.expect('Password:') child.sendline('yourpassword') child.sendline() #you just have to love my variable names #you may see either of the prompts so 2 cases here # if prompt is >, send an enable neverknow = child.expect(['#', '>']) if neverknow==1: child.sendline('en') child.expect('#') #if prompt is #, upload the c.txt file line by line elif neverknow==0: child.sendline('configure terminal') child.expect('#') filename = 'c.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: line = line #+ "\015" child.sendline(line) #this script can be run with the following command: #python3 script.py 192.168.0.1 8002 myconsoleserver if __name__ == "__main__": ip = sys.argv[1] port = sys.argv[2] consoleserver = sys.argv[3] createall(ip, port, consoleserver)