Author Topic: [Python] Custom Ping with Range (1-254)  (Read 985 times)

0 Members and 1 Guest are viewing this topic.

Offline Pyromaniac

  • /dev/null
  • *
  • Posts: 19
  • Cookies: 3
    • View Profile
[Python] Custom Ping with Range (1-254)
« on: October 15, 2015, 09:58:27 pm »
I just started learning threading so I decided to make a program to ping a network. Probably not the best way to approach it. Just posted this so I can get some constructive feedback and hope to help other programmers learn python too.

Code: (python) [Select]

#!/usr/bin/python
 
import subprocess
import threading
import time
import sys
 
def ping_it_boy(ip_addr):
    p = subprocess.Popen(["ping","-n","1",ip_addr], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
 
    for line in p.stdout.read().split("\n"):
        if line.strip().startswith("Reply from "):
            l = line.strip().split()
            m = line.replace(l[0]+" "+l[1]+" "+l[2], "")
            if m.strip() != "Destination host unreachable.":
                 print(l[2][:-1] + " >>> " + m)
 
def get_input(prompt):
    """
   Function Get input from the user maintaining the python compatibility with earlier and newer versions.
   :param prompt:
   :rtype : str
   :return: Returns the Hash string received from user.
   """
    if sys.hexversion > 0x03000000:
        return input(prompt)
    else:
        return raw_input(prompt)
 
if __name__ == "__main__":
    ip = get_input("Enter the base IP. Example: 192.168.1 \n>>> ")
    ip = ip.strip() + "."
    print("Starting multiply threads for "+ ip + "0/24")
    t_thread = []
    t_sleep_on = 20
    for i in range(1, 255):
        t = threading.Thread(target=ping_it_boy, args=(ip + str(i),))
        t_thread.append(t)
        t.start()
        if i == t_sleep_on:
            for i in t_thread:
                i.join()
                t_thread.remove(i)
            # print("Wakey Wakey")
            t_sleep_on += 20
 

ohh btw the reason why i cut the thread by 20 is because I have a slow pc. Launching a lot of thread cause my computer to crash so I capped it at 20.
« Last Edit: October 16, 2015, 06:13:44 am by Pyromaniac »

Offline kenjoe41

  • Symphorophiliac Programmer
  • Administrator
  • Baron
  • *
  • Posts: 990
  • Cookies: 224
    • View Profile
Re: [Python] Custom Ping with Range (1-254)
« Reply #1 on: October 15, 2015, 10:41:14 pm »
Code: (python) [Select]
#!/usr/bin/python

import subprocess
import threading
import time
import sys

def ping_it_boy(ip_addr):
    p = subprocess.Popen(["ping","-n","1",ip_addr], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    for line in p.stdout.read().split("\n"):
        if line.strip().startswith("Reply from "):
            l = line.strip().split()
            m = line.replace(l[0]+" "+l[1]+" "+l[2], "")
            if m.strip() != "Destination host unreachable.":
                 print(l[2][:-1] + " >>> " + m)

def get_input(prompt):
    """
    Function Get input from the user maintaining the python compatibility with earlier and newer versions.
    :param prompt:
    :rtype : str
    :return: Returns the Hash string received from user.
    """
    if sys.hexversion > 0x03000000:
        return input(prompt)
    else:
        return raw_input(prompt)

if __name__ == "__main__":
    ip = get_input("Enter the base IP. Example: 192.168.1 \n>>> ")
    ip = ip.strip() + "."
    print("Starting multiply threads for "+ ip + "0/24")
    t_thread = []
    t_sleep_on = 20
    for i in range(1, 255):
        t = threading.Thread(target=ping_it_boy, args=(ip + str(i),))
        t_thread.append(t)
        t.start()
        if i == t_sleep_on:
            for i in t_thread:
                i.join()
                t_thread.remove(i)
            # print("Wakey Wakey")
            t_sleep_on += 20

Haven't changed much except add one function. I would advise you extend this for mask or IP block and you won't need a user to give you a base IP.
If you can't explain it to a 6 year old, you don't understand it yourself.
http://upload.alpha.evilzone.org/index.php?page=img&img=GwkGGneGR7Pl222zVGmNTjerkhkYNGtBuiYXkpyNv4ScOAWQu0-Y8[<NgGw/hsq]>EvbQrOrousk[/img]

Offline Pyromaniac

  • /dev/null
  • *
  • Posts: 19
  • Cookies: 3
    • View Profile
Re: [Python] Custom Ping with Range (1-254)
« Reply #2 on: October 16, 2015, 06:11:20 am »
Haven't changed much except add one function.
Thanks! I forgot to mention that I was on python 2.7 because I was using the pyinstaller to freeze the app here and there. Thanks for making it work on python3.

I would advise you extend this for mask or IP block and you won't need a user to give you a base IP.
I was thinking about that but didn't know how to deal with multiple nic pc yet. I will look into it and extend this further.

Offline gray-fox

  • Knight
  • **
  • Posts: 208
  • Cookies: 52
    • View Profile
Re: [Python] Custom Ping with Range (1-254)
« Reply #3 on: October 16, 2015, 08:13:12 am »
I was thinking about that but didn't know how to deal with multiple nic pc yet. I will look into it and extend this further.
How about asking interface from user as commandline argument(Use argparser or something ) and then work "base ip" from there. Much nicer than asking that base ip imo.

Short example to get that base ip with interface name:
Code: [Select]
import socket
import fcntl
import struct

def get_ipbase(iface):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip_raw = socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,
        struct.pack('256s', iface[:15])
    )[20:24])
    ip_ = ip_raw.split(".")
    ip_base = ip_[:-1]
    return '.'.join(ip_base)

#example
print get_ipbase('wlan0') #Prints e.g. 192.168.100
« Last Edit: October 16, 2015, 09:02:00 am by gray-fox »

Offline Pyromaniac

  • /dev/null
  • *
  • Posts: 19
  • Cookies: 3
    • View Profile
Re: [Python] Custom Ping with Range (1-254)
« Reply #4 on: October 16, 2015, 08:01:19 pm »
How about asking interface from user as commandline argument(Use argparser or something ) and then work "base ip" from there. Much nicer than asking that base ip imo.
That's a great idea but I will be bound to unix. Well the reason why I created this was because I work for a company with very old network. All the sys admins who have more authority than me are all "windows experts". They also aren't familiar with tools like nmap lol. I created this to prove a point that they need to learn scripting to make their life easier since half the staff who knows what they are doing are gone :( I am a trainee admin, but I doubt that they can show me anything useful ahahahah.

I can probably connect to google dns and retrieve the ip automatically tough to avoid picking up the lo. The downfall is that in the future if I need to ping all devices from a nic that doesn't connect to internet than I am kind of screw. I will figure a way out and update it later. Just picked up black hat python. Very very interesting book.

Code: (python) [Select]
import subprocess
import threading
import time
import socket

def ping_it_boy(ip_addr):
    p = subprocess.Popen(["ping","-n","1",ip_addr], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    for line in p.stdout.read().split("\n"):
        if line.strip().startswith("Reply from "):
            l = line.strip().split()
            m = line.replace(l[0]+" "+l[1]+" "+l[2], "")
            if m.strip() != "Destination host unreachable.":
                 print(l[2][:-1] + " >>> " + m)

def get_ip_addr():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8",80))
    ip = s.getsockname()[0]
    base_ip = ip.split(".")[0] + "." + ip.split(".")[1] + "." + ip.split(".")[2] + "."
    return base_ip


if __name__ == "__main__":
    # ip = raw_input("Enter the base IP. Example: 192.168.1 \n>>> ")
    # ip = ip.strip() + "."
    ip = get_ip_addr()
    print("Starting multiply threads for "+ ip + "0/24")
    t_thread = []
    t_sleep_on = 20
    for i in range(1, 255):
        t = threading.Thread(target=ping_it_boy, args=(ip + str(i),))
        t_thread.append(t)
        t.start()
        if i == t_sleep_on:
            # print("Threading sleeping: " + str(i))
            for i in t_thread:
                i.join()
                t_thread.remove(i)
            # print("Wakey Wakey")
            t_sleep_on += 20



Offline gray-fox

  • Knight
  • **
  • Posts: 208
  • Cookies: 52
    • View Profile
Re: [Python] Custom Ping with Range (1-254)
« Reply #5 on: October 16, 2015, 10:41:44 pm »
Kind of forgot your script were for windows when I wrote my previous post(even tho I did noticed it from ping arguments+parsing). But for windows(works also in Linux and OS X ) you might wanna check netifaces module. Haven't use it myself but it seems quit useful for this kind of stuff.

edit:

Also this part of script in your last post:
Code: (python) [Select]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8",80))
    ip = s.getsockname()[0]
I think alternative to this without querying outside server could be:
Code: (python) [Select]
host = socket.gethostname()
ip = socket.gethostbyname(host)

This should work on Windows. I tested it with my VM windows7 and it returned correct local ip and not lo. Instead in some Linux systems it always returns '127.0.0.1'.
« Last Edit: October 16, 2015, 10:54:58 pm by gray-fox »

Offline Pyromaniac

  • /dev/null
  • *
  • Posts: 19
  • Cookies: 3
    • View Profile
Re: [Python] Custom Ping with Range (1-254)
« Reply #6 on: October 17, 2015, 06:00:52 am »
Thanks bro and +a cookie. netifaces looks simple enough and is very suitable for this app. I will give it a try  :)