关于缓冲区溢出:python telnet服务器崩溃

python telnet server crash

每当我的客户机通过telnet连接到我的服务器时

1
telnet myip 43

当客户端在自己的计算机上连续点击ctrl+c时,会导致telnet服务器崩溃…如何阻止这种情况?还有没有可能我的服务器受到缓冲区溢出的攻击?

这是我的脚本(非常基本的脚本)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python
import sys
import socket
import urllib2
def main():
    s = socket.socket()         # Create a socket object
    host = ''
    BUFFER_SIZE = 2048
    port = 43                   # Reserve a port for your service.
    s.bind((host, port))        # Bind to the port
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.listen(120)               # Now wait for client connection.
    while True:
        data = ''
        print 'waiting for connection...'
        c, addr = s.accept()     # Establish connection with client.
        print 'Got connection from', addr
        data = c.recv(BUFFER_SIZE)
        print 'requested website: '+data
        print x
        c.send(x)
        c.close()                # Close the connection
if __name__ == '__main__':
    main()


试试这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import string
valid_chars ="-_.() %s%s" % (string.ascii_letters, string.digits)

[...]

        data = c.recv(BUFFER_SIZE)
        data=''.join(c for c in data if c in valid_chars)
        print 'requested website: '+data
        if len(data)>0:
            try:
                urllib2.urlopen('localhost:2020/?id='+data ).read()
                print x
                c.send(x)
            except:
                pass
        c.close()                # Close the connection

编辑valid_chars以仅允许ID参数使用字符。