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系統,您可能需要稍微修改代碼。