简体   繁体   English

从python中的telnet会话进行Telnet

[英]Telnet from telnet session in python

Is it possible to telnet to a server and from there telnet to another server in python? 可以通过telnet到服务器,然后从telnet到python中的另一台服务器吗? Since there is a controller which I telnet into using a username and password, and from the controller command line I need to login as root to run linux command. 由于有一个控制器,我使用用户名和密码远程登录到该控制器,并且需要从该控制器的命令行登录才能运行linux命令。 How would I do that using python? 我将如何使用python做到这一点?

I use the telentlib to login into router controller but from the router controller I need to log in again to get into shell. 我使用telentlib登录到路由器控制器,但是需要从路由器控制器重新登录才能进入Shell。 Is this possible using python? 使用python可以吗?

Thanks! 谢谢!

Just checked it with the hardware I have in hand & telnetlib. 只需使用我手头和telnetlib的硬件进行检查。 Saw no problem. 没问题。 When you are connected to the first device just send all the necessary commands using telnet.write('cmd') . 当您连接到第一台设备时,只需使用telnet.write('cmd')发送所有必要的命令。 It may be sudo su\\n , telnet 192.168.0.2\\n or whatever else. 可能是sudo su\\ntelnet 192.168.0.2\\n或其他任何东西。 Telnetlib keeps in mind only its own telnet connection, all secondary connections are handled by the corresponding controllers. Telnetlib仅记住其自己的telnet连接,所有辅助连接均由相应的控制器处理。

Have you looked into using expect (there should be a python binding); 您是否研究过使用Expect(应该有python绑定); basically, what I think you want to do is: 基本上,我认为您想做的是:

  1. From your python script, use telnetlib to connect to server A (pass in username/password). 在python脚本中,使用telnetlib连接到服务器A(输入用户名/密码)。
  2. Within this "socket", send the remaining commands, eg "telnet serverB" and use expect (or some other mechanism) to check that you get back the expected "User:" prompt; 在此“套接字”中,发送其余命令,例如“ telnet serverB”,并使用Expect(或其他某种机制)检查您是否获得了预期的“ User:”提示; if so, send user and then password and then whatever commands, and otherwise handle errors. 如果是这样,请先发送用户,然后发送密码,再发送任何命令,否则将处理错误。

This should be very much doable and is fairly common with older stuff that doesn't support a cleaner API. 这应该是非常可行的,并且对于不支持更清洁API的较旧版本也很常见。

You can use write() to issue the sudo command. 您可以使用write()发出sudo命令。

tn.write("sudo\n")

You could also use read_until() to help with the credentials. 您还可以使用read_until()来帮助获得凭据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM