【问题标题】:Reading output with telnetlib in realtime使用 telnetlib 实时读取输出
【发布时间】:2012-04-24 22:57:07
【问题描述】:

我正在使用 Python 的 telnetlib 远程登录到某台机器并执行一些命令,我​​想获得这些命令的输出。

那么,目前的情况是-

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

tn.write("command1")
tn.write("command2")
tn.write("command3")
tn.write("command4")
tn.write("exit\n")

sess_op = tn.read_all()
print sess_op
#here I get the whole output

现在,我可以在 sess_op 中获取所有合并后的输出。

但是,我想要的是在 command1 执行之后和 command2 执行之前立即获取它的输出,就好像我在另一台机器的 shell 中工作一样,如下所示 -

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

tn.write("command1")
#here I want to get the output for command1
tn.write("command2")
#here I want to get the output for command2
tn.write("command3")
tn.write("command4")
tn.write("exit\n")

sess_op = tn.read_all()
print sess_op

【问题讨论】:

    标签: python telnetlib


    【解决方案1】:

    您必须参考telnetlib模块here的文档。
    试试这个 -

    tn = telnetlib.Telnet(HOST)
    tn.read_until("login: ")
    tn.write(user + "\n")
    if password:
        tn.read_until("Password: ")
        tn.write(password + "\n")
    
    tn.write("command1")
    print tn.read_eager()
    tn.write("command2")
    print tn.read_eager()
    tn.write("command3")
    print tn.read_eager()
    tn.write("command4")
    print tn.read_eager()
    tn.write("exit\n")
    
    sess_op = tn.read_all()
    print sess_op
    

    【讨论】:

      【解决方案2】:

      我在使用 telnetlib 时遇到了类似的情况。

      然后我意识到每个命令末尾缺少回车和换行,并对所有命令执行了 read_eager。像这样的:

       tn = telnetlib.Telnet(HOST, PORT)
       tn.read_until("login: ")
       tn.write(user + "\r\n")
       tn.read_until("password: ")
       tn.write(password + "\r\n")
      
       tn.write("command1\r\n")
       ret1 = tn.read_eager()
       print ret1 #or use however you want
       tn.write("command2\r\n")
       print tn.read_eager()
       ... and so on
      

      而不是只写如下命令:

       tn.write("command1")
       print tn.read_eager()
      

      如果它只对您使用“\n”,则仅添加一个“\n”可能就足够了,而不是“\r\n”,但就我而言,我必须使用“\r\n”并且我还没试过只换一条线。

      【讨论】:

      • 它在我的情况下不起作用,只显示'_',我只是给出'显示版本'命令
      【解决方案3】:

      我也遇到了 read_very_eager() 函数没有显示任何数据的相同问题。从一些帖子中得到了该命令需要一些时间来执行的想法。所以使用了 time.sleep() 函数。

      代码片段:

      tn.write(b"sh ip rou\r\n")
      time.sleep(10)
      data9 = tn.read_very_eager()
      print(data9)
      

      【讨论】:

        猜你喜欢
        • 2019-09-06
        • 1970-01-01
        • 2022-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-11
        • 1970-01-01
        相关资源
        最近更新 更多