Python Code to Ping Servers

Python Code to Ping Servers

This is sort of a follow up from my tip last week - Cut Command a couple of examples.

Below is the code, the first section is setting the variables to read the config file, stored in certain directories, and also write out to a log file.

The code is very simple to do the ping and will write out if it responds or if it's down.

Very small easy script if you do have a long list of servers that you need to check.

import os							
import subprocess				
import sys							

filename = sys.argv[0]												myping = "ping -n 2 "													
logdir = os.getenv("logs")				
logfile = 'dns_ping.log'										
logfilename=os.path.join(logdir, logfile)											
confdir = os.getenv("my_config")													
conffile = ('dns1_list.txt')									
conffilename=os.path.join(confdir, conffile)									
f = open(logfilename, "w")											
for server in open(conffilename):									
  ret = subprocess.call(myping + server, shell=True,stdout=f,stderr=subprocess.STDOUT)	
  if ret == 0:						
    f.write (server.strip() + " is alive" + "\n")					
  else: 
    f.write (server.strip() + " did not respond" + "\n")
	 
print ("\n\tYou can see the results in the logfile : "+ logfilename);	

I am always interested in your thoughts so if you have any comments or feedback then please feel free to add any comments, or you can mail me  here.

Related Posts Plugin for WordPress, Blogger... 

 

Emails and Unsubscribing

Emails and Unsubscribing

Don't forget to check out our other pages