一、检测主机是否存活

import  time
import subprocess
host_list = ['10.0.5.10','10.0.5.11','10.0.5.21','10.0.5.19','10.0.5.18','10.0.5.17','10.0.5.16','10.0.5.15','10.0.5.13','10.0.5.12','192.168.2.2']

def runCmd(cmd,host):
    start=time.time()
    res = subprocess.Popen(cmd,
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
    res.stdout.read().decode('gbk')
    run_time = time.time()-start
    if run_time > 1:
        return False
    else:
        return True

def runCmd2(weixin):
    res = subprocess.Popen(weixin,
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)

for host in host_list:
    cmd = 'ping %s -c 1'%host
    a = runCmd(cmd,host)
    if not a:
        weixin = '/usr/local/zabbix/alertscripts/weixin.sh caojin %s_not_ok'%host
        runCmd2(weixin)
View Code

主机不存活,使用企业微信报警

二、检测nginx是否启动,如果没有启动,启动它

import subprocess
import sys,os
port_test = "netstat -lntup|grep %s|wc -l" %sys.argv[1]

def cmd(result):
    obj=subprocess.Popen(result,
                     shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE
                     )
    port = obj.stdout.read().decode('gbk')
    return port

if __name__ == '__main__':
    port = int(cmd(port_test))
    if port == 0:
        print('not ok,try Start it')
        start='/usr/local/nginx/sbin/nginx'
        if os.path.exists(start):
            cmd(start)  # start nginx
            port2 = int(cmd(port_test))     # test port
            if port2 == 0:
                print('is not ok')
            else:
                print('ok')
        else:
            print('Path does not exist')
    else:
        print('port is ok')
View Code

测试结果

[root@Myjumpserver test]# netstat -lntup|grep 80
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      9911/nginx          
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      9911/nginx          
[root@Myjumpserver test]# python start.py 80
port is ok
[root@Myjumpserver test]# /usr/local/nginx/sbin/nginx -s stop
[root@Myjumpserver test]# netstat -lntup|grep 80
[root@Myjumpserver test]# python start.py 80
not ok,try Start it
ok
[root@Myjumpserver test]# netstat -lntup|grep 80
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      9977/nginx          
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      9977/nginx 

 定时检测

00 5 * * * /usr/bin/python3 /root/test/start.py 80>/dev/null 2>&1        # 每天早上5点执行

 三、备份文件。保留30天

import time
import datetime
import os
import shutil
from monitor_logger import Logger
from monitor_falcon import Falcon
import traceback

'''
from jin.cao
cd /etc/nginx && tar -zcf nginx_conf_bak_18.tgz conf.d/ stream.d/
mv /etc/nginx/nginx_conf_bak_18.tgz /usr/local/bin/monitor/nginxbak/20190711/nginx_conf_bak_18.tgz
'''
log_file = u"monitor_backup_up.log"
class Backup():
    def __init__(self, base_path, logger=None):
        self.logger = logger if logger else Logger(log_file).get_logger()
        self.falcon = Falcon(self.logger)
        self.base_path = base_path

    def mkdir_files(self):
        path_time = self.base_path + '/'+time.strftime('%Y%m%d') + '/'
        if not os.path.exists(path_time):
            os.makedirs(path_time)
        return path_time

    def command(self, cmd):
        os.popen(cmd)

    def backup(self,path_time):
        try:
            filename = 'nginx_conf_bak_%s.tgz'%(time.strftime('%H'))
            cmd1 = "cd /etc/nginx && tar -zcf " + filename + ' conf.d/ stream.d/'
            self.command(cmd1)
            cmd2 = "mv /etc/nginx/" + filename + ' '+path_time
            self.command(cmd2)
        except:
            self.logger.error(traceback.format_exc())

    def removedirs(self):
        oldpath = (datetime.datetime.now() - datetime.timedelta(days=29)).strftime("%Y%m%d")
        listpath =  os.listdir(self.base_path)
        tag = True
        while tag:
            if len(listpath) > 29:
                for dir in listpath:
                    if oldpath > dir:
                        rmdir = base_path + '/'+dir
                        try:
                            shutil.rmtree(rmdir)
                        except:
                            self.logger.error(traceback.format_exc())
                        listpath.remove(listpath[0])
                else:
                    tag = False
            else:
                tag = False

    def main(self):
        path_time = self.mkdir_files()
        self.backup(path_time)
        self.removedirs()

if __name__ == '__main__':
    base_path = '/usr/local/bin/monitor/nginxbak'
    backup = Backup(base_path)
    backup.main()
View Code

 

posted on 2018-12-24 10:50  可口_可乐  阅读(533)  评论(0)    收藏  举报