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
101
102
103
104
105
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import socket
import getopt
import yaml
import os.path
from dns import resolver,reversename
own_directory = os.path.dirname(os.path.abspath(__file__))
lib = os.path.join(own_directory, '..')
if os.path.exists(os.path.join(lib, 'hostinfo')):
sys.path = [lib] + sys.path
from hostinfo import printer
def _get_data(path):
stream = file(path, 'r')
return yaml.load(stream)
def print_info(path, key=None, oneline=False, verbose=False):
data = _get_data(path)
p = printer.Printer(data, oneline, verbose)
p.info(key)
def _print_keys(data, prefix = ''):
for key in data.keys():
print "%s%s" % (prefix, key)
if key == 'addresses':
for k in set([a['interface'] for a in data[key]]):
print "%s%s.%s" % (prefix, key, k)
if key == 'ports':
for k in set([p['process'] for p in data[key] if 'process' in p]):
print "%s%s.%s" % (prefix, key, k)
if len([p for p in data[key] if 'process' not in p]) > 0:
print "%s%s.%s" % (prefix, key, 'UNKNOWN')
if isinstance(data[key], dict):
_print_keys(data[key], "%s%s." % (prefix, key))
def print_keys(path):
data = _get_data(path)
_print_keys(data)
def find_host(host):
path = "/usr/local/share/hostinfo/%s" % host
if os.path.exists(path):
return path
# try to build the fqdn
path = "/usr/local/share/hostinfo/%s.spline.inf.fu-berlin.de" % \
host.replace('.spline.de', '')
if os.path.exists(path):
return path
try:
# try to use reverse dns
addr=reversename.from_address(host)
hostname = str(resolver.query(addr,"PTR")[0])
path = "/usr/local/share/hostinfo/%s" % hostname[0:-1]
except:
pass
if os.path.exists(path):
return path
return None
def main():
self_name = sys.argv.pop(0)
optlist, args = getopt.gnu_getopt(sys.argv, 'ofkv',
['oneline', 'file', 'keys', 'verbose'])
flags = [opt for (opt, value) in optlist if value == '']
file = '--file' in flags or '-f' in flags
oneline = '--oneline' in flags or '-o' in flags
keys = '--keys' in flags or '-k' in flags
verbose = '--verbose' in flags or '-v' in flags
if len(args) < 1:
print('Usage: %s <host> [info]' % self_name)
sys.exit(1)
path = find_host(args[0])
if path is None:
print("Host '%s' could not be found!" % args[0])
sys.exit(1)
if file:
print(path)
elif keys:
print_keys(path)
else:
key=None
if len(args) > 1:
key = args[1]
print_info(path, key=key, oneline=oneline, verbose=verbose)
sys.exit(0)
if __name__ == '__main__':
main()
|