Python constructs ICMP echo request and realizes network probe function code sharing _python

Source: Internet
Author: User
Tags network function ord pack sleep

Python sends ICMP echo requesy request

Copy Code code as follows:

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 >>) + (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 ')



Scan detection network function (Network detector)

Copy Code code as follows:

#!/usr/bin/env Python3
#-*-Coding:utf-8-*-

'''
Probe the network host to survive.
'''

Import OS
Import struct
Import Array
Import time
Import socket
Import ipy
Import threading

Class Sendpingthr (threading. Thread):
'''
The thread that sent the ICMP request message.

Parameters:
Ippool--An iterative IP address pool
Icmppacket--Constructed ICMP message
Icmpsocket--ICMP socket connection
Timeout--Setting send 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:
'''
Parameters:
Timeout--socket timeout, default 3 seconds
IPV6--is IPV6, default is 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字段, no practical significance

@property #属性装饰器
def __icmpsocket (self):
' Create an 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 message Parity and calculation method '"
If Len (packet) & 1:
Packet = packet + ' "
Words = Array.array (' h ', packet)
sum = 0
For word in words:
sum + = (Word & 0xFFFF)
sum = (sum >>) + (sum & 0xffff)
sum = sum + (sum >> 16)

Return (~sum) & 0xFFFF

@property
def __icmppacket (self):
' Construct ICMP message '
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):
"To determine whether IP is a legitimate unicast address"
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):
"Production IP address Pool"
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 to IP in ippool if Self.isunip (IP)}

def mping (self, Ippool):
"" Using ICMP packets to detect the existence of a network host

Parameters:
Ippool--An iterative IP address pool
'''
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))

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.