8/7 工作总结

1.利用 ansible 自动化工具,获取相应主机的信息

(1) 调用接口得到相应的 ip 链表  (http 协议)

def getHostInfo():
    HostIPList = []
    url = 'http://cmdb.mwbyd.cn/api/host/host/'
    r = requests.get(url)
    result_json = r.json()
    count = 0
    while count != result_json['count']:
        url = url if count == 0 else result_json['next']
        r = requests.get(url)
        result_json = r.json()

        result = result_json['results']
        for host in result:
            HostIPList.append(host['ip'])
            count += 1
        HostIPList.sort()
    return HostIPList

(2)调用 ansible python api 利用 ssh 协议获取相应ip的网络信息,系统信息(json 解析数据)

  1 class MyInventory(Inventory):
  2     def __init__(self, resource):
  3 
  4         self.resource = resource
  5         self.inventory = Inventory(host_list=[])
  6         self.gen_inventory()
  7 
  8     def my_add_group(self, hosts, groupname, groupvars=None):
  9         """
 10         add hosts to a group
 11         """
 12         my_group = Group(name=groupname)
 13 
 14         # if group variables exists, add them to group
 15         if groupvars:
 16             for key, value in groupvars.iteritems():
 17                 my_group.set_variable(key, value)
 18 
 19         # add hosts to group
 20         for host in hosts:
 21             # set connection variables
 22             hostname = host.get("hostname")
 23             hostip = host.get('ip', hostname)
 24             hostport = host.get("port")
 25             username = host.get("username")
 26             password = host.get("password")
 27             ssh_key = host.get("ssh_key")
 28             my_host = Host(name=hostname, port=hostport)
 29             my_host.set_variable('ansible_ssh_host', hostip)
 30             my_host.set_variable('ansible_ssh_port', hostport)
 31             my_host.set_variable('ansible_ssh_user', username)
 32             my_host.set_variable('ansible_ssh_pass', password)
 33             my_host.set_variable('ansible_ssh_private_key_file', ssh_key)
 34 
 35             # set other variables
 36             for key, value in host.iteritems():
 37                 if key not in ["hostname", "port", "username", "password"]:
 38                     my_host.set_variable(key, value)
 39             # add to group
 40             my_group.add_host(my_host)
 41 
 42         self.inventory.add_group(my_group)
 43 
 44     def gen_inventory(self):
 45         """
 46         add hosts to inventory.
 47         """
 48         if isinstance(self.resource, list):
 49             self.my_add_group(self.resource, 'default_group')
 50         elif isinstance(self.resource, dict):
 51             for groupname, hosts_and_vars in self.resource.iteritems():
 52                 self.my_add_group(hosts_and_vars.get("hosts"), groupname, hosts_and_vars.get("vars"))
 53 
 54 
 55 class MyRunner(MyInventory):
 56     def __init__(self, *args, **kwargs):
 57         super(MyRunner, self).__init__(*args, **kwargs)
 58         self.results_raw = {}
 59     def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*',
 60             become=False, become_method='sudo', become_user='root', become_pass='', transport='paramiko'):
 61         hoc = Runner(module_name=module_name,
 62                      module_args=module_args,
 63                      timeout=timeout,
 64                      inventory=self.inventory,
 65                      pattern=pattern,
 66                      forks=forks,
 67                      become=become,
 68                      become_method=become_method,
 69                      become_user=become_user,
 70                      become_pass=become_pass,
 71                      transport=transport
 72                      )
 73         self.results_raw = hoc.run()
 74         return self.results_raw
 75 
 76     @property
 77     def results(self):
 78         result = {'failed': {}, 'ok': {}}
 79         dark = self.results_raw.get('dark')
 80         contacted = self.results_raw.get('contacted')
 81         if dark:
 82             for host, info in dark.items():
 83                 result['failed'][host] = info.get('msg')
 84 
 85         if contacted:
 86             for host, info in contacted.items():
 87                 if info.get('invocation').get('module_name') in ['raw', 'shell', 'command', 'script']:
 88                     if info.get('rc') == 0:
 89                         result['ok'][host] = info.get('stdout') + info.get('stderr')
 90                     else:
 91                         result['failed'][host] = info.get('stdout') + info.get('stderr')
 92                 else:
 93                     if info.get('failed'):
 94                         result['failed'][host] = info.get('msg')
 95                     else:
 96                         result['ok'][host] = info.get('changed')
 97         return result
 98 
 99 
100 def getHostInfoByIp(ip_list):
101     resource = []
102     for ip in ip_list:
103         resource.append({
104             "hostname": ip,
105             "port": "22",
106             "username": "root",
107             "password": "xxx",
108         })
109     runner = MyRunner(resource)
110     result = runner.run(module_name='setup', module_args='')
111     if not result.has_key("contacted"):
112         return False
113     contacted = result.get('contacted')
114     hostinfo_list = []
115     for k, v in contacted.items():
116         ansible_facts = v.get('ansible_facts')
117         ansible_devices = ansible_facts.get('ansible_devices')
118         disk = {}
119         for d, v in ansible_devices.items():
120             disk[d] = v['size']
121         ansible_processor = ansible_facts.get('ansible_processor')
122 
123         system_type = ansible_facts.get("ansible_distribution")
124         if system_type.lower() == "freebsd":
125             system_version = ansible_facts.get("ansible_distribution_release")
126             cpu_cores = ansible_facts.get("ansible_processor_count")
127         else:
128             system_version = ansible_facts.get("ansible_distribution_version")
129             cpu_cores = ansible_facts.get("ansible_processor_vcpus")
130 
131         cpu = cpu_cores
132         if len(ansible_processor) > 0:
133             cpu = ansible_processor[0] + ' * ' + unicode(cpu_cores)
134 
135         # 遍历 ansible_facts 字典
136         network_card = {}
137         for key,value in ansible_facts.items():
138             if (type(value) is types.DictType) and value.has_key('promisc'):
139                 network_card[key] = value
140 
141         hostinfo_list.append({
142             'ip': k,
143             'kernel': ansible_facts.get('ansible_kernel'),
144             'hostname': ansible_facts['ansible_hostname'],
145             'memory': ansible_facts.get('ansible_memtotal_mb'),
146             'cpu': cpu,
147             'sn': ansible_facts.get('ansible_product_serial'),
148             'disk': json.dumps(disk),
149             'os_name': system_type + ' ' + system_version + ' ' + ansible_facts.get('ansible_architecture'),
150             'mac': ansible_facts.get("ansible_default_ipv4").get("macaddress"),
151             'network': ansible_facts.get("ansible_default_ipv4").get("network"),
152             'gateway': ansible_facts.get("ansible_default_ipv4").get("gateway"),
153             'netmask': ansible_facts.get("ansible_default_ipv4").get("netmask"),
154             'fqdn': ansible_facts.get("ansible_fqdn"),
155             'network_card':json.dumps(network_card)
156         })
157     return hostinfo_list
View Code

(3)将获取的数据存到数据库中,调用接口(http协议,身份验证)

 1 class CMDBApi():
 2 
 3     token = ''
 4     cmdb_url = 'http://test.cmdb.mwbyd.cn'
 5     api = '/api/host/info/'
 6     headers = {"Content-Type": "application/json"}
 7 
 8     def __init__(self):
 9         state, token = self.getToken()
10         if state:
11             self.headers['Authorization'] = 'Token ' + token
12 
13     def getToken(self):
14         try:
15             response = requests.post(self.cmdb_url + '/api/tokenauth/' + '?format=json',
16                                      data=json.dumps({'username': 'cmdb', 'password': 'mwbyd,123'}),
17                                      headers={"Content-Type": "application/json"})
18             if response.status_code != 200:
19                 return False, 'fail!'
20             data = json.loads(response.text)
21             return True, data['token']
22         except Exception, ex:
23             return False, str(ex)
24 
25     def post(self,par):
26         try:
27             response = requests.post(self.cmdb_url + self.api + '?format=json',data=json.dumps(par),headers=self.headers)
28             if response.status_code < 200 or response.status_code >= 300:
29                 return False, 'fail!'
30             data = json.loads(response.text)
31             return True, data
32         except Exception, ex:
33             return False, str(ex)
34 
35     def delete(self):
36         try:
37             response = requests.delete(self.cmdb_url + self.api, headers=self.headers)
38             if response.status_code != 200:
39                 return False, 'fail!'
40             data = json.loads(response.text)
41             return True, 'succ!'
42         except Exception, ex:
43             return False, str(ex)
View Code
1 if __name__ == "__main__":
2     cmdb_api = CMDBApi()
3     cmdb_api.delete()    #删除旧数据
4     ip_list = getHostInfo()
5     hostinfo_list = getHostInfoByIp(ip_list)
6     for hostinfo in hostinfo_list:
7         cmdb_api.post(hostinfo)
View Code

(4)从数据库中读取数据并传入到前端,显示(前端页面的显示)

 

posted @ 2017-08-07 23:46  in_the_way  阅读(362)  评论(0编辑  收藏  举报