1 #coding=utf8
2
3 """
4 CMDB接口调用
5 """
6 import csv
7 import json
8 import time
9
10 import requests
11 from requests.auth import HTTPDigestAuth
12
13 class getAPIInfo(object):
14
15 def __init__(self,api_url,username,password):
16 self.headers = {'Accept': 'application/json'}
17 self.base_url = 'http://xx.xx.xx.xx:8080'
18 self.api_url = api_url
19 self.username = username
20 self.password = password
21
22 def get_info(self):
23 headers = self.headers
24 base_url = self.base_url
25 api_url = self.api_url
26 username = self.username
27 password = self.password
28
29 authhandler = HTTPDigestAuth(username,password)
30 resp = requests.get(base_url + api_url, auth=authhandler, headers=headers)
31 content = json.loads(resp.text)
32 return content
33
34 class writeToCsv(object):
35 def __init__(self,data,info):
36 self.data = data
37 self.info = info
38
39 def write_to_csv(self):
40 rows = self.data
41 info = self.info
42 csvfile = "设备信息列表" + info + time.strftime('_%Y%m%d%H%M%S', time.localtime(time.time())) + ".csv"
43 # print(csvfile)
44 # 创建文件对象
45 f = open(csvfile, 'w')
46
47 # 通过文件创建csv对象
48 csv_write = csv.writer(f)
49
50 # writerow: 按行写入, writerows: 是批量写入
51 # 写入数据 取列表的第一行字典,用字典的key值做为头行数据
52 csv_write.writerow(rows[0].keys())
53
54 # 循环里面的字典,将value作为数据写入进去
55 for row in rows:
56 csv_write.writerow(row.values())
57
58 # 关闭打开的文件
59 f.close()
60 return "读写完成:"+csvfile
61
62 if __name__ == '__main__':
63 # # 1 - 查询设备信息列表 /plat/res/device
64 api_url = "/imcrs/plat/res/device?size=1000"
65 info = "device"
66
67 # 2-获取AC相关信息http://ip:8080/imcrs/wlan/acInfo/queryAcBasicInfo
68 # api_url = "/imcrs/wlan/acInfo/queryAcBasicInfo"
69 # info = 'acBasicInfo'
70
71 # 3 -查询Ap相关信息GET /imcrs/wlan/apInfo/queryApBasicInfo
72 # api_url = "/imcrs/wlan/apInfo/queryApBasicInfo"
73 # info = 'apBasicInfo'
74
75 # #4-查询设备类型列表/plat/res/category
76 # api_url = "/imcrs/plat/res/category"
77
78 # #5-查询资产列表/netasset/asset
79 # api_url = "/imcrs/netasset/asset"
80
81 # 获取API接口信息
82 username = '******'
83 password = '******'
84 # 1- 获取api接口信息
85 req = getAPIInfo(api_url,username,password)
86 content = req.get_info()
87 # print(content)
88
89 # #获取设备json数据
90 data = content[info]
91
92 # 2-调用写入csv类
93 write = writeToCsv(data,info)
94 resp = write.write_to_csv()
95 print(resp)