Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #V2 of InternetWatcher - Added file flushing every X runs, to assist in Replication scenarios.
- #This scripts automatically polls the Google DNS server every 15 seconds to check that it has internet connectivity - It logs both LIVE and DEAD statuses to a formatted .csv file
- #Import required libraries
- import logging, time, socket, os, sys
- #Declare Variables
- ##Number of runs passed
- count = 0
- ##Last count where file was flushed
- lastCount = 0
- ##How many counts until it flushes file
- minCounter = 100
- ##Max number of iterations before it restarts itself - 5759 is roughly 24 hours
- maxCount = 5759
- #Define logging function
- ##file_name is the file name you want to force it to append to
- ##mode disables addHandler if anything other than "c"
- ##folderpath is the path to folder, leave it empty to put log files in executable folder
- def startupTask(file_name="", mode="c", folderpath=""):
- ##If the filename is nothing, then prepare a new file filename. Otherwise, the supplied filename should be used
- if file_name == "":
- t_fn = folderpath+time.strftime("%d%m20%y-%H%M%S",time.localtime())+".csv"
- else:
- t_fn = file_name
- ##Configure logging in the specific format
- logging.basicConfig(
- filename=t_fn,
- filemode="a",
- level=logging.INFO,
- datefmt="%d %b - %Y : %H:%M:%S",
- format="%(asctime)s , %(levelname)s , %(message)s")
- console = logging.StreamHandler()
- console.setLevel(logging.INFO)
- formatter = logging.Formatter("%(asctime)s , %(levelname)s , %(message)s","%d %b - %Y : %H:%M:%S")
- console.setFormatter(formatter)
- ##Add handler if equal to c, otherwise ignore
- if mode == "c":
- logging.getLogger('').addHandler(console)
- else:
- pass
- ##Return the file name
- return t_fn
- #Start logging
- cur_fn = startupTask("", "c", "")
- #Main Script
- while True:
- time.sleep(10)
- ##If the maximum count has been reached, restart the script
- ##Alternatively, kill the script.
- if count > maxCount:
- logging.shutdown()
- time.sleep(0.2)
- os.execv(sys.executable, ['python'] + sys.argv)
- ###quit()
- ##If the appropriate number of counts has passed, flush the log to disk and reopen the file for appending
- elif count == lastCount+minCounter:
- lastCount = count
- logging.shutdown()
- time.sleep(0.2)
- startupTask(cur_fn, "l")
- else:
- pass
- ##Attempt connection to Google DNS, log as success
- try:
- time.sleep(5)
- count = count + 1
- s = socket.create_connection(("8.8.8.8", 53),5)
- logging.info(str(count)+" , LIVE")
- ##If the connection fails, log as failure
- except:
- logging.warn(str(count)+" , DEAD")
Add Comment
Please, Sign In to add comment