当前位置: 首页 > 后端技术 > Python

脚本自动关闭Zabbix中的down主机

时间:2023-03-25 20:59:59 Python

下面我使用Python通过Py-ZabbixAPI关闭Zabbix中的down主机。基本思路是1.获取前组的IP。2、使用telnet查看主机是否Down。3.关闭主机警告。python脚本非常依赖telnet的连接结果。如果网络不稳定,会直接影响结果。我得想办法解决这个问题。以下是脚本的初始小damo。新手一定要先测试一下脚本是否符合你的生产环境,然后再去正式环境执行#!/bin/envpythonimporttelnetlibimportpyzabbixfrompyzabbiximportZabbixAPIimportosweb=input("输入您的Zabbix-Web地址:")username=input("API用户:")passwd=input("密码:")groupids=input("HostGroup1:15\nHostGroup2:16\n输入你的组:")#checkYourPasswordtry:zapi=ZabbixAPI(url=web,user=username,password=passwd)print("authenticationsuccessful")zapi.do_request('user.logout')except:print("Userauthenticationerror!!Scriptexit")os._exit(0)#GetHostIPFromZabbixdefZabbixIP():zapi=ZabbixAPI(url=web,user=username,password=passwd)#获取输出result数字result1=zapi.do_request("host.get",{"groupids":groupids,"output":["name"],'countOutput':True})#输出结果带IPresult2=zapi.do_request("host.get",{"groupids":groupids,"output":["name"],"selectInterfaces":["interfaces","ip"]})host_count=int(result1.get(u'result'))#初始化IPList,稍后用于安装IPIPList=[]foriinrange(host_count):num=i#分别输出元组VeeeHostList=result2.get(u'result')[num]#print(VeeeHostList)#得到包含ip的元组eg:{interfaces:["ip":"0.0.0.0"]}HostIP=VeeeHostList.get('interfaces')#到元组中的数组["ip":"0.0.0.0"]IpTup=HostIP[0]Ip=IpTup.get(r"ip")#print(ip)IPList.append(Ip)zapi.do_request('user.logout')returnIPList#做telnet测试端口是否打开即检测服务器是否在线,如果不在线,关闭hostdeftelenetlib():WrongIpList=[]RightIpList=[]foripinIpGroup:try:tn=telnetlib.Telnet(host=ip,port=22,timeout=5)print("telnet连接失败")RightIpList.append(ip)except:print("thereissometimewrongwith"+ip+"!!!")WrongIpList.append(ip)returnWrongIpList,RightIpListdefUpdateHost():zapi=ZabbixAPI(url=web,user=username,password=passwd)forWinterfaceinIpWrongGroup:result3=zapi.do_request("host.get",{"output":"hostid","selectInterfaces":["interfaces","ip"],"filter":{"ip":Winterface}})result4=str(result3.get(u'result')).split('\'')hostid=result4[3]zapi.do_request("host.update",{"hostid":hostid,"status":1})用于IpRightGroup中的Rinterface:result3=zapi.do_request("host.get",{"output":"hostid","selectInterfaces":["interfaces","ip"],"filter":{"ip":Rinterface}})result4=str(result3.get(u'result')).split('\'')hostid=result4[3]zapi.do_request("host.update",{"hostid":hostid,"status":0})zapi.do_request('user.logout')IpGroup=ZabbixIP()IpWrongGroup,IpRightGroup=telenetlib()UpdateHost()诚挚的,有问题可以联系博主Telegram:@tingbob