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 地址和端口作为参数。然后,我们为每个设备创建一个线程并启动它。最后,我们等待所有线程完成。
请注意,这个示例仅用于演示目的。在实际应用中,你可能需要根据你的需求对代码进行调整,例如添加异常处理、身份验证等。