/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk
24.1.116 by Björn Påhlsson
added a mandos list client program
1
#!/usr/bin/python
240 by Teddy Hogeborn
Merge "mandos-list" from belorn.
2
# -*- mode: python; coding: utf-8 -*-
24.1.116 by Björn Påhlsson
added a mandos list client program
3
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
4
from __future__ import division
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
5
import sys
24.1.116 by Björn Påhlsson
added a mandos list client program
6
import dbus
7
from optparse import OptionParser
240 by Teddy Hogeborn
Merge "mandos-list" from belorn.
8
import locale
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
9
import datetime
10
import re
240 by Teddy Hogeborn
Merge "mandos-list" from belorn.
11
12
locale.setlocale(locale.LC_ALL, u'')
24.1.116 by Björn Påhlsson
added a mandos list client program
13
14
tablewords = {
240 by Teddy Hogeborn
Merge "mandos-list" from belorn.
15
    'name': u'Name',
16
    'enabled': u'Enabled',
17
    'timeout': u'Timeout',
18
    'last_checked_ok': u'Last Successful Check',
19
    'created': u'Created',
20
    'interval': u'Interval',
21
    'host': u'Host',
22
    'fingerprint': u'Fingerprint',
23
    'checker_running': u'Check Is Running',
24
    'last_enabled': u'Last Enabled',
25
    'checker': u'Checker',
24.1.116 by Björn Påhlsson
added a mandos list client program
26
    }
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
27
defaultkeywords = ('name', 'enabled', 'timeout', 'last_checked_ok',
28
                   'checker')
24.1.130 by Björn Påhlsson
new domain name for d-bus
29
domain = 'se.bsnet.fukt'
30
busname = domain + '.Mandos'
31
server_path = '/'
32
server_interface = domain + '.Mandos'
33
client_interface = domain + '.Mandos.Client'
395 by Teddy Hogeborn
Merge from release branch.
34
version = "1.0.14"
24.1.118 by Björn Påhlsson
Added enable/disable
35
bus = dbus.SystemBus()
36
mandos_dbus_objc = bus.get_object(busname, server_path)
37
mandos_serv = dbus.Interface(mandos_dbus_objc,
38
                             dbus_interface = server_interface)
39
mandos_clients = mandos_serv.GetAllClientsWithProperties()
40
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
41
def timedelta_to_milliseconds(td):
42
    "Convert a datetime.timedelta object to milliseconds"
43
    return ((td.days * 24 * 60 * 60 * 1000)
44
            + (td.seconds * 1000)
45
            + (td.microseconds // 1000))
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
46
47
def milliseconds_to_string(ms):
48
    td = datetime.timedelta(0, 0, 0, ms)
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
49
    return (u"%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
50
            % { "days": "%dT" % td.days if td.days else "",
51
                "hours": td.seconds // 3600,
52
                "minutes": (td.seconds % 3600) // 60,
53
                "seconds": td.seconds % 60,
54
                })
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
55
56
57
def string_to_delta(interval):
58
    """Parse a string and return a datetime.timedelta
59
60
    >>> string_to_delta('7d')
61
    datetime.timedelta(7)
62
    >>> string_to_delta('60s')
63
    datetime.timedelta(0, 60)
64
    >>> string_to_delta('60m')
65
    datetime.timedelta(0, 3600)
66
    >>> string_to_delta('24h')
67
    datetime.timedelta(1)
68
    >>> string_to_delta(u'1w')
69
    datetime.timedelta(7)
70
    >>> string_to_delta('5m 30s')
71
    datetime.timedelta(0, 330)
72
    """
73
    timevalue = datetime.timedelta(0)
74
    regexp = re.compile("\d+[dsmhw]")
75
    
76
    for s in regexp.findall(interval):
77
        try:
78
            suffix = unicode(s[-1])
79
            value = int(s[:-1])
80
            if suffix == u"d":
81
                delta = datetime.timedelta(value)
82
            elif suffix == u"s":
83
                delta = datetime.timedelta(0, value)
84
            elif suffix == u"m":
85
                delta = datetime.timedelta(0, 0, 0, 0, value)
86
            elif suffix == u"h":
87
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
88
            elif suffix == u"w":
89
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
90
            else:
91
                raise ValueError
92
        except (ValueError, IndexError):
93
            raise ValueError
94
        timevalue += delta
95
    return timevalue
96
97
def print_clients(clients):
98
    def valuetostring(value, keyword):
99
        if type(value) is dbus.Boolean:
100
            return u"Yes" if value else u"No"
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
101
        if keyword in (u"timeout", u"interval"):
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
102
            return milliseconds_to_string(value)
103
        return unicode(value)
104
    
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
105
    # Create format string to print table rows
24.1.118 by Björn Påhlsson
Added enable/disable
106
    format_string = u' '.join(u'%%-%ds' %
107
                              max(len(tablewords[key]),
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
108
                                  max(len(valuetostring(client[key], key))
24.1.118 by Björn Påhlsson
Added enable/disable
109
                                      for client in
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
110
                                      clients))
24.1.118 by Björn Påhlsson
Added enable/disable
111
                              for key in keywords)
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
112
    # Print header line
355 by Teddy Hogeborn
* mandos: White-space fixes only.
113
    print format_string % tuple(tablewords[key] for key in keywords)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
114
    for client in clients:
115
        print format_string % tuple(valuetostring(client[key], key)
24.1.118 by Björn Påhlsson
Added enable/disable
116
                                    for key in keywords)
117
24.1.116 by Björn Påhlsson
added a mandos list client program
118
parser = OptionParser(version = "%%prog %s" % version)
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
119
parser.add_option("-a", "--all", action="store_true",
240 by Teddy Hogeborn
Merge "mandos-list" from belorn.
120
                  help="Print all fields")
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
121
parser.add_option("-e", "--enable", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
122
                  help="Enable client")
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
123
parser.add_option("-d", "--disable", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
124
                  help="disable client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
125
parser.add_option("-b", "--bump-timeout", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
126
                  help="Bump timeout for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
127
parser.add_option("--start-checker", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
128
                  help="Start checker for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
129
parser.add_option("--stop-checker", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
130
                  help="Stop checker for client")
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
131
parser.add_option("-V", "--is-enabled", action="store_true",
132
                  help="Check if client is enabled")
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
133
parser.add_option("-r", "--remove", action="store_true",
134
                  help="Remove client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
135
parser.add_option("-c", "--checker", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
136
                  help="Set checker command for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
137
parser.add_option("-t", "--timeout", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
138
                  help="Set timeout for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
139
parser.add_option("-i", "--interval", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
140
                  help="Set checker interval for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
141
parser.add_option("-H", "--host", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
142
                  help="Set host for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
143
parser.add_option("-s", "--secret", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
144
                  help="Set password blob (file) for client")
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
145
options, client_names = parser.parse_args()
146
291 by Teddy Hogeborn
Merge from Björn:
147
# Compile list of clients to process
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
148
clients=[]
149
for name in client_names:
150
    for path, client in mandos_clients.iteritems():
151
        if client['name'] == name:
152
            client_objc = bus.get_object(busname, path)
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
153
            clients.append(client_objc)
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
154
            break
155
    else:
156
        print >> sys.stderr, "Client not found on server: %r" % name
157
        sys.exit(1)
158
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
159
if not clients and mandos_clients.values():
24.1.116 by Björn Påhlsson
added a mandos list client program
160
    keywords = defaultkeywords
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
161
    if options.all:
162
        keywords = ('name', 'enabled', 'timeout', 'last_checked_ok',
163
                    'created', 'interval', 'host', 'fingerprint',
164
                    'checker_running', 'last_enabled', 'checker')
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
165
    print_clients(mandos_clients.values())
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
166
167
# Process each client in the list by all selected options
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
168
for client in clients:
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
169
    if options.remove:
170
        mandos_serv.RemoveClient(client.__dbus_object_path__)
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
171
    if options.enable:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
172
        client.Enable(dbus_interface=client_interface)
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
173
    if options.disable:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
174
        client.Disable(dbus_interface=client_interface)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
175
    if options.bump_timeout:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
176
        client.CheckedOK(dbus_interface=client_interface)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
177
    if options.start_checker:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
178
        client.StartChecker(dbus_interface=client_interface)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
179
    if options.stop_checker:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
180
        client.StopChecker(dbus_interface=client_interface)
411 by Teddy Hogeborn
More consistent terminology: Clients are no longer "invalid" - they
181
    if options.is_enabled:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
182
        sys.exit(0 if client.Get(client_interface,
183
                                 u"enabled",
184
                                 dbus_interface=dbus.PROPERTIES_IFACE)
185
                 else 1)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
186
    if options.checker:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
187
        client.Set(client_interface, u"checker", options.checker,
188
                   dbus_interface=dbus.PROPERTIES_IFACE)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
189
    if options.host:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
190
        client.Set(client_interface, u"host", options.host,
191
                   dbus_interface=dbus.PROPERTIES_IFACE)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
192
    if options.interval:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
193
        client.Set(client_interface, u"interval",
194
                   timedelta_to_milliseconds
195
                   (string_to_delta(options.interval)),
196
                   dbus_interface=dbus.PROPERTIES_IFACE)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
197
    if options.timeout:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
198
        client.Set(client_interface, u"timeout",
199
                   timedelta_to_milliseconds(string_to_delta
200
                                             (options.timeout)),
201
                   dbus_interface=dbus.PROPERTIES_IFACE)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
202
    if options.secret:
382 by Teddy Hogeborn
* mandos-ctl: Made work again after D-Bus API changes.
203
        client.Set(client_interface, u"secret",
204
                   dbus.ByteArray(open(options.secret, u'rb').read()),
205
                   dbus_interface=dbus.PROPERTIES_IFACE)