经常使用python检测服务器是否能ping通, 程序是否正常运行(检测对应的端口是否正常)
以前使用shell脚本的写法如下:
复制代码 代码如下:
PINGRET=$( ping www.baidu.com -c 2 | grep "icmp_" ); if [ -z $PINGRET ]; then echo "ping fail"; else echo "ping ok"; fi
或者
复制代码 代码如下:
ping -c 2 www.baidu.com|grep "icmp_" && echo 'ping ok' || echo 'ping fail'
代码示例:
复制代码 代码如下:
import os
import socket
import subprocess
server='www.baidu.com'
def pingServer(server):
result=os.system('ping '+server+' -c 2')
if result:
print '服务器%s ping fail' % server
else:
print '服务器%s ping ok' % server
print result
def pingServerCall(server):
fnull = open(os.devnull, 'w')
result = subprocess.call('ping '+server+' -c 2', shell = True, stdout = fnull, stderr = fnull)
if result:
print '服务器%s ping fail' % server
else:
print '服务器%s ping ok' % server
fnull.close()
def check_aliveness(ip, port):
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:
sk.connect((ip,port))
print 'server %s %d service is OK!' %(ip,port)
return True
except Exception:
print 'server %s %d service is NOT OK!' %(ip,port)
return False
finally:
sk.close()
return False
if name=='main':
pingServerCall(server)
pingServer(server)
check_aliveness('192.168.230.128', 6379)
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8