I created a script that parses a directory, strips the ".txt" extension off the file, telnet & log on to the device (the filename is the device name), opens the associated ".txt" file, sends all the commands containted in the file to the device and then executes some commands to save the changes. I'm not very experienced with programming, writing Python, using functions, OOP, etc., therefore I'd like to know if there is a better way to do this:
#
# This scripts obtains a directory listing, strips the extensions and telnets to the
# device (which is the filename in the directory). Then it writes the commands in the
# file to the device, saves config and writes it back to SYSMAN. It can be run using:
# python send_file4.py
#
# Note: "os" is imported for future functionality.
#
# by: TCDH
# on: 10/17/05
# revised: 10/18/05 TCDH - Added logic to check for offline devices and sign-on failures.
#
import telnetlib, re, os, string
dirpath = (r"c:\temp\sun")
dirlist = os.listdir(dirpath)
wpath = (r"c:\temp\py\send_file4.out")
output = file(wpath, "w")
for i in dirlist:
try:
tn = telnetlib.Telnet(i.rstrip(".txt"))
tn.read_until("Username: ")
except:
output.write(i.rstrip(".txt") + ": not responding.\n")
continue
tn.write("cworks\n")
(index, match, read) = tn.expect(["Password: "], 5)
if not match:
output.write(i.rstrip(".txt") + ": sign-on failure.\n")
continue
tn.write("<password_here>\n")
tn.write("conf t\n")
rpath = (dirpath + "\\" + i)
input = file(rpath, "r")
for lines in file(rpath):
tn.write(input.readline())
tn.write("end\n") # exit config mode
tn.write("wr\n") # save config
tn.read_until("#")
tn.write("wr net\n") #write config to TFTP
tn.read_until("]? ")
tn.write("172.16.250.22\n") # TFTP server address
tn.read_until("]? ")
tn.write("\n")
tn.read_until("[confirm]")
tn.write("\n")
tn.read_until("#")
tn.write("exit\n") # end session
This script needs to be able to log which device is offline and if there was a sign-on problem. For the first exception (device offline), I had to use try-except because tn.expect wouldn't work. However, I had to use tn.expect on the second exception (sign-on problem) because try-except wouldn't work there.
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor