#!/usr/bin/env python3
# coding=utf-8
import requests
import json
import boto3
headers = {'Content-Type': 'application/json-rpc'}
#url = 'http://%s/zabbix/api_jsonrpc.php' % server_ip
url = 'http://xxxxxxxx/zabbix/api_jsonrpc.php'
#######获得aws中的ip地址
def getEc2Ip():
ec2 = boto3.resource('ec2') # 使用EC2服务
#instance = ec2.Instance('你的实例id') # 获取一个EC2实例(一台机器)
#state = instance.state # 获取实例的当前状态,返回是一个字典
'''
state说明:
0 : pending
16 : running
32 : shutting-down
48 : terminated
64 : stopping
80 : stopped
'''
# 返回实例的一个或多个网络接口信息
#attrs = instance.network_interfaces_attribute
# 返回实例的公有ip,每次重启后该ip会改变
#publicIp = instance.public_ip_address
# 返回实例的私有ip,每次重启后该ip不会改变
#privateIp = instance.private_ip_address
# 停止一个实例,返回一个字典对象
#stop_dic = instance.stop()
# 等待一个实例完成停止操作
#instance.wait_until_stopped()
# 启用一个实例,返回一个字典对象
#start_dic = instance.start()
# 等待一个实例到它正常运行
#instance.wait_until_running()
# 也可以选出正在运行的所有实例
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
)
print(len(list(instances)))
#print(len(instances))
ec2ip=[]
for instance in instances:
print(instance.private_ip_address)
ec2ip.append(instance.private_ip_address)
ec2ipSet=set(ec2ip)
return ec2ipSet
# 获取token
def getToken(username, passwd):
#username = 'yonghui.wang'
#passwd = '123456'
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": username,
"password": passwd
},
"id": 0,
"auth": None,
}
request = requests.post(url=url, headers=headers, data=json.dumps(data))
print(request)
dict1 = json.loads(request.text)
print(dict1)
print(dict1['result'])
return dict1['result']
# 从api获取主机信息,
def getHosts(token_num):
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 2,
"auth": token_num,
}
request = requests.post(url=url, headers=headers, data=json.dumps(data))
dict = json.loads(request.content)
# print dict['result']
return dict['result']
# 整理信息,输出想要的信息,组合成字典,我这边提出ip。
def getProc(data):
dict = {}
list = data
for i in list:
host = i['host']
inter = i['interfaces']
for j in inter:
ip = j['ip']
dict[host] = ip
return dict
# 排序ip列表
def getData(dict):
data = dict
ip_list = []
for key in data.keys():
ip = data[key]
ip_list.append(ip)
ip_list = list(set(ip_list))
ip_list.sort()
return set(ip_list)
# 整理输出ip
def getGroup(ip_list):
ip_group = {}
ips = ip_list
for i in ips:
print(i)
if __name__ == "__main__":
username = 'xxxxx'
passwd = '123456'
token_num = getToken(username, passwd)
data = getHosts(token_num)
hosts = getProc(data)
ip_list = getData(hosts)
getGroup(ip_list)
ec2ipSet=getEc2Ip()
setcha=ec2ipSet - ip_list
print(setcha)
for i in list(setcha):
print(i)