【问题标题】:Python program to connect to console via telnetlib通过 telnetlib 连接到控制台的 Python 程序
【发布时间】:2013-09-08 17:02:06
【问题描述】:

您好,我是一名 tcl 人,我试图在 Python 中进行日常活动,以便熟悉一门新语言并将 Python 与 tcl 进行比较。没有人想要 tcl 程序了 :)

好的,所以我提供了一个代码来自动化这个典型的活动,我会做这个活动来清除控制台行。

$ telnet 172.28.247.240
Trying 172.28.247.240...
Escape character is '^]'.
User Access Verification
Password: 
labc-f18-ts>en
Password: 
labc-f18-ts#clear line 66
[confirm]
 [OK]

我的代码如下所示:

import getpass
import sys
import telnetlib

a_tuple = [ ('172.28.247.240' , 66)]
HOST = j[0]
user = "admin"
password = "1234"

tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")
    tn.read_until("labc-f18-ts>") 
    tn.write ("en" +"\n")
    tn.read_until("labc-f18-ts#")
    tn.write("clear line %d" %j[1])
    tn.write("exit\n")
    sess_op = tn.read_all()
    print sess_op

但我似乎没有得到任何输出,也不知道它是否真的清除了这些行 - 没有任何输出。请帮忙。

还有像pexpect 这样我应该使用的东西而不是我上面的东西吗?

【问题讨论】:

  • 您好,我已经修复了一些代码,因为 Python 依赖于空格,而您拥有的代码示例将无法运行。
  • 谢谢@Lego 但还是不行。

标签: python regex list python-2.7 telnet


【解决方案1】:
import telnetlib
# ...

a_tuple = [('172.28.247.240', 66)]
HOST = a_tuple[0] # do you mean to use 'a_tuple' instead of 'j'?
# ...

tn = telnetlib.Telnet(HOST[0], HOST[1]) # <-- pass the port, I don't think this accepts tuples of hostname/ip and port
# ...

您的部分代码是否应该与上面一样?

另外,我通常在发送命令时使用回车符 (\r) 而不是换行符 (\n)。有些主机对此很挑剔。

【讨论】:

  • HOST = ('172.28.247.240',66) 然后tn = telnetlib.Telnet(*Host) 会更流畅。
猜你喜欢
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 2020-03-18
  • 2014-08-13
  • 1970-01-01
相关资源
最近更新 更多