Python is often used to check whether the server can be pinged and whether the program runs properly (check whether the corresponding port is normal)
Previously, shell scripts were written as follows:
Copy codeThe Code is as follows:
PINGRET = $ (ping www.baidu.com-c 2 | grep "icmp _"); if [-z $ PINGRET]; then echo "ping fail"; else echo "ping OK"; fi
Or
Copy codeThe Code is as follows:
Ping-c 2 www.baidu.com | grep "icmp _" & echo 'Ping OK '| echo 'Ping fail'
Sample Code:
Copy codeThe Code is as follows:
#! /Usr/bin/python
# Encoding = UTF-8
# Filename: net_is_normal.py
Import OS
Import socket
Import subprocess
# Determine whether the network is normal
Server = 'www .baidu.com'
# Check whether the server can be pinged. When the program runs, the command running information is displayed in the standard output.
Def pingServer (server ):
Result = OS. system ('ping' + server + '-c 2 ')
If result:
Print 'server % s ping fail '% server
Else:
Print 'server % s ping OK '% server
Print result
# Locate the program output to/dev/null. Otherwise, the running information of the command will be displayed in the standard output when the program is running.
Def pingServerCall (server ):
Fnull = open (OS. devnull, 'w ')
Result = subprocess. call ('ping' + server + '-c 2', shell = True, stdout = fnull, stderr = fnull)
If result:
Print 'server % s ping fail '% server
Else:
Print 'server % s ping OK '% server
Fnull. close ()
# It can be used to check whether the program is normal. If it detects whether redis is normal, it checks whether port 6379 of redis is normal.
# Check whether ssh is normal, that is, check whether ssh port 22 is normal
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
Failed t 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 ', 192)