python构造icmp echo请求和实现网络探测器功能代码分享


Posted in Python onJanuary 10, 2014

python发送icmp echo requesy请求

import socket
import struct
def checksum(source_string):
    sum = 0
    countTo = (len(source_string)/2)*2
    count = 0
    while count<countTo:
        thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
        sum = sum + thisVal
        sum = sum & 0xffffffff 
        count = count + 2
    if countTo<len(source_string):
        sum = sum + ord(source_string[len(source_string) - 1])
        sum = sum & 0xffffffff 
    sum = (sum >> 16)  +  (sum & 0xffff)
    sum = sum + (sum >> 16)
    answer = ~sum
    answer = answer & 0xffff
    answer = answer >> 8 | (answer << 8 & 0xff00)
    return answer
def ping(ip):
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, 1)
    packet = struct.pack(
            "!BBHHH", 8, 0, 0, 0, 0
    )
    chksum=checksum(packet)
    packet = struct.pack(
            "!BBHHH", 8, 0, chksum, 0, 0
    )
    s.sendto(packet, (ip, 1))
if __name__=='__main__':
    ping('192.168.41.56')

扫描探测网络功能(网络探测器)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-'''
探测网络主机存活。
'''
import os
import struct
import array
import time
import socket
import IPy
import threading
class SendPingThr(threading.Thread):
    '''
    发送ICMP请求报文的线程。
    参数:
        ipPool      -- 可迭代的IP地址池
        icmpPacket  -- 构造的icmp报文
        icmpSocket  -- icmp套字接
        timeout     -- 设置发送超时
    '''
    def __init__(self, ipPool, icmpPacket, icmpSocket, timeout=3):
        threading.Thread.__init__(self)
        self.Sock = icmpSocket
        self.ipPool = ipPool
        self.packet = icmpPacket
        self.timeout = timeout
        self.Sock.settimeout( timeout + 3 )
    def run(self):
        time.sleep(0.01)  #等待接收线程启动
        for ip in self.ipPool:
            try:
                self.Sock.sendto(self.packet, (ip, 0))
            except socket.timeout:
                break
        time.sleep(self.timeout)
class Nscan:
    '''
    参数:
        timeout    -- Socket超时,默认3秒
        IPv6       -- 是否是IPv6,默认为False
    '''
    def __init__(self, timeout=3, IPv6=False):
        self.timeout = timeout
        self.IPv6 = IPv6
        self.__data = struct.pack('d', time.time())   #用于ICMP报文的负荷字节(8bit)
        self.__id = os.getpid()   #构造ICMP报文的ID字段,无实际意义
    @property   #属性装饰器
    def __icmpSocket(self):
        '''创建ICMP Socket'''
        if not self.IPv6:
            Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
        else:
            Sock = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.getprotobyname("ipv6-icmp"))
        return Sock
    def __inCksum(self, packet):
        '''ICMP 报文效验和计算方法'''
        if len(packet) & 1:
            packet = packet + '\0'
        words = array.array('h', packet)
        sum = 0
        for word in words:
            sum += (word & 0xffff)
        sum = (sum >> 16) + (sum & 0xffff)
        sum = sum + (sum >> 16)
        return (~sum) & 0xffff
    @property
    def __icmpPacket(self):
        '''构造 ICMP 报文'''
        if not self.IPv6:
            header = struct.pack('bbHHh', 8, 0, 0, self.__id, 0) # TYPE、CODE、CHKSUM、ID、SEQ
        else:
            header = struct.pack('BbHHh', 128, 0, 0, self.__id, 0)
        packet = header + self.__data     # packet without checksum
        chkSum = self.__inCksum(packet) # make checksum
        if not self.IPv6:
            header = struct.pack('bbHHh', 8, 0, chkSum, self.__id, 0)
        else:
            header = struct.pack('BbHHh', 128, 0, chkSum, self.__id, 0)
        return header + self.__data   # packet *with* checksum
    def isUnIP(self, IP):
        '''判断IP是否是一个合法的单播地址'''
        IP = [int(x) for x in IP.split('.') if x.isdigit()]
        if len(IP) == 4:
            if (0 < IP[0] < 223 and IP[0] != 127 and IP[1] < 256 and IP[2] < 256 and 0 < IP[3] < 255):
                return True
        return False
    def makeIpPool(self, startIP, lastIP):
        '''生产 IP 地址池'''
        IPver = 6 if self.IPv6 else 4
        intIP = lambda ip: IPy.IP(ip).int()
        ipPool = {IPy.intToIp(ip, IPver) for ip in range(intIP(startIP), intIP(lastIP)+1)}
        return {ip for ip in ipPool if self.isUnIP(ip)}
    def mPing(self, ipPool):
        '''利用ICMP报文探测网络主机存活
        参数:
            ipPool  -- 可迭代的IP地址池
        '''
        Sock = self.__icmpSocket
        Sock.settimeout(self.timeout)
        packet = self.__icmpPacket
        recvFroms = set()   #接收线程的来源IP地址容器
        sendThr = SendPingThr(ipPool, packet, Sock, self.timeout)
        sendThr.start()
        while True:
            try:
                recvFroms.add(Sock.recvfrom(1024)[1][0])
            except Exception:
                pass
            finally:
                if not sendThr.isAlive():
                    break
        return recvFroms & ipPool
if __name__=='__main__':
    s = Nscan()
    ipPool = s.makeIpPool('192.168.0.1', '192.168.0.254')
    print( s.mPing(ipPool) )
Python 相关文章推荐
python 生成不重复的随机数的代码
May 15 Python
python学习笔记:字典的使用示例详解
Jun 13 Python
详解Python编程中time模块的使用
Nov 20 Python
Python解析json之ValueError: Expecting property name enclosed in double quotes: line 1 column 2(char 1)
Jul 06 Python
python去除扩展名的实例讲解
Apr 23 Python
Python 利用pydub库操作音频文件的方法
Jan 09 Python
python实现感知器算法(批处理)
Jan 18 Python
python实现自动解数独小程序
Jan 21 Python
Python+selenium点击网页上指定坐标的实例
Jul 05 Python
Python for循环搭配else常见问题解决
Feb 11 Python
pytorch  网络参数 weight bias 初始化详解
Jun 24 Python
pytorch Dropout过拟合的操作
May 27 Python
python中mechanize库的简单使用示例
Jan 10 #Python
python使用新浪微博api上传图片到微博示例
Jan 10 #Python
python发腾讯微博代码分享
Jan 10 #Python
python实现2014火车票查询代码分享
Jan 10 #Python
python抓取豆瓣图片并自动保存示例学习
Jan 10 #Python
python文件比较示例分享
Jan 10 #Python
python发送伪造的arp请求
Jan 09 #Python
You might like
wordpress之wp-settings.php
2007/08/17 PHP
php中cookie的作用域
2008/03/27 PHP
4种PHP异步执行的常用方式
2015/12/24 PHP
由php中字符offset特征造成的绕过漏洞详解
2017/07/07 PHP
jquery 事件对象属性小结
2010/04/27 Javascript
使用jquery实现的一个图片延迟加载插件(含图片延迟加载原理)
2014/06/05 Javascript
JavaScript异步加载浅析
2014/12/28 Javascript
JavaScript中的函数模式详解
2015/02/11 Javascript
jQuery实现统计输入文字个数的方法
2015/03/11 Javascript
JavaScript中使用Math.PI圆周率属性的方法
2015/06/14 Javascript
Node.js程序中的本地文件操作用法小结
2016/03/06 Javascript
jQuery实现的多滑动门,多选项卡效果代码
2016/03/28 Javascript
浅析Jquery操作select
2016/12/13 Javascript
jQuery获取所有父级元素及同级元素及子元素的方法(推荐)
2018/01/21 jQuery
详解Angular中通过$location获取地址栏的参数
2018/08/02 Javascript
vue中选项卡点击切换且能滑动切换功能的实现代码
2018/11/25 Javascript
vue路由传参三种基本方式详解
2019/12/09 Javascript
electron 如何将任意资源打包的方法步骤
2020/04/16 Javascript
在Python的循环体中使用else语句的方法
2015/03/30 Python
分析在Python中何种情况下需要使用断言
2015/04/01 Python
python实现简单点对点(p2p)聊天
2017/09/13 Python
关于win10在tensorflow的安装及在pycharm中运行步骤详解
2020/03/16 Python
Windows下pycharm安装第三方库失败(通用解决方案)
2020/09/17 Python
如何用Python进行时间序列分解和预测
2021/03/01 Python
飞利浦法国官网:Philips法国
2019/07/10 全球购物
投资协议书范本
2014/04/21 职场文书
社区党建工作汇报材料
2014/08/14 职场文书
优秀乡村医生先进事迹材料
2014/08/23 职场文书
抗洪救灾标语
2014/10/08 职场文书
工作检讨书500字
2014/10/19 职场文书
担保书格式
2015/01/20 职场文书
追讨欠款律师函
2015/06/24 职场文书
小区物业管理2015年度工作总结
2015/10/22 职场文书
2016年小学“我们的节日·中秋节”活动总结
2016/04/05 职场文书
解决Nginx 配置 proxy_pass 后 返回404问题
2021/03/31 Servers
SpringBoot整合MongoDB的实现步骤
2021/06/23 MongoDB