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變量。此外,根據您的需求,您可以在連接后執行其他命令。