Coder Social home page Coder Social logo

mauricelambert / networkscanner Goto Github PK

View Code? Open in Web Editor NEW
7.0 2.0 1.0 48 KB

This package implements an asynchronous network scanner.

License: GNU General Public License v3.0

Python 100.00%
network-analysis network-scanner pypi-package python3 asyncio async scanner scapy host-discovery

networkscanner's Introduction

NetworkScanner logo

NetworkScanner

Description

This package implements an asynchronous network scanner (using scapy or asyncio).

Requirements

This package require:

  • python3
  • python3 Standard Library
  • PythonToolsKit

Optional:

  • Scapy

Installation

pip install NetworkScanner 

Usages

Command lines

# Python executable
python3 NetworkScanner.pyz -h
# or
chmod u+x NetworkScanner.pyz
./NetworkScanner.pyz --help

# Python module
python3 -m NetworkScanner -t 172.18.0.1-172.18.0.15

# Entry point (console)
NetworkScanner -d --noping --hostname --ports 22 80 -p 445 139 443 -T 1 -R -s -t 172.18.0.0/28
NetworkScanner -i 172.18.0. -P -t 172.18.0.0/28 # Passive scan using scapy sniffer

Python3

# Simple usage to print results in your console
from NetworkScanner import NetworkScanner, logger
scanner = NetworkScanner({"172.18.0.1", "172.18.0.3"})
scanner.scan()      # Without scapy

# Custom behaviors

def do_IP_UP(ip, reason, detail = None):
    print(f"{ip} is UP ({reason} {detail})")

scanner.handle_UP = do_IP_UP
scanner.scan(True)  # With scapy

scanner.hosts_up    # List of IP addresses used
scanner.hosts_down  # List of unused IP addresses

from scapy.all import *
scanner = NetworkScanner({"172.18.0.1"}, False, [22, 80], False, True, False, 1, conf.iface)
scanner.handle_UP = do_IP_UP
scanner.handle_DOWN = print
scanner.scan()

logger.setLevel(10) # debug mode

class CustomNetworkScanner(NetworkScanner):
    def handle_UP(self, ip: str, detection_type: str, details = None): # details is a kwarg
        print(f"IP: {ip} is UP (detection type: {detection_type}, details: {details}")
    def handle_DOWN(self, ip: str):
        print(f"IP: {ip} is DOWN")

scanner = NetworkScanner({"172.18.0.1", "172.18.0.3"})
scanner.scan()
scanner.scan(passive=True) # passive mode using scapy sniffer

Useful usages

With scapy, hosts discovery (best performances):

NetworkScanner --noping -T 1 -t [targets]
from NetworkScanner import NetworkScanner
from scapy.all import conf

scanner = NetworkScanner(
    {},
    ping=False,
    ports=[],
    arp=True,
    hostname=False,
    real_time=False,
    timeout=1,
    iface=conf.iface,
)
scanner.scan(True)

Without scapy, hosts discovery:

NetworkScanner -t [targets]
from NetworkScanner import NetworkScanner
scanner = NetworkScanner(
    {},
    ping=True,
    ports=[],
    arp=True,
    hostname=False,
    real_time=False,
    timeout=1,
)
scanner.scan()

Without scapy, opened port && hosts discovery:

from NetworkScanner import NetworkScanner

def host_up(ip: str, method: str, port: int = None):
    if method == 'tcp':
        print(f"{ip}:{port} is open.")
    else:
        print(f"{ip} is UP.")

scanner = NetworkScanner(
    {},
    ping=False,
    ports=[22, 80, 443],
    arp=True,
    hostname=False,
    real_time=False,
    timeout=1,
)
scanner.handle_UP = host_up
scanner.scan(False)

Links

Help

usage: NetworkScanner.py [-h] [--interface INTERFACE] --targets TARGETS [TARGETS ...] [--noping] [--noarp]
                         [--hostname] [--ports PORTS [PORTS ...]] [--timeout TIMEOUT] [--no-realtime] [--debug]
                         [--print-ip] [--force-asynchronous] [--passive-scan]

This program scans networks and IP address ranges.

options:
  -h, --help            show this help message and exit
  --interface INTERFACE, -i INTERFACE
                        Part of the IP, MAC or name of the interface
  --targets TARGETS [TARGETS ...], -t TARGETS [TARGETS ...]
                        Targets from networks and IP address ranges.
  --noping, -g          No ping detection. [Without scapy ping is required for ARP detection]
  --noarp, -A           No arp cache.
  --hostname, -H        Test the hostname resolution to defined if host is UP (longer).
  --ports PORTS [PORTS ...], -p PORTS [PORTS ...]
                        Test the TCP port connections to defined if the host is UP.
  --timeout TIMEOUT, -T TIMEOUT
                        Connections timeout.
  --no-realtime, -R     Do not print results in real time.
  --debug, -d           Debug mode (logger level debug).
  --print-ip, -I        Print only the IP address if UP.
  --force-asynchronous, --async, -a
                        Force asynchronous mode, using asyncio instead of scapy.
  --passive-scan, --passive, -P
                        Passive scan, sniff the network packets to identify who is up. This scan is endless because
                        you can never be sure to have detected all the IP addresses.

Licence

Licensed under the GPL, version 3.

networkscanner's People

Contributors

mauricelambert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

mastersatish

networkscanner's Issues

Cannot execute, cannot import run from asyncio

I installed NetworkScanner using pip on Rocky 8.6 running python 3.6. I get the following error, even after I installed asyncio with pip

→ python3 NetworkScanner.pyz -h

NetworkScanner  Copyright (C) 2021, 2022  Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.

Traceback (most recent call last):
  File "/usr/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib64/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "NetworkScanner.pyz/__main__.py", line 290, in <module>
ImportError: cannot import name 'run'
→ python3 -m NetworkScanner -t 172.18.0.1-172.18.0.15

NetworkScanner  Copyright (C) 2021, 2022  Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.

Traceback (most recent call last):
  File "/usr/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib64/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/opt/lynis/python3_env/lib/python3.6/site-packages/NetworkScanner.py", line 290, in <module>
    from asyncio import (
ImportError: cannot import name 'run'

OSError: [Errno 24] Too many open files

from NetworkScanner import NetworkScanner
from asyncio import run

scanner = NetworkScanner(
	NetworkScanner.get_targets_from_network("192.168.178.0/23"),
	ping=True,
	arp=True,
	hostname=True,
	real_time=False,
	timeout=3)
run(scanner.scan())
print(scanner.hosts_up)

NetworkScanner Copyright (C) 2021 Maurice Lambert
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions.

Traceback (most recent call last):
File "ipcalc.py", line 12, in
run(scanner.scan())
File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/tkladmin/.local/lib/python3.8/site-packages/NetworkScanner/NetworkScanner.py", line 81, in scan
await gather(*[self.test_ip(str(target)) for target in self.targets])
File "/home/tkladmin/.local/lib/python3.8/site-packages/NetworkScanner/NetworkScanner.py", line 95, in test_ip
process = await create_subprocess_shell(Constants.PING_COMMAND.value + ip, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
File "/usr/lib/python3.8/asyncio/subprocess.py", line 216, in create_subprocess_shell
transport, protocol = await loop.subprocess_shell(
File "/usr/lib/python3.8/asyncio/base_events.py", line 1597, in subprocess_shell
transport = await self._make_subprocess_transport(
File "/usr/lib/python3.8/asyncio/unix_events.py", line 197, in _make_subprocess_transport
transp = _UnixSubprocessTransport(self, protocol, args, shell,
File "/usr/lib/python3.8/asyncio/base_subprocess.py", line 36, in init
self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
File "/usr/lib/python3.8/asyncio/unix_events.py", line 789, in _start
self._proc = subprocess.Popen(
File "/usr/lib/python3.8/subprocess.py", line 858, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1605, in _execute_child
errpipe_read, errpipe_write = os.pipe()
OSError: [Errno 24] Too many open files


/24 works

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.