2015-11-13 89 views
1

我正在尝试编写一个简单的telnet客户端,它只是使用telnet在远程盒子上运行单个命令。这需要在asyncio上运行,因为在该框架下同时监视其他任务。如何使用telnetlib3在python asyncio上运行远程命令

我得到了它几乎工作,用下面的代码,我从telnet-client扭捏作为telnetlib3库的一部分;除非它不返回。我很难确定这个protocol.waiter_closed是什么。

在任何情况下,我该如何调整此代码,以便它在远程端处理完命令后返回?

感谢

#!/usr/bin/env python3 
import logging 

import asyncio 
import telnetlib3 

# just to check that connection is thrown away 
class MyClient(telnetlib3.TelnetClient): 
    def connection_lost(self, *args): 
     print("connection lost on client {} - args={}".format(self, args)) 

@asyncio.coroutine 
def register_telnet_command(loop, Client, host, port, command): 
    transport, protocol = yield from loop.create_connection(Client, host, port) 

    print("{} async connection OK for command {}".format(host, command)) 

    def send_command(): 
     EOF = chr(4) 
     EOL = '\n' 
     # adding newline and end-of-file for this simple example 
     command_line = command + EOL + EOF 
     protocol.stream.write(protocol.shell.encode(command_line)) 

    # one shot invokation of the command 
    loop.call_soon(send_command) 
    # what does this do exactly ? 
    yield from protocol.waiter_closed 

port = 23 
hostname = "fit01" 

def main(): 
    def ClientFactory(): 
     return MyClient(encoding='utf-8', shell = telnetlib3.TerminalShell) 
    # create as many clients as we have hosts 

    loop = asyncio.get_event_loop() 
    loop.run_until_complete(
     register_telnet_command(loop, log, ClientFactory, 
           host = hostname, port = port, 
           command = "id")) 
    return 0 

main() 
+0

我想通了;重新定义'connection_lost'是一个非常糟糕的主意;这个方法负责填充'waiter_closed'属性。 – user5417363

回答

0

对不起,我的错,不从telnetlib3.connection_lost调用代码重新定义close_connection是一个坏主意,因为这是填充waiter_closed的代码。

我应该做的

class MyClient(telnetlib3.TelnetClient): 
    def connection_lost(self, *args): 
     print("connection lost on client {} - args={}".format(self, args)) 
     super().connection_lost(*args) 
相关问题