My own config generator and autoloader part 2 – uploading the config


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)

#if c.txt exists, contents should be deleted
  clearcommand = "truncate -s 0 c.txt"
  command = "tail --lines=+1 /mnt/c/Users/" + myfinaluser + "/Desktop/test.txt >> /home/" + myfinaluser + "/c.txt"
#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:')
#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:
#if prompt is #, upload the c.txt file line by line
  elif neverknow==0:
     child.sendline('configure terminal')
     filename = 'c.txt' 
     with open(filename) as file_object:
       lines = file_object.readlines()
       for line in lines:
         line = line #+ "\015"

#this script can be run with the following command:
#python3 8002 myconsoleserver

if __name__ == "__main__":
  ip = sys.argv[1] 
  port = sys.argv[2]
  consoleserver = sys.argv[3]
  createall(ip, port, consoleserver)


Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:


Komentujesz korzystając z konta Wyloguj /  Zmień )

Zdjęcie na Google

Komentujesz korzystając z konta Google. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

Połączenie z %s