一个类似于telnet的python脚本。
#!/usr/bin/python
#coding:utf-8
'''
1.判断服务是否正常
2.判断机器是否存活
'''
import os,socket,subprocess,sys
#把程序输出定位到/dev/null,否则会在程序运行时会在标准输出中显示命令的运行信息
def servercheck(ip):
with open(os.devnull,'w') as fnull:
result = subprocess.call('ping '+ip+' -c 2', shell = True, stdout = fnull, stderr = fnull)
if result != 0:
print '%s ping fail' % ip
else:
print '%s ping success' % ip
return
#可用于检测程序是否正常,如检测服务和端口
def servicecheck(ip, port):
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:
sk.connect((ip,port))
print '%s %d service is UP!' %(ip,port)
except Exception:
print '%s %d service is DOWN!' %(ip,port)
servercheck(ip)
finally:
sk.close()
return
if __name__ == '__main__':
if len(sys.argv) == 3:
ip=sys.argv[1]
port=sys.argv[2]
servicecheck(str(ip), int(port))
else:
print "Usage:ip port"
sys.exit(1)