ip scanner with python code example
Example 1: python ping scan
import time
import ipaddress
import subprocess
from colorama import init
init()
import threading
from queue import Queue
print_lock = threading.Lock()
net_addr = input("Enter Network (192.168.1.0/24): ")
startTime = time.time()
ip_net = ipaddress.ip_network(net_addr)
all_hosts = list(ip_net.hosts())
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = subprocess.SW_HIDE
print ('Sweeping Network with ICMP: ', net_addr)
def pingsweep(ip):
output = subprocess.Popen(['ping', '-n', '1', '-w', '150', str(all_hosts[ip])], stdout=subprocess.PIPE, startupinfo=info).communicate()[0]
with print_lock:
print('\033[93m', end='')
if "Reply" in output.decode('utf-8'):
print(str(all_hosts[ip]), '\033[32m'+"is Online")
elif "Destination host unreachable" in output.decode('utf-8'):
pass
elif "Request timed out" in output.decode('utf-8'):
pass
else:
print("UNKNOWN", end='')
def threader():
while True:
worker = q.get()
pingsweep(worker)
q.task_done()
q = Queue()
for x in range(100):
t = threading.Thread(target = threader)
t.daemon = True
t.start()
for worker in range(len(all_hosts)):
q.put(worker)
q.join()
runtime = float("%0.2f" % (time.time() - startTime))
print("Run Time: ", runtime, "seconds")
Example 2: python ping scan
import socket
import time
import threading
from queue import Queue
socket.setdefaulttimeout(0.25)
print_lock = threading.Lock()
target = input('Enter the host to be scanned: ')
t_IP = socket.gethostbyname(target)
print ('Starting scan on host: ', t_IP)
def portscan(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
con = s.connect((t_IP, port))
with print_lock:
print(port, 'is open')
con.close()
except:
pass
def threader():
while True:
worker = q.get()
portscan(worker)
q.task_done()
q = Queue()
startTime = time.time()
for x in range(100):
t = threading.Thread(target = threader)
t.daemon = True
t.start()
for worker in range(1, 500):
q.put(worker)
q.join()
print('Time taken:', time.time() - startTime)