,可以通过以下步骤实现:
import telnetlib
import csv
devices = [
{'ip': '192.168.1.1', 'username': 'admin', 'password': 'password1'},
{'ip': '192.168.1.2', 'username': 'admin', 'password': 'password2'},
{'ip': '192.168.1.3', 'username': 'admin', 'password': 'password3'}
]
def execute_telnet_command(ip, username, password, command):
try:
# 连接设备
tn = telnetlib.Telnet(ip)
tn.read_until(b"Username: ")
tn.write(username.encode('ascii') + b"\n")
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
# 执行telnet命令
tn.write(command.encode('ascii') + b"\n")
output = tn.read_all().decode('ascii')
# 关闭telnet连接
tn.close()
return output
except Exception as e:
return str(e)
command = "show interfaces"
output_file = "output.csv"
with open(output_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Device IP', 'Command Output'])
for device in devices:
ip = device['ip']
username = device['username']
password = device['password']
output = execute_telnet_command(ip, username, password, command)
writer.writerow([ip, output])
以上代码会依次连接每个设备,执行telnet命令,并将设备IP和命令输出保存到csv文件中。你可以根据实际情况修改设备的IP地址、用户名、密码、要执行的telnet命令和保存输出的文件路径。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云