How To Create Ping Sweeping Script Using Python Programming Language - Pentesting Python

Namaste Friend,

                                    Today's Tutorial is about how we can create python script for doing ping request more easily and fastly. or you can say  "How To Create High-Speed Ping Sweeping Script written in python".


so, let's talk about today's topic.




What is Ping Scan



Ping Scan is a process of sending ICMP ECHO request packet to any live host. If a Host wants to mention his availability, it will definitely reply with an ICMP ECHO response packet.

Now, you will think why I said, "want to mention” in previous lines.

This Is Because, To Prevent System From Hackings Attacks, Users Use Firewalls And Other Security Features That's Not Allow Host Machine to Response back at ICMP Packet Request But Don't Worry, Almost All Host System Likes To Respond On ICMP ECHO Requests.

To Send Ping ICMP Request, All Types Of Operating System’s Provides Built-in Facility That Can Help User To Ping Any Host And Verify That, The Host Is Live Or Not.


In Another word, Ping Scans Also Known As Ping Sweeping. Ping Sweeping is the procedure to Find More Than One Machine Availability in Specific Network Range.



Why Create Ping Sweeping Script



Let Assume If You Want To Scan Big List Of IP Addresses To Find Live Host Systems But this Procedure is very time consuming And You don’t have that much time. So, here what we can do? we can use our automatic ping sweeping python script that can handle all our works automatically.

In Simple Words, This Script also plays very important role in the various type of penetrating testing and hacking.


Find Live Systems



To Send A Simple ICMP Echo Request, you can use many types of utilities in different situations like


Windows (built-in)

Here, -n argument is selecting a number of time to send ICMP ECHO request.



$ ping -n 5 192.168.1.101/24



Linux (built-in)

Here, -n argument is selecting a number of time to send ICMP ECHO request.


$ ping -c 5 192.168.1.101/24


ICMP IP Network Scanning with Nmap tool


You can use regular open source tool called Nmap. Best For Scanning Because Nmap has also the ability to guess host even after ICMP filter and Firewall. Type the following command to run ICMP IP Scan:
$ nmap -sP -PI 192.168.1.101/24



Create Ping Sweep Script




Friends, Belive Me This Script is very also very good example of multi-processing because here in this script, to increase the speed of ping sweeping process, we will use multiprocessing module.

now, let's Talk about the basic structure of ping script.

1. This Function is for selecting commands for ping sweeping according to the operating system.


 # Command Selecting Function
 def set_os_command(self):
  oper = platform.system()
  if (oper=="Windows"):
   ping = "ping -n {} {}"
  elif (oper== "Linux"):
   ping= "ping -c {} {}"
  else :
   ping= "ping -c {} {}"
  self.commad=ping
  return






2. This Function is for sending ICMP ECHO request and also for verifying response status.



 # Function for Checking IP Status
 def checkping(self, ip):
  ping=self.commad
  recv=os.popen(ping.format(self.timeout, ip)).read()
  recv=recv.upper()
  if recv.count('TTL'):
   print "[+]\t {} \t==> Live ".format(ip)
   self.live_ip_collector.put(ip)
  return








3. This Function Is Using Special Technique For Selecting Range Of IP Address To Ping Sweep Scan



# Extracting Number format
def extraction(port):
 storeport=[]
 # Verifiying Port Value
 if port:
  # Verifying Port is in Range
  if "-" in port and "," not in port:
   x1,x2=port.split('-')
   storeport=range(int(x1),int(x2))
  # Verifying Port is in Commas
  elif "," in port and "-" not in port:
   storeport=port.split(',')
  elif "," in port and "-" in port:
   x2=[]
   for i in port.split(','):
    if '-' in i:
     y1,y2=i.split('-')
     x2=x2+range(int(y1),int(y2))
    else:
     x2.append(i)
   storeport=x2
  else:
   storeport.append(port)
 else:
  pass
 return storeport



# Extracting Ip Address
def IP_extractor(ip):
 storeobj=[]
 ip=ip.split(':')
 x1=extraction(ip[0])
 x2=extraction(ip[1])
 x3=extraction(ip[2])
 x4=extraction(ip[3])
 for i1 in x1:
  for i2 in x2:
   for i3 in x3:
    for i4 in x4:
     storeobj.append("{}.{}.{}.{}".format(i1,i2,i3,i4))
return storeobj





4. This Function is For Using Multi-Processing In Scanning.





 # Function For Multi_processing
 def scanning_boosters(self):
  proces=[]
  for ip in self.target:
   k=len(multiprocessing.active_children())
   if k==self.thread:
    time.sleep(3)
    self.thread=self.thread+30
   mythread=multiprocessing.Process(target=self.checkping, args=(ip,))
   mythread.start()
   proces.append(mythread)

  for mythread in proces:
   mythread.join()
  self.timeclose=time.time()
  self.showing_results()
  return




Features Of This Script:


  • High-Speed Ping Sweep.
  • Stable Script
  • Cross-platform Supported
  • Result Save as txt
  • Unique feature of input


Here, it's my codes of python pinger.



here, is my demo codes

1.  pypinger.py


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/python

# ---------------- READ ME ---------------------------------------------
# This Script is Created Only For Practise And Educational Purpose Only
# This Script Is Created For http://bitforestinfo.blogspot.com
# This Script is Written By
__author__='''

######################################################
                By S.S.B Group                          
######################################################

    Suraj Singh
    Admin
    S.S.B Group
    surajsinghbisht054@gmail.com
    http://bitforestinfo.blogspot.in/

    Note: We Feel Proud To Be Indian
######################################################
'''
# =================Other Configuration================ 
# Usages :
usage = "usage: %prog [options] "
# Version
Version="%prog 0.0.1"
# ====================================================

# Importing Modules
import os, multiprocessing, time, optparse, platform

# Main Engine
class Pinger:
 def __init__(self, target, thread, output, timeout):
  self.timestarted=time.time()
  self.live_ip_collector=multiprocessing.Queue()
  self.target=target
  self.thread=thread
  self.output=output
  self.timeout=timeout
  self.set_os_command()
  #self.checkping()
  self.scanning_boosters()

  # Saving OUtput
 def save_output(self):
  f=open(self.output,'a')
  for i in self.live_ip_collector:
   f.write(i+'\n')
  f.close()
  return

 # Function For Multi_processing
 def scanning_boosters(self):
  proces=[]
  for ip in self.target:
   k=len(multiprocessing.active_children())
   if k==self.thread:
    time.sleep(3)
    self.thread=self.thread+30
   mythread=multiprocessing.Process(target=self.checkping, args=(ip,))
   mythread.start()
   proces.append(mythread)

  for mythread in proces:
   mythread.join()
  self.timeclose=time.time()
  self.showing_results()
  return

 # Printing Function
 def showing_results(self):
  storeip=[]
  x=1
  while x==1:
   try:
    storeip.append(self.live_ip_collector.get_nowait())
   except:
    x=x+1
  self.live_ip_collector=storeip

  print "\n"*3,"#"*80
  print "[+] Scan Started On \t\t:\t",time.ctime(self.timestarted)
  print "[+] Scan Closed On  \t\t:\t",time.ctime(self.timeclose)
  print "[+] Scan Total Duration \t:\t",self.timeclose-self.timestarted
  print "[+] Total Live System Answered\t:\t",len(self.live_ip_collector)
  if self.output:
   self.save_output()
  print "\n[+] Thanks For Using My Program. By S.S.B"
  return

 # Command Selecting Function
 def set_os_command(self):
  oper = platform.system()
  if (oper=="Windows"):
   ping = "ping -n {} {}"
  elif (oper== "Linux"):
   ping= "ping -c {} {}"
  else :
   ping= "ping -c {} {}"
  self.commad=ping
  return

 # Function for Checking IP Status
 def checkping(self, ip):
  ping=self.commad
  recv=os.popen(ping.format(self.timeout, ip)).read()
  recv=recv.upper()
  if recv.count('TTL'):
   print "[+]\t {} \t==> Live ".format(ip)
   self.live_ip_collector.put(ip)
  return


# Extracting Number format
def extraction(port):
 storeport=[]
 # Verifiying Port Value
 if port:
  # Verifying Port is in Range
  if "-" in port and "," not in port:
   x1,x2=port.split('-')
   storeport=range(int(x1),int(x2))
  # Verifying Port is in Commas
  elif "," in port and "-" not in port:
   storeport=port.split(',')
  elif "," in port and "-" in port:
   x2=[]
   for i in port.split(','):
    if '-' in i:
     y1,y2=i.split('-')
     x2=x2+range(int(y1),int(y2))
    else:
     x2.append(i)
   storeport=x2
  else:
   storeport.append(port)
 else:
  pass
 return storeport

# Extracting Ip Address
def IP_extractor(ip):
 storeobj=[]
 ip=ip.split(':')
 x1=extraction(ip[0])
 x2=extraction(ip[1])
 x3=extraction(ip[2])
 x4=extraction(ip[3])
 for i1 in x1:
  for i2 in x2:
   for i3 in x3:
    for i4 in x4:
     storeobj.append("{}.{}.{}.{}".format(i1,i2,i3,i4))
 return storeobj

def main():
 print __author__
 parser=optparse.OptionParser(usage=usage,version=Version)
 parser.add_option('-i','--target',type='string',dest='target',help="Specify IP Addresses Range For Scan", default=None)
 parser.add_option('-t',"--thread",type='string', dest="thread", help="Specify Number of Thread For Scanning ", default='100')
 parser.add_option('-o',"--output",type='string', dest="output", help="Specify Path For Saving Output in Txt.", default="live_ip.txt")
 parser.add_option('-c','--timeout',type='string', dest="timeout", help="Specify No. Of Request Per IP",default='1')
 (options, args)= parser.parse_args()
 if not options.target:
  print "[+] Please Provide IP Range. e.g: 192-192:128:1:4-70, For More, Check Readme "
  exit(0)
 target=options.target
 thread=options.thread
 output=options.output
 timeout=options.timeout
 target=IP_extractor(target)
 Pinger(target,thread,output,timeout)
 return

# Trigger
if __name__ == '__main__':
 main()

For Downloading, Raw Script Click Here


Now, Let's Talk About This Script. 


In this Script For Providing IP Address Range. You Have To Provide Input Like Example Given Below:

for e.g: Our Ip Address = 192.168.10.1

You will Provide input like this = 192:168:10:1  (Change "." into ":")

First, Split 192.168.10.1 into 4 Sections.

Section 1 =  192
Section 2 =  168
Section 3 =  10
Section 4 =  1

Now, In Each Section, Choose Your Ip Address Digits Separated by Commas or Provide Range.

e.g:  section 1 = 100-115,120,130,155-180


After Thats Join These Number with The Help of This Symbol ":"  Examples:

=> 192:168:10:1-15,18,25
=> 192-195:168:10:1
=> 192-192,200:168-170:10-5:1-15

example Q.1:

192.168.10.1,
192.168.10.2,
192.168.10.3,
192.168.10.4,
192.168.10.5,
192.168.10.6,
192.168.10.7,

Ans. 192:168:10:1-7

Example Q.2:

112.168.10.1
113.168.10.1
114.168.10.1
155.168.10.1
196.168.10.1
197.168.10.1
198.168.10.1
199.168.10.1

Ans. 112-114,155,196-199:168:10:1

Example 3:

192-199,212,250:150-168,173:10-16,19:1-10

Usages


Usage: pypinger.py [options]

Options:

  --version             show program's version number and exit

  -h, --help            show this help message and exit

  -i TARGET, --target=TARGET
                        Specify IP Addresses Range For Scan. Eg:- 192:168:10:1-7

  -t THREAD, --thread=THREAD
                        Specify Number of Thread For Scanning

  -o OUTPUT, --output=OUTPUT
                        Specify Path For Saving Output in Txt.

  -c TIMEOUT, --timeout=TIMEOUT
                        Specify No. Of Request Per IP


Usages Example:


  • python pypinger.py -i 192:168:10:1-100
  • python pypinger.py -i 192:168:10:1-200



Let's See, How Our Code Running.




hmm, our script running well.

or

If You Want Practical Usages Then Watch This Video.






Done!

Have a nice day.

Thanks For Reading.

For More Update, Visit Our Blog Regularly. 
, Subscribe Our Blog, 
Follow Us and share it.
For Any Type of Suggestion, Help Or Question
Contact me:
S.S.B
surajsinghbisht054@gmail.com
or Comment Below

Share this

Related Posts

Previous
Next Post »