Python实现对特定IP进行端口扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import telnetlib
from socket import *


# 使用socket
def socket_scan(host, port):
conn = socket(AF_INET, SOCK_STREAM)
conn.settimeout(2)
try:
conn.connect((host, port))
print(host, port, 'is available')
except Exception:
print(host, port, 'is not available')
finally:
conn.close()


# 使用telnet
def telnet_scan(host, port):
t = telnetlib.Telnet()
try:
t.open(host, port, timeout=2)
print(host, port, 'is available')
except Exception:
print(host, port, 'is not available')
finally:
t.close()


def main():
host = '127.0.0.1'
for port in range(80, 90):
socket_scan(host, port)


if __name__ == '__main__':
main()

运行结果:

1
2
3
4
5
6
7
8
9
10
127.0.0.1 80 is not available
127.0.0.1 81 is not available
127.0.0.1 82 is not available
127.0.0.1 83 is not available
127.0.0.1 84 is not available
127.0.0.1 85 is not available
127.0.0.1 86 is not available
127.0.0.1 87 is not available
127.0.0.1 88 is not available
127.0.0.1 89 is not available