为什么这个Python代码只在一个端口上侦听?

时间:2013-11-08 14:00:42

标签: python sockets tcp listen

我正在尝试编写一段可以侦听两个不同端口的python代码。在Java中,我可以通过启动一个在每个端口上监听的线程来做到这一点,但它看起来确实像在Python中那样工作。我到目前为止的代码是:

from socket import *
import thread
from datetime import datetime

BUFF_SIZE = 1024
HOST = '' # listen on all interfaces
PORT_FTP = 5000 # port to listen on
PORT_ESMTP = 5001 # TODO: change to real port

# HEADERS #################################
headerFtpGuild = "220-GuildFTPd FTP Server (c) 1997-2002\r\n220-Version 0.999.14\r\n"
headerFtpCerberus = "220-Cerberus FTP Server Personal Edition\r\n220-UNREGISTERED\r\n";
headerESMTP = "220 ESMTP service ready\r\n250\x20ok\r\n";
###########################################

def handlerFTP(clientsock,addr):
    try:
        clientsock.send(headerFtpGuild)
        print '[*] Faked FTP banner'
        clientsock.close()
    except:
        pass

def handlerESMTP(clientsock,addr):
    try:
        clientsock.send(headerESMTP)
        print '[*] Faked ESMTP banner'
        clientsock.close()
    except:
        pass

def getTime():
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')


def listenFTP():
    ADDR = (HOST, PORT_FTP)
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serversock.bind(ADDR)
    serversock.listen(1)

    print '[*]FTP'

    while 1:
        clientsock, addr = serversock.accept()
        print '[ ] possible probe detected from:', addr[0], '@', getTime()
        thread.start_new_thread(handlerFTP, (clientsock, addr))

def listenESMTP():
    ADDR = (HOST, PORT_ESMTP)
    serversock1 = socket(AF_INET, SOCK_STREAM)
    serversock1.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serversock1.bind(ADDR)
    serversock1.listen(1)

    print '[*]ESMTP'

    while 1:
        clientsock1, addr1 = serversock1.accept()
        print '[ ] possible probe detected from:', addr1[0], '@', getTime()
        thread.start_new_thread(handlerESMTP, (clientsock1, addr1))

if __name__=='__main__':
    listenFTP()
    listenESMTP()

似乎只有listenFTP()正在被执行。我该怎么办?提前谢谢。

2 个答案:

答案 0 :(得分:1)

我认为你基本上没有在你的python代码中使用线程。您启动FTP侦听器,当然,此方法将永久执行 。您可以添加具有thread.start_new_thread功能的quickfix,如下所示:

if __name__=='__main__':
    import thread
    thread.start_new_thread(listenFTP)
    thread.start_new_thread(listenESMTP)

希望这有帮助!

答案 1 :(得分:0)

尝试将listenFTP()listenESMTP()置于无限循环或while循环中。