Python 套接字监听 [英] Python Socket Listening

查看:64
本文介绍了Python 套接字监听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面提到的所有内容都在使用 python 2.7 的 Windows 机器上

你好

我目前正在尝试在套接字上侦听远程程序发送的数据.然后将此数据打印到屏幕上,并请求用户输入,然后将其返回到远程程序.在测试中,我已经能够让远程程序向我发送一个命令行程序菜单(cmd、ipconfig、whoami、ftp),然后我的程序返回一个数字作为菜单选项的选择.

I am currently attempting to listen on a socket for data send by a remote program. This data is then printed to the screen and user input is requested that is then returned to remote program. In testing I have been able to have the remote program send me a menu of command line programs (cmd, ipconfig, whoami, ftp) and then my program returns with a number as a selection of the menu option.

远程程序接收我的响应并发送所选命令的输出.ipconfig 和 whoami 工作完美,但 cmd 和 ftp 只返回终端的输出一次.(即,我可以在 FTP 程序中输入一个命令并将该命令也发送到远程程序,然后我再也没有收到回复)

The remote program receives my response and sends the output of the selected command. ipconfig and whoami work perfectly, but cmd and ftp only returns the output of the terminal once. (I.E. I can enter one command into the FTP program and send that too the remote program before I never hear back)

我的代码失败的部分是if ready[0]: 在第一次对话之后永远不会第二次准备好.

The part of my code that fails is that if ready[0]: never becomes ready a second time after the first conversation.

我知道远程程序运行正常,因为我可以使用 netcat 代替我的代码并无限期地操作 cmd 终端.

I know the remote program is functioning correctly as I can use netcat to act in lieu of my code and operate the cmd terminal indefinitely.

我如何正确实现可以解释这种类型连接的 python 套接字侦听器?

How do I go about properly implementing a python socket listener that can account for this type of connection?

我的程序"的全部内容:

My "program" in its entirety:

import socket, sys, struct, time, select

host = ''
port = 50000
connectionSevered=0

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print 'Failed to create socket'
    sys.exit()
print '[+] Listening for connections on port '+str(port)+'.'

s.bind((host,port))
s.listen(5)         

def recvall(the_socket,timeout=2):
    global connectionSevered
    data='';          # Data found by recv
    total_data=[];    # Finally list of everything

    s.setblocking(0)  #make socket non blocking
    begin=time.time() #beginning time

    while 1:
        ready = select.select([client], [], [], .2)
        if time.time()-begin > timeout:
            print 'Timeout reached'
            #Leave loop, timer has reached its threshold
            break
        if ready[0]:
            print 'In ready loop!'
            try:
                data = client.recv(4096)    #attempt to fetch data
                if data:
                    begin=time.time()       #reset timeout timer
                    total_data.append(data) 
                    data='';
            except socket.error:
                print '[+] Lost connection to client. Printing buffer...'
                connectionSevered=1   # Let main loop know connection has errored
                pass
        time.sleep(1)
    #join all parts to make final string
    return ''.join(total_data)

client, address = s.accept()
print '[+] Client connected!'

while (connectionSevered==0): # While connection hasn't errored
    print "connectionSevered="+str(connectionSevered) # DEBUG
    recvall(s)
    response = raw_input()                  #take user input
    client.sendto(response)                   #send input
client.close(0)

如果您需要更多信息,请告诉我,任何帮助将不胜感激,我对此很陌生并且渴望学习.

Please let me know if you need more information, any help would be greatly appreciated, I am very new to this and eager to learn.

推荐答案

玩了一段时间终于让它在本地使用 python 2.7 的 telnet 会话工作得很好.

Playing around with this for a while finally got it working nice with a telnet session locally using python 2.7.

它的作用是设置一个线程,当客户端连接侦听客户端内容时运行该线程.

What it does is it sets up a thread that runs when the client connects listening for client stuff.

当客户端发送一个返回值时(如果你与 Linux 系统交互,\r\n"可能需要改变它?)消息被打印到服务器,而如果有原始输入,则会发生这种情况服务器端这将被发送到客户端:

When the client sends a return ("\r\n" might have to change that if your interacting with a Linux system?) the message gets printed to the server, while this is happening if there is a raw input at the server side this will get sent to the client:

import socket
import threading
host = ''
port = 50000
connectionSevered=0

class client(threading.Thread):
    def __init__(self, conn):
        super(client, self).__init__()
        self.conn = conn
        self.data = ""
    def run(self):
        while True:
            self.data = self.data + self.conn.recv(1024)
            if self.data.endswith(u"\r\n"):
                print self.data
                self.data = ""

    def send_msg(self,msg):
        self.conn.send(msg)

    def close(self):
        self.conn.close()

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host,port))
    s.listen(5)
except socket.error:
    print 'Failed to create socket'
    sys.exit()

print '[+] Listening for connections on port: {0}'.format(port)


conn, address = s.accept()
c = client(conn)
c.start()
print '[+] Client connected: {0}'.format(address[0])
c.send_msg(u"\r\n")
print "connectionSevered:{0}".format(connectionSevered) 
while (connectionSevered==0):
    try:
        response = raw_input()  
        c.send_msg(response + u"\r\n")
    except:
        c.close()

以上答案不适用于多个连接.我已经通过添加另一个线程来进行连接来更新它.现在可以连接多个用户.

The above answer will not work for more than a single connection. I have updated it by adding another thread for taking connections. It it now possible to have more than a single user connect.

import socket
import threading
import sys
host = ''
port = 50000

class client(threading.Thread):
    def __init__(self, conn):
        super(client, self).__init__()
        self.conn = conn
        self.data = ""

    def run(self):
        while True:
            self.data = self.data + self.conn.recv(1024)
            if self.data.endswith(u"\r\n"):
                print self.data
                self.data = ""

    def send_msg(self,msg):
        self.conn.send(msg)

    def close(self):
        self.conn.close()

class connectionThread(threading.Thread):
    def __init__(self, host, port):
        super(connectionThread, self).__init__()
        try:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.s.bind((host,port))
            self.s.listen(5)
        except socket.error:
            print 'Failed to create socket'
            sys.exit()
        self.clients = []

    def run(self):
        while True:
            conn, address = self.s.accept()
            c = client(conn)
            c.start()
            c.send_msg(u"\r\n")
            self.clients.append(c)
            print '[+] Client connected: {0}'.format(address[0])



def main():
    get_conns = connectionThread(host, port)
    get_conns.start()
    while True:
        try:
            response = raw_input() 
            for c in get_conns.clients:
                c.send_msg(response + u"\r\n")
        except KeyboardInterrupt:
            sys.exit()

if __name__ == '__main__':
    main()

客户端无法看到其他客户端说什么,来自服务器的消息将发送到所有客户端.我将把它留给读者作为练习.

Clients are not able to see what other clients say, messages from the server will be sent to all clients. I will leave that as an exercise for the reader.

这篇关于Python 套接字监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆