阅读量:3
Python 的 Telnet 库允许你通过 Telnet 协议连接到远程设备。要同时连接到多台设备,你可以使用多线程或多进程。以下是一个使用多线程的示例:
import telnetlib
import threading
# 定义一个用于连接设备的函数
def connect_to_device(ip, port):
tn = telnetlib.Telnet(ip, port)
# 这里可以添加与设备进行交互的代码
tn.write(b'your_command_here\n')
response = tn.read_until(b'end_of_response', timeout=5)
print(f'Response from {ip}:{port}: {response.decode()}')
tn.close()
# 设备列表和端口
devices = [
{'ip': '192.168.1.1', 'port': 23},
{'ip': '192.168.1.2', 'port': 23},
{'ip': '192.168.1.3', 'port': 23}
]
# 创建线程列表
threads = []
# 为每个设备创建一个线程并启动
for device in devices:
t = threading.Thread(target=connect_to_device, args=(device['ip'], device['port']))
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()
这个示例中,我们首先定义了一个名为 connect_to_device 的函数,该函数接受设备的 IP 地址和端口作为参数。然后,我们为每个设备创建一个线程并启动它。最后,我们等待所有线程完成。
请注意,这个示例仅用于演示目的。在实际应用中,你可能需要根据你的需求对代码进行调整,例如添加异常处理、身份验证等。
以上就是关于“python telnet命令能连多台设备”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm