为什么它会像这样超时?

时间:2017-12-06 11:10:03

标签: python python-3.x python-2.7 tcp proxy

我正在尝试构建一个发送和接收数据的TCP代理脚本,我设法让它听,但它似乎没有正确连接...我的代码看起来对我来说正确检查python文档后(我试图在python 2.7和3.6中运行它)我得到这个超时消息:

输出:

anon@kali:~/Desktop/python scripts$ sudo python TCP\ proxy.py 127.0.0.1 21 ftp.target.ca 21 True
[*] Listening on 127.0.0.1:21d
[==>] Received incoming connection from 127.0.0.1:44806d
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "TCP proxy.py", line 60, in proxy_handler
    remote_socket.connect((remote_host,remote_port))
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 110] Connection timed out

我查看了文件" /usr/lib/python2.7/socket.py"但是当我将它与python docs和我的脚本进行比较时,我无法理解我正在寻找的内容

我的代码:

# import the modules
import sys
import socket
import threading

#define the server
def server_loop(local_host,local_port,remote_host,remote_port,receive_first):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        server.bind((local_host, local_port))
        server.listen(5)
        print ("[*] Listening on %s:%sd" % (local_host, local_port))
    except:
        print("[!!] Failed to listen on %s:%sd" % (local_host,local_port))
        print ("[!!] Check for others listening sockets or correct permissions")
        sys.exit(0)

    while True:
        client_socket, addr = server.accept()

        #print out the local connection information
        print ("[==>] Received incoming connection from %s:%sd" % (addr[0],addr[1]))

        #start a thread to talk to the remote host
        proxy_thread = threading.Thread(target=proxy_handler,args=(client_socket,remote_host,remote_port,receive_first))

        proxy_thread.start()
    else:
        print ("something went wrong")

def main():
    #no fancy command-line parasing here
    if len(sys.argv[1:]) !=5:
        print ("Usage: ./TCP proxy.py [localhost] [localport] [remotehost] [remoteport] [receive_first]")
        print("Example: ./TCP proxy.py 127.0.0.1 9000 10.12.132.1 9000 True")

    #set up local listening parameters
    local_host = sys.argv[1]
    local_port = int(sys.argv[2])

    #set up remote target
    remote_host = sys.argv[3]
    remote_port = int(sys.argv[4])

    #this tells proxy to connect and receive data before sending to remote host
    receive_first = sys.argv[5]

    if "True" in receive_first:
        receive_first = True
    else:
        receive_first = False

    #now spin up our listening socket
    server_loop(local_host,local_port,remote_host,remote_port,receive_first)

def proxy_handler(client_socket, remote_host, remote_port, receive_first):
    #connect to the remote host
    remote_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    remote_socket.connect((remote_host,remote_port))

    #receive data from the remote end if necessary
    if receive_first:
        remote_buffer = receive_from(remote_socket)
        hexdump(remote_buffer)

        #send it to the repsonse handler
        remote_buffer = respsonse_handler(remote_buffer)

        #if data is able to be sent to local client, send it
        if len(remote_buffer):
            print ("[<==] Sending %d bytes to localhost." % len(remote_buffer))
            client_socket.send(remote_buffer)
    #now loop and read from local,sent to remote,send to local,rinse/wash/repeat
    while True:
        #read from local host
        local_buffer = receive_from(client_socket)

        if len(local_buffer):
            print ("[==>] Received %d bytes from localhost." % len(local_buffer))

            #send it to request handler
            local_buffer = request_handler(local_buffer)

            #send data to remote host
            remote_socket.send(local_buffer)
            print ("[==>] Sent to remote.")

        #receive back response
        remote_buffer = receive_from(remote_socket)
        if len(remote_buffer):
            print ("[<==] Received %d bytes from remote." % len(remote_buffer))
            hexdump(remote_buffer)

            #send response to handler
            remote_buffer = response_handler(remote_buffer)

            #send response to local socket
            client_socket.send(remote_buffer)

            print ("[<==] Sent to localhost.")

        #if no data left on either side, close connection
        if not len(local_buffer) or not len(remote_buffer):
            client_socket.close()
            remote_socket.close()
            print ("[*] No more data, closing connections.")

            break

#this is a pretty hex dumping function taken from the comments of http://code.activestate.com/recipes/142812-hex-dumper/
def hexdump(src, length=16):
    result = []
    digits = 4 if isinstance(src,unicode) else 2
    for i in xrange(0,len(src), length):
        s = src[i:i+length]
        hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s])
        text = b' '.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
        result.append( b"%04X %-*s %s" % (i, length*(digits + 1), hexa, text) )
    print (b'/n'.join(result))

def receive_from(connection):
    buffer = ""

    #set a 2 second timeout; depending on your target this may need to be adjusted
    connection.settimeout(2)

    try:
        #keep reading the buffer until no more data is there or it times out
        while True:
            data = connection.recv(4096)

            if not data:
                break
            buffer += data
    except:
        pass
    return buffer

#modify any requested destined for the remote host
def request_handler(buffer):
    #perform packet modifications
    return buffer

#modify any responses destined for the local host
def response_handler(buffer):
    #perform packet modifications
    return buffer

main()

我尝试过不同的ftp服务器/网站等,但得到相同的结果,我的代码出错了?任何意见或方向都将不胜感激。

1 个答案:

答案 0 :(得分:0)

好吧事实证明我的脚本很好只是我运行的ftp服务器不是哈哈 这是最终输出:

anon@kali:~/Desktop/python scripts$ sudo python TCP\ proxy.py 127.0.0.1 21 ftp.uconn.edu 21 True
[*] Listening on 127.0.0.1:21d
[==>] Received incoming connection from 127.0.0.1:51532d
0000 32 32 30 20 50 72 6F 46 54 50 44 20 31 2E 32 2E  2 2 0   P r o F T P D   1 . 2 ./n0010 31 30 20 53 65 72 76 65 72 20 28 66 74 70 2E 75  1 0   S e r v e r   ( f t p . u/n0020 63 6F 6E 6E 2E 65 64 75 29 20 5B 31 33 37 2E 39  c o n n . e d u )   [ 1 3 7 . 9/n0030 39 2E 32 36 2E 35 32 5D 0D 0A                    9 . 2 6 . 5 2 ] . .
[<==] Sending 58 bytes to localhost.
[==>] Received 353 bytes from localhost.
[==>] Sent to remote.
[<==] Received 337 bytes from remote.