Scapy 网段中ping扫描

安装scapy

pip3 install scapy-python3

交互式ip包构造

#scapy
>>> ping = sr(IP(dst='202.100.1.1')/ICMP()/b'welcome to qytang')

>>> b = IP(dst='202.100.1.1')/ICMP()/b'welcome to qytang'

>>> b.show()

>>> ping = sr1(b)     #send and receive  1个包

>>> ping.show()

>>> ping.getlayer(ICMP).fields    #提取ICMP的头部,并把头部字段提取出来产生一个字典

>>> ping.getlayer(ICMP).fields['id']    #提取id字段


#sr()	发送三层数据包,等待接收一个或者多个数据包的响应
#sr(1)	发送三层数据包,并仅仅只等待接收一个数据包的相应
#srp()	发送二层数据包,并且等待响应
#send()	发送三层数据包,系统会自动处理路由和二层信息
#sendp()	发送二层数据包

Scapy实现ping扫描

scapy_ping_one.py 实现一个ip地址的ping

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
from random import randint

def scapy_ping_one(host):
	id_ip = randint(1,65535)#随机产生IP_ID位
	id_ping = randint(1,65535)#随机产生Ping_ID位
	seq_ping = randint(1,65535)#随机产生Ping序列号位
	#构造Ping数据包
	packet = IP(dst = host,ttl = 64,id = id_ip)/ICMP(id = id_ping,seq = seq_ping)/b'Welcome to qytang'
	ping = sr1(packet,timeout = 2,verbose = False)#获取相应信息,超时为2秒,关闭详细信息
	#ping.show() #被调用来扫描整个网段时候最好注释起来,不然产生大量信息
	if ping:#如果又响应信息
		os._exit(3)#退出码为3

if __name__ == '__main__':
	scapy_ping_one('172.17.168.1')

scapy_ping_scan.py 实现整个网段的ping扫描

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import ipaddress
import time
import multiprocessing
from scapy_ping_one import scapy_ping_one
from scapy.all import *
def scapy_ping_scan(network):
	net = ipaddress.ip_network(network)
	ip_processes = {}
	for ip in net:
		ip_addr = str(ip)#读取网络中的每一个IP地址,注意需要str转换为字符串!
		ping_one = multiprocessing.Process(target = scapy_ping_one,args=(ip_addr))
		ping_one.start()
		ip_processes[ip_addr] = ping_one#产生IP与进程对应的字典
	ip_list = []
	for ip,process in ip_processes.items():
		if process.exitcode == 3:
			ip_list.append(ip)
		else:
			process.terminate()
	return sorted(ip_list)

if __name__ == '__main__':
	import time
	t = time.time()
	active_ip = scapy_ping_scan(sys.argv[1])
	print('活动IP地址如下:')
	for ip in active_ip:
		print(ip)
	t2 = time.time()
	print(t2 - t1)
posted @ 2018-11-24 15:36  春雨冰河  阅读(659)  评论(1编辑  收藏  举报