
在这篇文章中,我将使用 Python 和 Telnet 库登录到 IP 地址列表并执行一些命令并将输出发送到分隔的文本文件。
我的网络包含不同的供应商接入交换机,我需要从名为Ciscoswitch.txt的文件中的每个 IP 收集一些信息,例如产品编号或序列号。
注意:我不推荐使用Telnet,使用安全版本连接SSH等网络设备当然是最好的选择。
本文主要针对新手,从代表交换机或路由器的 IP 地址列表中收集信息,然后将代码的输出保存到每个 IP 地址的文本文件中。
直接上代码:
#!/usr/bin/env python
import getpass
import telnetlib
user = ("Admin")
password = ("password")
f = open ("C:\\Users\\user.name\\Desktop\\python\\Ciscoswitch.txt")
for line in f:
print "Getting Serials from Device " + (line)
HOST = line.strip()
tn = telnetlib.Telnet(HOST)
tn.read_until("Username:")
tn.write(user + "\n")
if password:
tn.read_until("Password:")
tn.write(password + "\n")
#this section is the switch configuration part
tn.write("enable \n")
tn.write("password\n")
tn.write("show version | section WS-C2960S-48LPS-L\n")
tn.write("exit\n")
#tn.write("exit\n")
readoutput = tn.read_all()
saveoutput = open("C:\\Users\\user.name\\Desktop\\serials\\switch" + HOST + ".txt", "w")
saveoutput.write(readoutput)
saveoutput.write("\n")
saveoutput.close
print tn.read_all()

文章转载自运维漫谈,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




