Open interactive telnet session from Python

半世苍凉 提交于 2019-12-02 08:14:45

问题


I am currently writing a small script in Python which reads some possible connections from a database (triple of node name, telnet IP address and telnet port) and present that to the user to choose to which node to connect.

After this selection I want to open an interactive Telnet session, which can be used by the user as if he had manually connected using the telnet command. Somehow I probably will need an escape sequence for that. It only needs to work on Linux OS.

I could just call telnet:

# Open shell
call(["telnet", selected_node['ip'], selected_node['port']])

That does work. However, I wonder if there might be a better solution.


回答1:


It's python, everything is included. There is a telnet module in the standard library.

import getpass
import telnetlib

HOST = "localhost"
user = input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until(b"login: ")
tn.write(user.encode('ascii') + b"\n")
if password:
    tn.read_until(b"Password: ")
    tn.write(password.encode('ascii') + b"\n")

tn.write(b"ls\n")
tn.write(b"exit\n")

print(tn.read_all().decode('ascii'))


来源:https://stackoverflow.com/questions/52264963/open-interactive-telnet-session-from-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!