import
urllib.request
import
json
import
re
url
=
'http://XXXXXXXXXXXXXXXX/api_jsonrpc.php'
username
=
'Admin'
password
=
'XXXXX'
def
requestJson(url,values):
data
=
json.dumps(values).encode(
'utf-8'
)
req
=
urllib.request.Request(url, data, {
'Content-Type'
:
'application/json-rpc'
})
response
=
urllib.request.urlopen(req, data)
a
=
response.read().decode(encoding
=
'utf-8'
)
output
=
json.loads(a)
try
:
message
=
output[
'result'
]
except
:
message
=
output[
'error'
][
'data'
]
print
(message)
quit()
return
output[
'result'
]
def
authenticate(url, username, password):
values
=
{
'jsonrpc'
:
'2.0'
,
'method'
:
'user.login'
,
'params'
: {
'user'
: username,
'password'
: password
},
'id'
:
'0'
}
idvalue
=
requestJson(url,values)
return
idvalue
auth
=
authenticate(url,username,password)
def
groups(auth):
values
=
{
"jsonrpc"
:
"2.0"
,
"method"
:
"hostgroup.get"
,
"params"
:{
"output"
:[
"groupid"
,
"name"
],
},
'auth'
: auth,
'id'
:
'1'
}
output
=
requestJson(url,values)
return
output
def
hosts(auth,a):
values
=
{
"jsonrpc"
:
"2.0"
,
"method"
:
"host.get"
,
"params"
:{
"output"
:[
"groupid"
,
"name"
],
"groupids"
: a,
},
'auth'
: auth,
'id'
:
'1'
}
output
=
requestJson(url,values)
return
output
def
items(auth,a):
values
=
{
"jsonrpc"
:
"2.0"
,
"method"
:
"item.get"
,
"params"
:{
"output"
: [
"itemids"
,
"key_"
],
"hostids"
: a,
},
'auth'
: auth,
'id'
:
'1'
}
output
=
requestJson(url,values)
return
output
def
his(auth,itemids):
values
=
{
"jsonrpc"
:
"2.0"
,
"method"
:
"item.get"
,
"params"
:{
"output"
:
"extend"
,
"history"
:
0
,
"itemids"
: itemids,
"sortfield"
:
"itemid"
,
"sortorder"
:
"DESC"
,
"limit"
:
1
},
'auth'
: auth,
'id'
:
'1'
}
output
=
requestJson(url,values)
return
output
def
trigger(auth):
values
=
{
"jsonrpc"
:
"2.0"
,
"method"
:
"trigger.get"
,
"params"
: {
"output"
: [
"description"
,
],
"filter"
: {
"hostid"
:
"10108"
,
},
"selectItems"
:"",
"sortfield"
:
"hostname"
,
"sortorder"
:
"DESC"
},
'auth'
: auth,
'id'
:
'1'
}
output
=
requestJson(url,values)
return
output
def
chaxun(groupid,items_value):
host
=
hosts(auth, groupid)
host_name
=
[]
host_id
=
[]
for
i
in
host:
host_id.append(i[
'hostid'
])
host_name.append(i[
'name'
])
hostall
=
dict
(
zip
(host_id, host_name))
host_names
=
[]
host_ids
=
[]
for
i
in
host_id:
host_id_value
=
items(auth, i)
for
index, value
in
enumerate
(host_id_value):
for
k, v
in
value.items():
if
items_value
in
v:
host_ids.append(host_id_value[index][
'itemid'
])
host_names.append(i)
host_names_list
=
[]
for
i
in
host_names:
for
k, v
in
hostall.items():
if
i
in
k:
host_names_list.append(v)
history_value
=
[]
for
i
in
host_ids:
history
=
his(auth, i)
history_value.append(history[
0
][
'lastvalue'
])
host_value
=
dict
(
zip
(host_names_list, history_value))
return
host_value
ret
=
chaxun(
5
,
"ProcThreadCount.[2]"
)
print
(ret)