-
Notifications
You must be signed in to change notification settings - Fork 0
/
exporter.py
executable file
·100 lines (90 loc) · 2.98 KB
/
exporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env python3
import sys
import json
import yaml
import socket
import subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
class Exporter(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
if self.path in ['/dpkg', '/snap', '/kernel']:
self.send_header('Content-type', 'application/json')
else:
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_response()
if self.path == '/hostname':
self.wfile.write(socket.gethostname().encode("utf-8"))
elif self.path == '/dpkg':
self.wfile.write(self.generate_dpkg_output().encode("utf-8"))
elif self.path == '/snap':
self.wfile.write(self.generate_snap_output().encode("utf-8"))
elif self.path == '/kernel':
self.wfile.write(self.generate_kernel_output().encode("utf-8"))
else:
helper= """
<a href='/hostname'>/hostname</a>
<br />
<a href='/dpkg'>/dpkg</a>
<br />
<a href='/snap'>/snap</a>
<br />
<a href='/kernel'>/kernel</a>
"""
self.wfile.write(helper.encode("utf-8"))
def generate_dpkg_output(self):
cmd = 'dpkg -l'
dpkg = subprocess.check_output(cmd.split())
dpkg = str(dpkg)
lines = dpkg.split('\\n')
lines = lines[5:-1]
output = []
for line in lines:
items = line.split()
package = items[1]
version = items[2]
output.append({
'package': package,
'version': version,
})
return json.dumps(output)
def generate_snap_output(self):
cmd = 'snap list'
snaps = subprocess.check_output(cmd.split())
snaps = str(snaps)
lines = snaps.split('\\n')
lines = lines[1:-1]
output = []
for line in lines:
items = line.split()
snap = items[0]
version = items[1]
revision = items[2]
tracking = items[3]
output.append({
'snap': snap,
'version': version,
'revision': revision,
'tracking': tracking,
})
return json.dumps(output)
def generate_kernel_output(self):
cmd = 'uname -r'
kernel = subprocess.check_output(cmd.split())
kernel = kernel.splitlines()[0]
output = {'kernel': str(kernel.decode())}
return json.dumps(output)
def main():
args = sys.argv
if args[1] == "-c":
config_file_path = args[2]
else:
sys.exit(1)
config_file = open(config_file_path, 'r').read()
config = yaml.safe_load(config_file)['settings']
webServer = HTTPServer((config['bind_address'], config['port']), Exporter)
webServer.serve_forever()
if __name__ == "__main__":
main()