/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos-ctl

mandos-ctl: Added support for all client calls

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
 
 
4
from __future__ import division
4
5
import sys
5
6
import dbus
6
7
from optparse import OptionParser
7
8
import locale
 
9
import datetime
 
10
import re
8
11
 
9
12
locale.setlocale(locale.LC_ALL, u'')
10
13
 
35
38
                             dbus_interface = server_interface)
36
39
mandos_clients = mandos_serv.GetAllClientsWithProperties()
37
40
 
38
 
def print_clients():
39
 
    def valuetostring(x):
40
 
        if type(x) is dbus.Boolean:
41
 
            return u"Yes" if x else u"No"
42
 
        else:
43
 
            return unicode(x)
 
41
def datetime_to_milliseconds(dt):
 
42
    "Return the 'timeout' attribute in milliseconds"
 
43
    return ((dt.days * 24 * 60 * 60 * 1000)
 
44
            + (dt.seconds * 1000)
 
45
            + (dt.microseconds // 1000))
 
46
 
 
47
def milliseconds_to_string(ms):
 
48
    td = datetime.timedelta(0, 0, 0, ms)
 
49
    return "%s%02d:%02d:%02d" % (("%dT" % td.days) if td.days else "", # days
 
50
                           td.seconds // 3600,        # hours
 
51
                           (td.seconds % 3600) // 60, # minutes
 
52
                           (td.seconds % 60))         # seconds
 
53
 
 
54
 
 
55
def string_to_delta(interval):
 
56
    """Parse a string and return a datetime.timedelta
 
57
 
 
58
    >>> string_to_delta('7d')
 
59
    datetime.timedelta(7)
 
60
    >>> string_to_delta('60s')
 
61
    datetime.timedelta(0, 60)
 
62
    >>> string_to_delta('60m')
 
63
    datetime.timedelta(0, 3600)
 
64
    >>> string_to_delta('24h')
 
65
    datetime.timedelta(1)
 
66
    >>> string_to_delta(u'1w')
 
67
    datetime.timedelta(7)
 
68
    >>> string_to_delta('5m 30s')
 
69
    datetime.timedelta(0, 330)
 
70
    """
 
71
    timevalue = datetime.timedelta(0)
 
72
    regexp = re.compile("\d+[dsmhw]")
 
73
    
 
74
    for s in regexp.findall(interval):
 
75
        try:
 
76
            suffix = unicode(s[-1])
 
77
            value = int(s[:-1])
 
78
            if suffix == u"d":
 
79
                delta = datetime.timedelta(value)
 
80
            elif suffix == u"s":
 
81
                delta = datetime.timedelta(0, value)
 
82
            elif suffix == u"m":
 
83
                delta = datetime.timedelta(0, 0, 0, 0, value)
 
84
            elif suffix == u"h":
 
85
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
 
86
            elif suffix == u"w":
 
87
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
 
88
            else:
 
89
                raise ValueError
 
90
        except (ValueError, IndexError):
 
91
            raise ValueError
 
92
        timevalue += delta
 
93
    return timevalue
 
94
 
 
95
def print_clients(clients):
 
96
    def valuetostring(value, keyword):
 
97
        if type(value) is dbus.Boolean:
 
98
            return u"Yes" if value else u"No"
 
99
        if keyword in ("timeout", "interval"):
 
100
            return milliseconds_to_string(value)
 
101
        return unicode(value)
 
102
    
44
103
    format_string = u' '.join(u'%%-%ds' %
45
104
                              max(len(tablewords[key]),
46
 
                                  max(len(valuetostring(client[key]))
 
105
                                  max(len(valuetostring(client[key], key))
47
106
                                      for client in
48
 
                                      mandos_clients.itervalues()))
 
107
                                      clients))
49
108
                              for key in keywords)
50
109
    print format_string % tuple(tablewords[key] for key in keywords) 
51
 
    for client in mandos_clients.itervalues():
52
 
        print format_string % tuple(valuetostring(client[key])
 
110
    for client in clients:
 
111
        print format_string % tuple(valuetostring(client[key], key)
53
112
                                    for key in keywords)
54
113
 
55
114
parser = OptionParser(version = "%%prog %s" % version)
59
118
                  help="Enable specified client")
60
119
parser.add_option("-d", "--disable", action="store_true",
61
120
                  help="disable specified client")
62
 
parser.add_option("-b", "--bumptimeout", action="store_true",
 
121
parser.add_option("-b", "--bump-timeout", action="store_true",
63
122
                  help="Bump timeout of specified client")
64
 
parser.add_option("-s", "--startchecker", action="store_true",
 
123
parser.add_option("--start-checker", action="store_true",
65
124
                  help="Start checker for specified client")
66
 
parser.add_option("-S", "--stopchecker", action="store_true",
67
 
                  help="Stop checker for specified client")
 
125
parser.add_option("--stop-checker", action="store_true",
 
126
                  help="Stop checker for specified client")
 
127
parser.add_option("-v", "--is-valid", action="store_true",
 
128
                  help="Stop checker for specified client")
 
129
parser.add_option("-c", "--checker", type="string",
 
130
                  help="Set checker command for specified client")
 
131
parser.add_option("-t", "--timeout", type="string",
 
132
                  help="Set timeout for specified client")
 
133
parser.add_option("-i", "--interval", type="string",
 
134
                  help="Set checker interval for specified client")
 
135
parser.add_option("-H", "--host", type="string",
 
136
                  help="Set host for specified client")
 
137
parser.add_option("-s", "--secret", type="string",
 
138
                  help="Set password blob (file) for specified client")
68
139
options, client_names = parser.parse_args()
69
140
 
70
141
clients=[]
86
157
        keywords = ('name', 'enabled', 'timeout', 'last_checked_ok',
87
158
                    'created', 'interval', 'host', 'fingerprint',
88
159
                    'checker_running', 'last_enabled', 'checker')
89
 
    print_clients()
90
 
 
 
160
    print_clients(mandos_clients.values())
 
161
    
91
162
for client in clients:
92
163
    if options.enable:
93
164
        client.Enable()
94
165
    if options.disable:
95
166
        client.Disable()
96
 
    if options.bumptimeout:
 
167
    if options.bump_timeout:
97
168
        client.BumpTimeout()
98
 
    if options.startchecker:
 
169
    if options.start_checker:
99
170
        client.StartChecker()
100
 
    if options.stopchecker:
 
171
    if options.stop_checker:
101
172
        client.StopChecker()
102
 
 
 
173
    if options.is_valid:
 
174
        sys.exit(0 if client.IsStillValid() else 1)
 
175
    if options.checker:
 
176
        client.SetChecker(options.checker)
 
177
    if options.host:
 
178
        client.SetHost(options.host)
 
179
    if options.interval:
 
180
        client.SetInterval(datetime_to_milliseconds
 
181
                           (string_to_delta(options.interval)))
 
182
    if options.timeout:
 
183
        client.SetTimeout(datetime_to_milliseconds
 
184
                          (string_to_delta(options.timeout)))
 
185
    if options.secret:
 
186
        client.SetSecret(dbus.ByteArray(open(options.secret, 'rb').read()))
 
187