libpython-zabbixを利用する方が便利がいいケド(作ってる途中で存在を知った)
供養のために残しておく
今後、こちらのスクリプトの出番が来たとき用のメモ↓
どうせなら標準ライブラリだけで動くように改変した方が良い。⇒ requestsをurllibに変更するだけで行けるはず
#!/usr/bin/env python3
from getpass import getpass
import requests
import json
import argparse
import datetime as datetime
zabbix = "http://zabbix-server/zabbix/api_jsonrpc.php"
# --------------------------------------------------------------------- #
parser = argparse.ArgumentParser(description='Close Alarms on Zabbix')
parser.add_argument('-u','--user',help="Zabbix User Name")
parser.add_argument('-p','--password',help="Zabbix User Password")
parser.add_argument('-s','--server',help="Zabbix Server URL ** Default is "+ "'" + zabbix + "'" )
parser.add_argument('-F', '--time-from',help="FORMAT: YYYYmmddHHMMSS" )
parser.add_argument('-T', '--time-till',help="FORMAT: YYYYmmddHHMMSS" )
parser.add_argument('-H', '--host', help="Target Host Name" )
parser.add_argument('-N', '--name', help="Target Event Name" )
parser.add_argument('-i', '--interactive', action="store_true", help="Interactive Mode" )
parser.add_argument('-d', '--dry-run', action="store_true", help="Dry-run Mode" )
args = parser.parse_args()
# --------------------------------------------------------------------- #
if args.server is not None:
zabbix = args.server
# --------------------------------------------------------------------- #
def zabbix_post(method,params,auth):
headers = {
'content-type': 'application/json'
}
json_data = {
"jsonrpc" : "2.0",
"method" : method,
"params" : params,
"id" : 1,
"auth" : auth
}
response = requests.post(
zabbix,
data = json.dumps(json_data),
headers = headers
)
return response
def time_unix2str(unixtime):
int_unixtime = int(unixtime)
dt = datetime.datetime.fromtimestamp(int_unixtime).strftime('%Y-%m-%d %H:%M:%S')
return dt
def time_str2unix(timestr):
str_timestr = str(timestr)
dt = datetime.datetime.strptime(str_timestr, '%Y%m%d%H%M%S').strftime('%s')
return dt
def usr_login(user=None,password=None):
if user is None:
user = input("User: ")
if password is None:
password = getpass(prompt = "Password: ")
try:
response = zabbix_post("user.login", {"user": user ,"password": password },None)
access_token = response.json()["result"]
except :
print("Login Failed")
exit(107)
return access_token
def get_hostid(access_token,hostname):
response = zabbix_post("host.get", {"filter": { "host" : hostname } },access_token)
try:
hostid = response.json()["result"][0]["hostid"]
except:
print(hostname + " was Not Found.")
exit(108)
return hostid
def search_problems(access_token,host,timefrom,timetill):
params = {"output": [ "clock","eventid","objectid","name" ] }
if host is not None:
hostid = get_hostid(access_token,host)
params.update(hostids=[ hostid ])
if timefrom is not None:
timefrom_unix = time_str2unix(timefrom)
params.update(time_from = timefrom_unix)
if timetill is not None:
timetill_unix = time_str2unix(timetill)
params.update(time_till = timetill_unix)
problems = zabbix_post("problem.get", params ,access_token)
problems_dict = problems.json()["result"]
return problems_dict
def close_problems(access_token,eventids):
message = "closed by api"
close_events = zabbix_post("event.acknowledge", {"eventids": eventids , "action" : 5, "message" : message },access_token)
return close_events
def main():
access_token = usr_login(args.user,args.password)
problems = search_problems(access_token, args.host, args.time_from, args.time_till )
target_eventids = []
for e in problems :
e.update(clock=time_unix2str(e["clock"]))
if args.name is None:
if args.interactive is True:
print(e)
target_eventids.append(e["eventid"])
elif args.name in e["name"]:
if args.interactive is True:
print(e)
target_eventids.append(e["eventid"])
if args.interactive is True:
answer = input("OK?(Y/[n] >>")
if answer != "Y":
print("canceled by user")
exit(1)
if args.dry_run is True:
exit(0)
close = close_problems(access_token,target_eventids)
if __name__ == "__main__":
main()