我正在用python编写一个简单的脚本,用于telnet多台cisco交换机并添加vlans。我正在UNET实验室或最新的EVE-NG中测试我的脚本。当我使用FOR循环远程登录到多个交换机并从with in循环调用tn =telnetlib.Telnet(主机)时,它只远程登录到变量HOST中的最后一个值,即10.1.1.7
这是我的代码,
#!/usr/bin/env python
import getpass
import sys
import telnetlib
user = raw_input("Enter your telnet username: ")
password = getpass.getpass()
for h in range (2,8):
print "Telnet to host" + str(h)
HOST = "10.1.1." + str(h)
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("conf t\n")
for n in range (10,20):
tn.write("vlan " + str(n) + "\n")发布于 2018-01-31 20:54:25
下面的代码对我来说很有效。把你所有的in放在一个工作表中(IP_test.txt)。
import getpass
import sys
import telnetlib
user = "YOURUSER"
password = "YOURPASSWORD"
with open('IP_test.txt') as file:
for HOST in file:
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("Command1\n")
tn.write("Command2\n")
print(tn.read_all())发布于 2019-02-24 14:39:44
下面的python脚本适用于我的相同目的
#!/usr/bin/env python3
import getpass
import telnetlib
user = input("Enter your Telnet Username: ")
password = getpass.getpass()
DeviceList=open('/home/tt/Hostname.txt')
for HOST in DeviceList:
print('Configuring on Device : ',HOST)
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(b"enable\n")
EnPass=input('Enter your Enable password : ')
tn.write(EnPass.encode('ascii')+b'\n')
c=open('/home/tt/Commands.txt')
for i in c:
tn.write(i.encode('ascii')+b'\n')
c.close()
print(tn.read_all().decode('ascii'))
tn.close()
DeviceList.close()}https://stackoverflow.com/questions/43620591
复制相似问题