Python 3, telnet automation

Mikael Hansen picture Mikael Hansen · Mar 11, 2015 · Viewed 16.7k times · Source

Im doing a project which is to collect certain information from a number of switches. Keep in mind im new to python and programming. What i want to do, is to: have a .txt file with the names of my switches.
Then loop through that list, and run a few commands, and save the output.

So far i have the following, which works on a single switch. As you can see in the comments, im trying to open my list.txt and loop through it, but my program wont work due to it being in a list (output: ['switchname-1'] ) How do i read my list.txt and get the variable as plain text, eg. switchname-1 without all the list chars ?

import sys
import telnetlib
import time

password = "password"
command = "show interface status"

##with open ("list.txt", "r") as devicelist:
##    hostlist = []
##    hostlist=devicelist.readlines()
##    print(hostlist)
hostlist= [ ("switchname-1","",""),]

for host in hostlist:

        cmd1 = "enable"
        tn = telnetlib.Telnet(host[0])

        time.sleep(2)
        tn.read_until(b"Password: ")
        tn.write(password.encode('ascii') + b"\n")
        time.sleep(2)
        tn.write(cmd1.encode('ascii') + b"\n")
        time.sleep(2)
        tn.write(password.encode('ascii') + b"\n")
        time.sleep(2)
        tn.write(command.encode('ascii') + b"\n")
        time.sleep(2)
        tn.write(b"\n")
        time.sleep(2)
        tn.write(b"\n")
        time.sleep(2)
        tn.write(b"exit\n")
        lastpost = tn.read_all().decode('ascii')
        op=open ("output.txt", "w")
        op.write(lastpost)  
        print("writing to file")
        op.close()
        print(lastpost)
        tn.close()

I am also trying to figure out if there is some kind of way to only print the last output from the switches instead of lastpost = tn.read_all().decode('ascii') which posts the whole telnet session ?

Answer

joel goldstick picture joel goldstick · Mar 11, 2015
with open ("list.txt", "r") as devicelist:
  hostlist = []
  hostlist=devicelist.readlines()
  for host in hostlist:
    print host
  print(hostlist)

But I think it would be better to write as function:

def host_list(file_name):
  with open(file_name, "r") as devicelist:
      yield devicelist.readline()

Then in your code below do:

  for h in host_list("your_file"):
     ...

The function will read the file a line at a time and return (yield) the text.