python实现tcp批量探测主机存活并进行端口扫描
程序员文章站
2024-01-05 13:46:28
注意* python版本是3.8* 一开始使用了线程池,后被注释掉,仅供参考* 单个ip探测,批量探测都可以,根据个人需求修改代码如下#!/usr/bin/env python# -*- coding: utf-8 -*-# @File : tcp_scan.py# @Author: Feng# @Date : 2020/11/5# @Desc : traceimport ipaddressimport timefrom concurrent.futures import T...
注意
* python版本是3.8
* 一开始使用了线程池,后被注释掉,仅供参考
* 单个ip探测,批量探测都可以,根据个人需求修改
代码如下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : tcp_scan.py
# @Author: Feng
# @Date : 2020/11/5
# @Desc : trace
import ipaddress
import time
from concurrent.futures import ThreadPoolExecutor,as_completed
from scapy.all import *
from random import randint
def ping_scan(host):
id_ip = randint(1, 65535) # 随机产生IP ID位
id_ping = randint(1, 65535) # 随机产生ping ID位
seq_ping = randint(1, 65535) # 随机产生ping序列号位
# ping指令会使用ICMP传输协议,ICMP报文中要封装IP头部
packet = IP(dst='39.99.161.182', ttl=64, id=id_ip) / ICMP(id=id_ping, seq=seq_ping)
res = sr1(packet, timeout=1, verbose=False)
time.sleep(0.5)
if res:
return True
else:
return False
'''def tcp_syn_scan(host, sport, eport):
ping = ping_scan(host)
pkt = sr(IP(dst=host)/TCP(dport=(int(sport),int(eport)),flags=2),
timeout=1, verbose=False)
pkt_list = pkt[0].res
for i in range(len(pkt_list)):
if pkt_list[i][1].haslayer(TCP):
tcp_fields = pkt_list[i][1].getlayer(TCP).fields
if tcp_fields['flags'] == 18:
print(str(tcp_fields['sport'])+ '端口开放')'''
def tcp_syn_scans(network, sport, eport):
net = ipaddress.ip_network(network)
#with ThreadPoolExecutor(max_workers=10) as t:
for ip in net:
ping_result = ping_scan(str(ip))
if ping_result == False:
print('[*] '+ str(ip) +' 主机不可达')
else:
for port in range(sport, eport):
port_scan(ip, port)
# task = t.submit(port_scan, ip, port)
# time.sleep(0.2)
def port_scan(ip,port):
pkt = sr(IP(dst=str(ip)) / TCP(dport=port, flags=2),
timeout=1, verbose=False)
pkt_list = pkt[0].res
if pkt_list:
for i in range(len(pkt_list)):
if pkt_list[i][1].haslayer(TCP):
tcp_fields = pkt_list[i][1].getlayer(TCP).fields
if tcp_fields['flags'] == 18:# syn+ack
print(str(ip) + ' ' + str(tcp_fields['sport']) + ' port is opening')
else:
print(str(ip) + ' ' + str(tcp_fields['sport']) + ' port is filter')# 可以是关闭也可以能是被过滤
else:
print(str(ip) + ' ' + str(port) + ' port is closed')
if __name__ == '__main__':
tcp_syn_scans('39.99.161.0/24', 1, 65535)
运行结果
本文地址:https://blog.csdn.net/qq_32171761/article/details/109642472