python有第三方telnet模块,这样就不用登录到每台交换机上查询。
这里有个连接盛科交换机的example:
#!/usrbin/env python import telnetlib def do_telnet(Host, password, commands): tn = telnetlib.Telnet(Host, port=23, timeout=10) # 初始化一个tn实例 # tn.set_debuglevel(2) # 设置debug级别 tn.read_until(‘Password: ‘) # 输入密码 tn.write(password + ‘\n‘) tn.read_until("#") # 输入你要查询的命令 for command in commands: tn.write(command + "\n") time.sleep(5) # tn.write("quit\n") res = tn.read_very_eager() print res tn.close() if __name__==‘__main__‘: Host = ‘172.16.100.****‘ password = ‘9*****‘ commands = [‘show interface trunk‘] do_telnet(Host, password, commands) 执行结果: [[email protected] home]# python test.py show interface trunk Port Encapsulation Status Native VLAN -------------------------------------------------- eth-0-1 802.1q trunking 100 eth-0-2 802.1q trunking 100 eth-0-3 802.1q trunking 100 eth-0-4 802.1q trunking 100 eth-0-5 802.1q trunking 100 eth-0-6 802.1q trunking 100 eth-0-9 802.1q trunking 100 eth-0-48 802.1q trunking 100 Port VLANs is allowed on trunk ------------------------------------------------------------------- eth-0-1 100,102-130 eth-0-2 100,102-130 eth-0-3 100,102-130 eth-0-4 100,102-130 eth-0-5 100,102-130 eth-0-6 100,102-130 eth-0-9 100,102-130 eth-0-48 1,99-130 inter-openstack#
这里需要注意的是,关于telnetlib模块中几种read方法的区别:
参考链接:https://docs.python.org/2/library/telnetlib.html
http://python.u85.us/viewnews-359.html
时间: 2024-11-13 09:36:59