Python Check Internet Access Script

We had to check a linux server’s access status this week, so I write a python script to check and log internet status in the real.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'''
check ip address access every 5 seconds.
log into ping.log file.
show up times and down times.
requirement:
need install fping.(sudo apt install fping)
'''

import os
import time
from datetime import datetime
hostname = "google.com" #example

def check_one_time():
response = os.system("fping " + hostname)
if response == 0:
msg = "OK - " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open('ping.log', 'a') as myfile:
myfile.write(msg + ',\n')
print '----------------------------------- up -----------------------------------'
return True
else:
msg = "NG - " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open('ping.log', 'a') as myfile:
myfile.write(msg + ',\n')
print '---------------------------------- down ----------------------------------'
return False

up_times = 0
down_times = 0
while True:
if check_one_time():
up_times += 1
else:
down_times += 1
msg = 'down_times = ' + str(down_times) + '; up_times = ' + str(up_times)
with open('ping.log', 'a') as myfile:
myfile.write(msg + ',\n\n')
time.sleep(5)