下面我分享一下我写的Python写的脚本,其中scan_machine.sh是我调用的用Shell写的关于Nmap扫描的脚本,scan_hostname.log是Nmap扫描的结果,里面内容是IP 主机名。
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
#!/usr/bin/env python
#create by:sfzhang 20140820
#coding=utf-8
import
os,sys
import
json
import
urllib2
import
datetime,time
from
urllib2
import
URLError
nmap_cmd
=
"/shell/machine/scan_machine.sh"
def
runCmd(command):
global
mail_cmd
mail_cmd
=
'''mail -s "Report on not monitor Hosts of Zabbix" shifeng_zhang88 < /shell/machine/result/result.txt'''
return
os.system(command)
runCmd(nmap_cmd)
def
nmap_host():
hostiplst
=
[]
hostnamelst
=
[]
f
=
file
(
'/shell/machine/result/scan_hostname.log'
)
for
line
in
f.readlines():
hostip
=
line.split()[
0
]
hostname
=
line.split()[
1
]
hostiplst.append(hostip)
hostnamelst.append(hostname)
hostnamelst.sort()
#print hostiplst
return
hostnamelst
f.close()
def
zabbix_host():
zabbixhostlst
=
[]
#based url and required header
url
=
"http://192.168.161.128/api_jsonrpc.php"
header
=
{
"Content-Type"
:
"application/json"
}
#request json
data
=
json.dumps(
{
"jsonrpc"
:
"2.0"
,
"method"
:
"host.get"
,
"params"
:{
"output"
:[
"hostid"
,
"name"
],
"filter"
:{
"host"
:""}
},
#auth id
"auth"
:
"Zabbix Auth ID"
,
"id"
:
1
,
})
#create request object
request
=
urllib2.Request(url,data)
for
key
in
header:
request.add_header(key,header[key])
#get host list
try
:
result
=
urllib2.urlopen(request)
except
URLError as e:
print
"The server could not fulfill the request."
,e.reason
else
:
reponse
=
json.loads(result.read())
result.close()
#print "Number of Hosts:",len(reponse['result'])
for
host
in
reponse[
'result'
]:
#print "Host ID:",host['hostid'],"Host Name:",host['name']
zbxhosts
=
host[
'name'
]
zabbixhostlst.append(zbxhosts)
zabbixhostlst.sort()
return
zabbixhostlst
def
main():
nmaphostlst
=
nmap_host()
zbxhostlst
=
zabbix_host()
diff
=
list
(
set
(nmaphostlst) ^
set
(zbxhostlst))
content
=
"\n"
nomonitorlst
=
[]
if
len
(diff) !
=
0
:
for
host
in
diff:
if
host
in
nmaphostlst:
nomonitorlst.append(host)
else
:
sys.exit()
#print zbxhostlst
string
=
'\n'
.join(nomonitorlst)
f
=
file
(
'/shell/machine/result/result.txt'
,
'w'
)
f.write(string)
f.flush()
f.close()
runCmd(mail_cmd)
if
__name__
=
=
"__main__"
:
main()
|
把脚本添加到crontab,每台会收到关于那些主机没有添加监控的信息。
总结:
1)Zabbix API相关信息可以查看官方详细资料,看不懂英文的可以参考http://paperplane.ruhoh.com/zabbix/intro-to-zabbix-api/这篇文章。
2)通过该脚本可以知道那些主机没有添加监控,希望对大家有帮助,如果有更好的解决方法欢迎多多交流。