#!/usr/bin/env python
##
##check host and ports are UP or DOWN!
##read source file format :
##ip port port port ....
##
import os,sys,re
import subprocess
import socket
def runCheck(line):
if(line == ""):
return
ip_ports = line.split( )
ip = ip_ports[0]
p = subprocess.Popen(["ping -c 2 "+ ip],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True)
out = p.stdout.read()
regex = re.compile("time=\d*", re.IGNORECASE | re.MULTILINE)
if len(regex.findall(out)) > 0:
print "Server " + ip + " UP!"
for port in ip_ports[1:]:
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:
sk.connect((ip,int(port)))
print "Server " + ip + " port " + port + " OK!"
except Exception, e:
print "ERROR: Server " + ip + " port " + port + " not connect! " + repr(e)
sk.close()
else:
print "ERROR: Server " + ip + " DOWN!"
source = "ips.lst"
if os.path.exists(source):
file_obj = open("ips.lst")
for line in file_obj.readlines():
runCheck(line.strip())
exit()
else:
print "ERROR: source file is not exist;"
vim ips.lst
192.168.1.4 22 80
192.168.1.5 80
192.168.1.20
result:
Server 192.168.1.4 UP!
Server 192.168.1.4 port 22 OK!
Server 192.168.1.4 port 80 OK!
ERROR: Server 192.168.1.5 DOWN!
Server 192.168.1.20 UP!