Python Telnet库允许您通过Telnet协议与远程设备进行交互
pip install telnetlib
接下来,您可以使用以下代码示例连接到远程Telnet服务器:
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") # 执行命令(例如,显示当前工作目录) tn.write(b"ls\n") output = tn.read_until(b"$ ").decode("ascii") print(output) # 退出Telnet会话 tn.write(b"exit\n") tn.close()
请注意,您需要根据实际情况替换ip_address
、port
、username
和password
变量。此外,根据您的需求,您可以在连接后执行其他命令。