0x01 前言
前天我写了一篇文章:通过ping 监测服务器的网络状况 ,这脚本需要手动输入参数,这并不能满足我们自动化监控的需求。所以我还写了一个脚本,通过循环调用以达到不间断监控的需求。
0x02 思路
其实这个脚本很简单,通过while 循环调用ping 脚本,并且每次完成调用都睡眠60秒。
0x03 源代码
# -*- coding: UTF-8 -*-
#导入模块
import os
import time
# 循环暂停时间
sleep_time = 60
# 线路以及ip地址
server_ipaddr = {'ChinaTelecom': '10.1.1.1', 'ChinaUnicom': '10.1.1.2'}
#定义website_status_monitor_count
website_status_monitor_count = 1
#使用while 循环
while website_status_monitor_count == 1:
#使用历遍字典将参数传递到ping 脚本
for i in server_ipaddr:
website_status_monitor_run = os.popen(
'python3 /Users/terence/Documents/github/terence-Python-Proj/website_status_monitor/website_status_monitor.py -i ' +
server_ipaddr[i] + ' -n ' + '%s' % i)
#使用readlines 来读取shell 输出的内容
website_status_monitor_run_output = website_status_monitor_run.readlines()
#使用历遍列表获取其中的元素并打印
for output_str in website_status_monitor_run_output:
print(output_str.replace(' ', '\n'))
#打印分隔符
print('+' * 100 + '\n')
#休眠sleep_time 秒
time.sleep(sleep_time)
0x04 使用与输出
首先需要修改服务器名称与地址的字典:
server_ipaddr = {'ChinaTelecom': '10.1.1.1', 'ChinaUnicom': '10.1.1.2'}
你也可以修改休眠的时间:
sleep_time = 60
直接使用python 启动脚本:
python3 website_status_monitor_run.py
输出内容如下:
0x05 结语
这脚本的运行环境是Mac OS X,如果你想在Linux 下运行,可能需要做些修改。
完整的脚本可以点击下面的链接跳转到Github查看下载:























