python 使用socket模块扫描端口
import socket,sys
ip = sys.argv[1] #接收参数
ports = sys.argv[2] #接收参数
def port_scan(ip,port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, port))
return True
except:
return False
finally:
s.close()
#执行test1.py 127.0.0.1 80,139,445
def get_ip(ip):
for port in ports:
if port_scan(ip,int(port)):
print('[+]' + ip + ':'+ str(port) + ' Open')
else:
print('[-]' + ip + ':' + str(port) + ' Close'
#执行python.exe test1.py 127.0.0.1 440-445
def get_ip_port(ip,start_port,end_port):
for port in range(int(start_port),int(end_port)+1):
if port_scan(ip,port):
print('[+]' + ip + ':'+ str(port) + ' Open')
else:
print('[-]' + ip + ':' + str(port) + ' Close')
if '-' in ports:
ports = ports.split('-')
get_ip_port(ip,ports[0],ports[1])
else:
ports = ports.split(',')
get_ip(ip)
执行结果
C:\Python385>python.exe test1.py 127.0.0.1 440-445
[-]127.0.0.1:440 Close
[-]127.0.0.1:441 Close
[-]127.0.0.1:442 Close
[-]127.0.0.1:443 Close
[-]127.0.0.1:444 Close
[+]127.0.0.1:445 Open
C:\Python385>python.exe test1.py 127.0.0.1 80,139,445
[-]127.0.0.1:80 Close
[-]127.0.0.1:139 Close
[+]127.0.0.1:445 Open
加入多线程模块实现
import socket,sys
from threading import Thread
def port_scan(ip,port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, port))
return True
except:
return False
finally:
s.close()
#执行test1.py 127.0.0.1 80,139,445
def get_ip(ip,port):
if port_scan(ip,int(port)):
print('[+]' + ip + ':'+ str(port) + ' Open')
else:
print('[-]' + ip + ':' + str(port) + ' Close')
#执行python.exe test1.py 127.0.0.1 440-445
def get_ip_port(ip,port):
if port_scan(ip,port):
print('[+]' + ip + ':'+ str(port) + ' Open')
else:
print('[-]' + ip + ':' + str(port) + ' Close')
def main(ports):
if '-' in ports:
ports = ports.split('-')
for port in range(int(ports[0]), int(ports[1]) + 1):
t = Thread(target=get_ip_port,args=(ip,port))
t.start()
else:
ports = ports.split(',')
for port in ports:
t = Thread(target=get_ip,args=(ip,port))
t.start()
if __name__ == "__main__":
if len(sys.argv) == 3:
ip = sys.argv[1] # 接收参数
ports = sys.argv[2] # 接收参数
main(ports)
else:
print(
'''
Error!
Syntax: portscan.py [ip] [port]
Example: portscan.py 127.0.0.1 135,139,445,3389 | portscan.py 127.0.0.1 1-1000
'''
)
sys.exit()
执行结果
C:\Python385>python.exe test1.py 127.0.0.1
Error!
Syntax: portscan.py [ip] [port]
Example: portscan.py 127.0.0.1 135,139,445,3389 | portscan.py 127.0.0.1 1-1000
C:\Python385>python.exe test1.py 127.0.0.1 440-445
[+]127.0.0.1:445 Open
[-]127.0.0.1:442 Close
[-]127.0.0.1:440 Close
[-]127.0.0.1:441 Close
[-]127.0.0.1:444 Close
[-]127.0.0.1:443 Close