summaryrefslogtreecommitdiffstats
path: root/bin/hostinfo
blob: 9b4f09d7c850305fcc1d00fc95ab07ecd1780be1 (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import socket
import argparse
import yaml
import os
from dns import resolver,reversename

own_directory = os.path.dirname(os.path.abspath(os.path.realpath(__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, flags, key=None):
    data = _get_data(path)
    p = printer.Printer(data, flags)
    p.info(key)

def print_keys(path):
    def _print_keys(data, prefix = ''):
        if isinstance(data, str):
            return

        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)
            elif 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')
            elif isinstance(data[key], dict):
                _print_keys(data[key], "%s%s." % (prefix, key))
            elif isinstance(data[key], list):
                for v in data[key]:
                    _print_keys(v, "%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 main():
    basepath = '/usr/local/share/hostinfo'
    if 'HOSTINFO_PATH' in os.environ and os.environ['HOSTINFO_PATH'] != '':
        basepath = os.environ['HOSTINFO_PATH']

    parser = argparse.ArgumentParser()
    parser.add_argument("name", nargs="?")
    parser.add_argument("filter", nargs="?")
    parser.add_argument("-o", "--oneline", action="store_true",
                        help="each line is a complete record")
    parser.add_argument("-f", "--file", action="store_true",
                        help="print the path of the file the information is read from")
    parser.add_argument("-k", "--keys", action="store_true",
                        help="print only the available keys (used for bash completion)")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="increase output verbosity")
    parser.add_argument("-n", "--nospaces", action="store_true",
                        help="remove unnecessary spaces from output")
    parser.add_argument("-p", "--path", default=basepath,
                        help="set the basepath to the hostinfo data")
    parser.add_argument("-l", "--hosts", action="store_true",
                        help="lists all available hosts")
    parser.add_argument("-s", "--short", action="store_true",
                        help="remove the domain from the output")
    args = parser.parse_args()

    if args.path:
        basepath = args.path

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

    if args.name is None:
        parser.print_help()
        sys.exit(1)

    # info
    path = find_host(basepath, args.name)
    if path is None:
        sys.stderr.write("Host '%s' could not be found!\n" % args.name)
        sys.exit(1)

    if args.file:
        print(path)
    elif args.keys:
        print_keys(path)
    else:
        print_info(path, key=args.filter, flags=args)

    sys.exit(0)

if __name__ == '__main__':
    main()