|
[root@localhost shell]# cat main.py
#!/usr/bin/env python
#coding:utf-8
import sys
import os
import telnetlib
import timec
import threading
import datetime
now = datetime.datetime.now()
#Use for loop to telnet into each routers and execute commands
class Bakconf(threading.Thread):
def __init__(self,host,USERNAME,PASSWORD):
threading.Thread.__init__(self)
self.host=host
self.USERNAME=USERNAME
self.PASSWORD=PASSWORD
def run(self):
try:
tn = telnetlib.Telnet(self.host,port=23,timeout=5)
tn.set_debuglevel(5)
tn.read_until(b"Username:", timeout=2)
tn.write(self.USERNAME +b"\n")
tn.read_until(b"Password:", timeout=2)
tn.write(self.PASSWORD +b"\n")
tn.write(b"\n")
time.sleep(1)
tn.write("system-view"+"\n")
tn.write("user-interface vty 0 4"+"\n")
tn.write("screen-length 0"+"\n") #设置华为交换机命令不分布显示 cisco用terminal length 0
tn.write("quit"+"\n")
tn.write("quit"+"\n")
#######executive command in the txt file########
for COMMANDS in open(r'/networkbackup/shell/command.txt').readlines():
COMMAND = COMMANDS.strip('\n')
tn.write("%s\n" %COMMAND)
#######executive command in the txt file########
time.sleep(60) #设置延时,使下面命令有足够时间获取返回值,调整到适当时长
output = tn.read_very_eager() #获取返回值
tn.write("quit"+"\n")
filename = "/networkbackup/log/%s_%i-%.2i-%.2i_%.2i:%.2i:%.2i.log" % (self.host,now.year,now.month,now.day,now.hour,now.minute,now.second) #格式化文件名
time.sleep(.1)
fp = open(filename,"w")
fp.write(output)
fp.close()
except:
print "Can't connection %s"%self.host
return
def main():
USERNAME = "xxxxxxxxxxxxx" #交换机登录用户
PASSWORD = "xxxxxxxxxxxxx" #交换机登录密码
for host in open(r'/networkbackup/shell/sw.txt').readlines():
dsthost = host.strip('\n')
bakconf=Bakconf(dsthost, USERNAME, PASSWORD)
bakconf.start()
if __name__=="__main__":
main() |
|
|