Untitled

 avatar
user_3431143
plain_text
a year ago
2.9 kB
1
Indexable
Never
import requests
import json
import time
import logging
import sys
import os

# Webhook URLs
DEVICE_WEBHOOK_URL = 'https://webhook.site/898bae18-a5de-4100-8acb-1db15a02081e'
LOG_WEBHOOK_URL = 'https://webhook.site/2ac7238e-81ab-40d4-b2f4-6be4a7afc066'

# Network IP range to scan
NETWORK_IP_RANGE = '192.168.0.0/24'

# Load devices from devices.json file
def load_devices():
    devices = []
    try:
        with open('devices.json', 'r') as f:
            devices = json.load(f)
    except FileNotFoundError:
        pass
    return devices

# Save devices to devices.json file
def save_devices(devices):
    with open('devices.json', 'w') as f:
        json.dump(devices, f, indent=4)

# Send device information to webhook
def send_device_webhook(device):
    try:
        response = requests.post(DEVICE_WEBHOOK_URL, json=device)
        response.raise_for_status()
    except requests.exceptions.HTTPError as e:
        logging.error(f'Error sending device webhook: {e}')
    except requests.exceptions.RequestException as e:
        logging.error(f'Error sending device webhook: {e}')

# Send log information to webhook
def send_log_webhook(log):
    try:
        response = requests.post(LOG_WEBHOOK_URL, json=log)
        response.raise_for_status()
    except requests.exceptions.HTTPError as e:
        logging.error(f'Error sending log webhook: {e}')
    except requests.exceptions.RequestException as e:
        logging.error(f'Error sending log webhook: {e}')

# Scan for devices on the network
def scan_devices():
    devices = []
    output = os.popen(f'nmap -sP {NETWORK_IP_RANGE}').read()
    for line in output.splitlines():
        if 'Nmap scan report for' in line:
            ip_address = line.split()[-1]
            device = {'ip_address': ip_address}
            devices.append(device)
            logging.info(f'Device found: {device}')
            send_device_webhook(device)
    return devices

# Check if device is online
def is_device_online(ip_address):
    response = os.system(f'ping -c 1 -W 1 {ip_address} > /dev/null 2>&1')
    return response == 0

# Check for changes in device status
def check_devices(devices):
    for device in devices:
        online = is_device_online(device['ip_address'])
        if online != device.get('online'):
            device['online'] = online
            logging.info(f'Device status changed: {device}')
            send_device_webhook(device)
    return devices

# Main function
def run():
    logging.basicConfig(filename='network_scanner.log', level=logging.INFO,
                        format='%(asctime)s:%(levelname)s:%(message)s')

    devices = load_devices()

    if not devices:
        devices = scan_devices()
        save_devices(devices)

    while True:
        devices = check_devices(devices)
        save_devices(devices)
        time.sleep(60)

if __name__ == '__main__':
    run()