使用pexpect从虚拟机中侦听端口

时间:2010-09-09 21:02:14

标签: python tcp port tcplistener pexpect

我正在尝试在python中创建一个tcplistener(如果需要,使用pexpect)来监听来自windows xp主机上的virtualbox中的Ubuntu的tcp连接。如果你们中的一位能指出我正确的方向,我真的很感激。谢谢。

P.S:我在该领域的经验有限,欢迎任何帮助。

1 个答案:

答案 0 :(得分:1)

Python已经在标准库中提供了一个简单的套接字服务器,它恰当地命名为SocketServer。如果您想要的只是一个基本的倾听者,请查看此example straight from the documentation

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "%s wrote:" % self.client_address[0]
        print self.data
        # just send back the same data, but upper-cased
        self.request.send(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()