• zabbix 扩展脚本


    #!/usr/bin/env python
    #encoding:utf8
    # desc: self-inspection
    # args:
    #     reboot :  reboot AP 
    #     check  :  check AP syslog
    #     getApNum: return AP Number Online
    #     checkApOnline: ok: return ok; false: return ap ip : local apInfo 读取这个文件开始测试是否在线
    
    import os
    import sys
    from paramikoHelper import myParamiko
    from time import sleep
    from telnetAP import rebTelnet
    import threading
    
    # AP IP信息文件
    apInfoFile='/opt/script/apInfo'
    
    # 全局线程锁
    lock = threading.RLock()
    
    # 多线程计数器
    class Counter:
        count = 0
    
        def __init__(self, count):
            self.count = count
    
        def add(self, n = 1):
            lock.acquire()
            self.count = self.count + n
            lock.release()
    
        def delete(self, n = 1):
            lock.acquire()
            self.count = self.count - n
            lock.release()
    
        def get(self):
            return self.count
    
    # 读取命令执行的结果
    def getRunCommRes(cmd):
        return os.popen(cmd).read().strip('
    ').strip(' ')
        
    # 获取所有AP的IP地址列表
    def getAllIP():
        return open(apInfoFile).read().split('
    ')[:-1]
        
    # 通用工具类
    # 规定:
    #    定义普通方法的时候,必须定义两个默认且两个参数 arg1 = "", arg2 = ""
    #    定义被threadBox调用的target方法的时候,
    #         要满足4个参数,且第一个参数为ip(threadBox定义的),后面如果没有指定参数,需要用默认参数 arg2 = "", arg3 = "", arg4 = ""
    #         只有一个参数IP时: def oTarget(ip, arg2 = "", arg3 = "", arg4 = ""):
    class CommonUtil:
    
        def __init__(self):
            pass
        
        # 多线程执行
        def threadBox(slef, myTarget, arg1 = "", arg2 = "", arg3 = ""):
            threads = []
            
            for ip in getAllIP():
                t = threading.Thread(target=myTarget, args=(ip, arg1, arg2, arg3))
                threads.append(t)
                t.start()
            
            for t in threads:
                t.join()
            
        # 获取设备在线时长
        def uptime(self, arg1 = "", arg2 = ""):
            print getRunCommRes("uptime | cut -d ',' -f1 | awk -F'up' '{print $2}'")
        
        # 获取设备网络配置    
        def netInfo(self, arg1 = "", arg2 = ""):
            ip = getRunCommRes("ip a show eth0 | grep inet | grep eth0 | awk '{print $2}'")
            gateway = getRunCommRes("ip route  | grep default | awk '{print $3}'")
            print ip,gateway
    
        # 获取设备联盟号
        def getPortalId(self, arg1 = "", arg2 = ""):
            print getRunCommRes('cat /usr/local/etc/chilli/wid')
            
        # 运行指定的脚本文件
        def runScript(self, arg1, arg2 = ""):
            print getRunCommRes('/opt/script/' + arg1)
        
        # ping Target
        def pingTarget(self, ip, res, downCount, args4 = ""):
            code = os.system('/bin/ping -c 1 -w 3 ' + ip + '>/dev/null')
            if code != 0:
                code1 = os.system('/bin/ping -c 1 -w 3 ' + ip + '>/dev/null')
                if code1 != 0:
                    res.append(ip.split('.')[-1])
                    downCount.add() 
                    
        # 获取AP在线数
        # :::ex251::: 判断是否还有192.168.188.251的IP地址可以ping通
        #             如果可以ping通表示还有AP没有修改IP地址
        # a= 表示一共多少台AP, d=表示有多少台掉线, ::后面的数字表示192.168.188.+数字表示AP的ip地址
        #
        def checkApOnline(self, arg1 = "", arg2 = ""):
            # 检查接口是否正常
            interfaceName = getRunCommRes('ip addr show| grep 192.168.188.254').split('scope global')[1].strip(' ').split(':')[0]
            code = os.system("ip link show " + interfaceName + " | grep 'state UP' 1>/dev/null 2>&1 ")
    
            if code != 0:
                if 'eth2' == interfaceName:
                    print "err;if=down:eth1,," + interfaceName
                else:
                    print "err;if=down:" + interfaceName
            else:
                res = []
                total = len(getAllIP())
                downCount = Counter(0)
                ms251 = ""
    
                # 检查是否还存在251 IP的AP信息
                state251 = os.system('/bin/ping -c 1 -w 3 192.168.188.251 >/dev/null')
                if state251 == 0:
                    ms251 = ':::ex251:::'
                
                self.threadBox(self.pingTarget, res, downCount)
                
                if len(res) == 0:
                    print  ms251 + 'ok;' + str(total)
                else:
                    print  ms251 + 'err;a=' + str(total) + ';d=' + str(downCount.get()) + '::' + str(res)        
        
        # reboot target
        def rebootTarget(self, ip, resDict, args3 = "", args4 = ""):
            try:
                sshobj = myParamiko(ip, 'root', 'password@123')
                resInfo = sshobj.run_cmd("reboot")
                resDict[ip] = resInfo["stdin"].strip('
    ')
                sleep(1)
                sshobj.close()
    
            except Exception, e:
                resDict[ip] = "Error: " + str(e)
                if 'Authentication failed' in str(e):
                    try:
                        rebTelnet(ip, 'admin', 'password')
                        resDict[ip] = "telRebootAp!"
    
                    except Exception, e1:
                        resDict[ip] = "Error: " + str(e1)
                        
        # 重启AP
        def reboot(self):
            resDict = {}
            
            self.threadBox(self.rebootTarget, resDict)
            
            print resDict 
        
    # 执行前环境初始化
    def initSysDev():
        # 检查chilli程序是否异常退出
        chilliNum = getRunCommRes('ps -aef | grep chilli| grep -v grep | wc -l')
        cwatchNum = getRunCommRes('ps -aef | grep cwatch| grep -v grep | wc -l ')
    
        #if int(chilliNum) == 0 and int(cwatchNum) == 0:
        if int(chilliNum) == 0 :
            os.system('/usr/local/sbin/cwatch.sh &')
    
        # 根据网络方式配置IP地址,方便和AP通信 
        os.system('ip addr del 192.168.188.254/24 dev eth1 1>/dev/null 2>&1')
        os.system('ip addr del 192.168.188.254/24 dev eth2 1>/dev/null 2>&1')
        os.system('ip addr del 192.168.188.254/24 dev eth3 1>/dev/null 2>&1')
    
        code = os.system('ifconfig | grep ^br0 >/dev/null')
        if code == 0:
            os.system('ip addr add 192.168.188.254/24 dev br0 1>/dev/null 2>&1')
        else:
            code1 = os.system("ip link show eth1 | grep 'state UP' 1>/dev/null 2>&1 ")
            if code1 == 0:
                os.system("ifconfig eth1:1 192.168.188.254 up 1>/dev/null 2>&1")
            else:
                os.system("ifconfig eth2:1 192.168.188.254 up 1>/dev/null 2>&1")
    
    # 执行开始            
    def main():
        initSysDev()
    
        ComUtil = CommonUtil()
        
        if len(sys.argv) == 1:
            print "please add args!"
    
        elif len(sys.argv) == 2:
            myFun = getattr(ComUtil, sys.argv[1])
            myFun()
        
        elif len(sys.argv) == 3:
            myFun = getattr(ComUtil, sys.argv[1])
            myFun(sys.argv[2])
        
        elif len(sys.argv) == 4:
            myFun = getattr(ComUtil, sys.argv[1])
            myFun(sys.argv[2], sys.argv[3])
        
        else:
            print "args Error!"
       
        
    if __name__ == "__main__":
        main()
  • 相关阅读:
    Anaconda使用命令
    排序算法3--插入排序--希尔排序(缩小增量排序)
    排序算法2--插入排序--折半插入排序
    排序算法1--插入排序--直接插入排序
    排序总结---常用的排序算法总结,java和js实现
    前端兼容性问题
    js对象的几种创建方式和js实现继承的方式[转]
    js原型和原型链[转]
    性能优化的方法
    Http状态码
  • 原文地址:https://www.cnblogs.com/djoker/p/9371991.html
Copyright © 2020-2023  润新知