简体   繁体   English

如何将python套接字管道传输到stdin / stdout

[英]How to pipe python socket to a stdin/stdout

I need to write an app to contact to a server. 我需要编写一个与服务器联系的应用程序。 After sending a few messages it should allow the user to interact with the server by sending command and receive result. 发送一些消息后,它应该允许用户通过发送命令与服务器进行交互并接收结果。

How should I pipe my current socket so that the user can interact with the server without the need of reading input and writing output from/to stdin/stdout ? 我应该如何通过管道传输当前套接字,以便用户可以与服务器交互,而无需从stdin / stdout读取输入或向stdin / stdout写入输出?

You mean like using netcat? 您是说喜欢使用netcat?

cat initial_command_file - | nc host:port

the answer is, something needs to read and write. 答案是, 有些东西需要读写。 In the sample shell script above, cat reads from two sources in sequence, and writes to a single pipe; 在上面的示例Shell脚本中, cat依次从两个源读取数据,并写入单个管道。 nc reads from that pipe and writes to a socket, but also reads from the socket and writes to its stdout . nc从该管道读取并写入套接字,但也从套接字读取并写入其stdout

So there will always be some reading and writing going on ... however, you can structure your code so that doesn't intrude into the comms logic. 因此, 总会有一些读写过程。但是,您可以构造代码,以免干扰comms逻辑。

For example, you use itertools.chain to create an input iterator that behaves similarly to cat , so your TCP-facing code can take a single input iterable: 例如,您使用itertools.chain创建一个行为类似于cat的输入迭代器,因此面向TCP的代码可以采用单个可迭代输入:

def netcat(input, output, remote):
    """trivial example for 1:1 request-response protocol"""
    for request in input:
        remote.write(request)
        response = remote.read()
        output.write(response)

handshake = ['connect', 'initial', 'handshake', 'stuff']
cat = itertools.chain(handshake, sys.stdin)

server = ('localhost', 9000)
netcat(cat, sys.stdout, socket.create_connection(server))

You probably want something like pexpect . 您可能想要像pexpect之类的东西 Basically you'd create a spawn object that initates the connection (eg via ssh ) then use that object's expect() and sendline() methods to issue the commands you want to send at the prompts. 基本上你想创建一个spawn是initates连接对象(例如,通过ssh ),然后使用该对象的expect()sendline()方法来发出要在提示发送命令。 Then you can use the interact() method to turn control over to the user. 然后,您可以使用interact()方法将控制权移交给用户。

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

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