Certainly! Below is a Python script that checks if devices in an office (specified by a 5-digit office ID) are online or offline. This script transforms the office ID input to a corresponding IP address range and pings each device in the office every second to check its status.
Make sure to run this script with appropriate permissions, and you'll need to have ping3 installed for pinging. You can install it using pip:
pip install ping3
Here's the Python script:
import socket
import time
import threading
from ping3 import ping, PingError
def get_ip_from_office_id(office_id):
return f"pth{office_id}".ljust(10, '0') # Make it 'pthxxxxx' format
def resolve_ip(office_id):
ip_prefix = '192.168.1.' # Assuming the office devices are in this subnet
return f"{ip_prefix}{int(office_id[-1]) + 8}" # Get the last digit and add to 8
def ping_device(ip):
try:
response = ping(ip, timeout=1)
if response:
print(f"Device {ip} is online")
else:
print(f"Device {ip} is offline")
except PingError:
print(f"Device {ip} is offline or unreachable")
def check_office_devices(office_id):
transformed_id = get_ip_from_office_id(office_id)
office_ip = resolve_ip(office_id)
# Assuming you want to check IPs x.x.x.1 to x.x.x.10
for i in range(1, 11):
ip = f"{office_ip[:-1]}{i}"
ping_device(ip)
time.sleep(1) # Wait 1 second before rechecking
def main():
office_id = input("Enter the 5-digit office ID: ")
if not (office_id.isdigit() and len(office_id) == 5):
print("Invalid office ID. It must be a 5-digit number.")
return
while True:
check_office_devices(office_id)
if __name__ == "__main__":
main()
Explanation:
-
Function get_ip_from_office_id(office_id): Converts the office ID to a string formatted as pthxxxxx.
-
Function resolve_ip(office_id): This function calculates the IP address using the office ID. Here, it assumes the basic subnet structure of 192.168.1.x, where the last part is adjusted based on the last digit of the office ID.
-
Function ping_device(ip): Pings the specified IP. It will print whether the device is online or offline.
-
Function check_office_devices(office_id): Coordinates the process to ping devices from x.x.x.1 to x.x.x.10.
-
Main Loop: Continuously checks the status of the devices every second.
Note:
- Substitute the IP address prefix (
192.168.1.) with the actual subnet your office devices are on.
- This script will run indefinitely. You can stop it with
CTRL+C.
Make sure you test the script in an environment where you have permission to ping devices.