Python Telnet库允许您通过Telnet协议与远程设备进行交互
pip install telnetlib
接下来,您可以使用以下示例代码连接到远程设备并执行命令:
import telnetlib # 设置Telnet服务器的IP地址和端口 ip_address = "192.168.1.1" port = 23 # 创建一个Telnet对象 tn = telnetlib.Telnet(ip_address, port) # 登录到远程设备(如果需要) username = "your_username" password = "your_password" tn.read_until(b"login: ") tn.write(username.encode("ascii") + b"\n") tn.read_until(b"Password: ") tn.write(password.encode("ascii") + b"\n") # 执行命令并获取输出 command = "your_command" tn.write(command.encode("ascii") + b"\n") output = tn.read_until(b"$ ").decode("ascii") print(output) # 关闭连接 tn.close()
请将ip_address
、port
、username
、password
和command
替换为您要连接的远程设备和要执行的命令。注意,这个示例适用于类Unix系统,如果您使用的是Windows系统,您可能需要稍微修改代码。