Commit 0cc592c1 authored by Tharani Ariyawansa's avatar Tharani Ariyawansa

monitor v1

parent b4aabe6c
import argparse, socket, time, json, datetime, platform, psutil, requests, pprint, uuid
from socket import getservbyname, getservbyport
import os
from time import sleep
from ping3 import ping
# parse args
parser = argparse.ArgumentParser(description='Monitoring script to send system info to a tracking server')
parser.add_argument('-d', '--dest', default='142.250.4.138',
help='API Endpoint for Monitoring Data (Defaults to http://localhost:8080/)')
parser.add_argument('-i', '--interval', default=5, type=int,
help='Interval between checks (Seconds. Defaults to 5 seconds)')
parser.add_argument('-a', '--attempts', default=30, type=int,
help='Attempts to send data when sending failes (Defaults to 30)')
parser.add_argument('-t', '--timeout', default=60, type=int,
help='Timeout between resend attempts (Seconds. Defaults to 60. If attempts is reached script will die)')
args = parser.parse_args()
# Factor in sleep for bandwidth checking
if args.interval >= 2:
args.interval -= 2
def write_to_file(file_to_write, message):
os.makedirs(os.path.dirname(file_to_write), exist_ok=True)
fh = open(file_to_write, "a")
fh.write(message + "\n")
fh.close()
def monitor():
# Hostname Info
hostname = socket.gethostname()
print("Hostname:", hostname)
# CPU Info
cpu_count = psutil.cpu_count()
cpu_usage = psutil.cpu_percent(interval=1)
print("CPU:\n\tCount:", cpu_count, "\n\tUsage:", cpu_usage)
# Memory Info
memory_stats = psutil.virtual_memory()
memory_total = memory_stats.total
memory_used = memory_stats.used
memory_used_percent = memory_stats.percent
print("Memory:\n\tPercent:", memory_used_percent, "\n\tTotal:", memory_total / 1e+6, "MB", "\n\tUsed:",
memory_used / 1e+6, "MB")
## Disk Info
disk_info = psutil.disk_partitions()
print("Disks:")
disks = []
for x in disk_info:
# Try fixes issues with connected 'disk' such as CD-ROMS, Phones, etc.
try:
disk = {"name": x.device}
print("-----------------------------------------------------------------\n")
except:
a = False
print("Average Delay time between links\n")
THRESHOLD = 0.25 # 250 milliseconds is the Comcast SLA threshold.
# SET YOUR PING INTERVAL HERE, IN SECONDS
INTERVAL = 1
# WHO SHOULD WE RUN THE PING TEST AGAINST
DESTINATION = "142.250.4.138" # "www.google.com"
# LOG TO WRITE TO WHEN PINGS TAKE LONGER THAN THE THRESHOLD SET ABOVE
i = datetime.datetime.now()
log_file = "logs/latency-tester." + i.strftime("%Y.%m.%d.%H.%M.%S") + ".log"
count = 0
header = f"Pinging {DESTINATION} every {INTERVAL} secs; threshold: {THRESHOLD} secs."
print(header)
write_to_file(log_file, header)
a = True
while a:
count += 1
latency = ping(DESTINATION)
# Do we want to write it to the log?
write_log = "Yes" if latency > THRESHOLD else "No"
line = f"Pinged {DESTINATION}; latency: {latency} secs; logging: {write_log}"
print(line)
write_to_file(log_file, line)
if count == 5:
a = False
sleep(INTERVAL)
def main():
# printing menu
while True: # running loop infinitely
# print options
print("Network Monitoring")
print("-" * 30) # printing headers
print("1. Continuous Monitoring")
print("2. Period Monitoring")
print("3. Quit")
print("-" * 30) # printing headers
choice = input("Enter any option from the above: ")
if choice == "1":
print("The monitoring will be done in every 30 seconds")
yes_no = input("Continue (yes/no): ").lower() # taking input and making all characters lower
if yes_no == "yes":
# if user chosen yes
while True:
monitor()
time.sleep(30) # run the function at every 30 seconds
elif yes_no == "no":
# is user chosen no
print("Continuing to main menu...")
else:
# if user chosen any other option other than yes and no
print("Invalid option chosen")
elif choice == "2":
print("The monitoring will be done in every 30 minutes")
yes_no = input("Continue (yes/no): ").lower() # taking input and making all characters lower
if yes_no == "yes":
# if user chosen yes
while True:
monitor()
time.sleep(1800) # run the function at every 1800 seconds (30 minutes)
elif yes_no == "no":
# is user chosen no
print("Continuing to main menu...")
else:
# if user chosen any other option other than yes and no
print("Invalid option chosen")
elif choice == "3":
print("Good Bye!")
break
else:
print("Invalid option chosen")
if __name__ == '__main__':
main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment