python之端口扫描

使用python脚本进行tcp全连接测试

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
from socket import *
from threading import Thread
import optparse

def connPort(ipAddr,port):
setdefaulttimeout(1)
try:
conn = socket(AF_INET,SOCK_STREAM)
conn.connect((ipAddr,port))
conn.send(b"python\r\n")
print("[+] %d/tcp open"%port)
results = conn.recv(100)

print("[+] %s"%str(results,encoding="utf-8"))
except Exception as e:
#print(e)
pass

if __name__ == "__main__":
parser = optparse.OptionParser("python portscan.py -H <host ip addr> -p <port>")
parser.add_option("-H",dest='hAddr',type='string',help='specify ip addr')
parser.add_option("-p",dest='port',type='string',help='specify port')
(options,args) = parser.parse_args()
if options.hAddr==None or options.port==None:
print(parser.usage)
else:
ports = str(options.port).split(",")
for i in ports:
t = Thread(target=connPort,args=(options.hAddr,int(i)))
t.start()

使用python-nmap进行端口扫描

由于扫描方式还有很多,如syn,tcp null scan,tcp fin scan,tcp xmas scan等,所以完全自己实现多种扫描方式太麻烦。

可以直接使用python-nmap工具进行扫描,前提是将nmap添加至环境变量中

1
2
3
import nmap
nmScan = nmap.PortScanner()
nmScan.scan("127.0.0.1",80)