summaryrefslogtreecommitdiffstats
path: root/bin/hostinfo
blob: 43fd5b45a1b445e12f381642d5cf01164510f6e3 (plain)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import socket
import getopt
import yaml
import os
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, nospaces=False):
    data = _get_data(path)
    p = printer.Printer(data, oneline, verbose, nospaces)
    p.info(key)

def print_keys(path):
    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))

    data = _get_data(path)
    _print_keys(data)

def print_hosts(path, short):
    metadata = os.path.join(path, 'metadata', 'hosts')
    if os.path.exists(metadata):
        hosts = yaml.load(file(metadata, 'r'))
        if 'hosts' in hosts:
            for host in hosts['hosts']:
                if short:
                    print(host.replace('.spline.inf.fu-berlin.de',''))
                else:
                    print(host)
            return True

    sys.stderr.write("'%s' not found!\n" % metadata)
    return False

def find_host(basepath, host):
    path = os.path.join(basepath, host)
    if os.path.exists(path):
        return path

    # try to build the fqdn
    path = os.path.join(basepath, "%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 = os.path.join(basepath, hostname[0:-1])
    except:
        pass

    if os.path.exists(path):
        return path

    return None

def print_help(self_name):
    print('Usage: %s <host> [info]' % self_name)

def main():
    self_name = sys.argv.pop(0)
    basepath = '/usr/local/share/hostinfo'
    if 'HOSTINFO_PATH' in os.environ:
        basepath = os.environ['HOSTINFO_PATH']

    file = oneline = keys = verbose = nospaces = help = \
        hosts = short = False
    try:
        optlist, args = getopt.gnu_getopt(sys.argv, 'ofkvnh?p:ls',
                                          ['oneline', 'file', 'keys', 'verbose',
                                           'nospaces', 'help', 'path=', 'hosts',
                                           'short'])
        opts = {}
        for key, value in optlist:
            opts[key] = value

        file = any([o in opts for o in ['--file', '-f']])
        oneline = any([o in opts for o in ['--oneline', '-f']])
        keys = any([o in opts for o in ['--keys', '-k']])
        verbose = any([o in opts for o in ['--verbose', '-v']])
        nospaces = any([o in opts for o in ['--nospaces', '-n']])
        help = any([o in opts for o in ['--help', '-h', '-?']])
        hosts = any([o in opts for o in ['--hosts', '-l']])
        short = any([o in opts for o in ['--short', '-s']])

        if any([o in opts for o in ['--path', '-p']]):
            basepath = [opts[o] for o in ['--path', '-p'] if o in opts][0]
    except getopt.GetoptError, e:
        print("Error: %s" % e)
        print
        args = []

    if hosts:
        if not print_hosts(basepath, short):
            sys.exit(1)
        sys.exit(0)

    if help or len(args) < 1:
        print_help(self_name)
        if not help:
            sys.exit(1)
        sys.exit(0)

    path = find_host(basepath, 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, nospaces=nospaces)
    sys.exit(0)

if __name__ == '__main__':
    main()