diff options
author | Joerg Steffens <joerg.steffens@bareos.com> | 2019-11-21 21:45:41 +0300 |
---|---|---|
committer | Joerg Steffens <joerg.steffens@bareos.com> | 2019-12-06 11:51:08 +0300 |
commit | 0095ae8276cc7edc31cdb10246a915a5e2d4246f (patch) | |
tree | b238d2e42e7b41b11c487896883956f75f02974f /python-bareos | |
parent | f91424ad0df4c15f4ffe45c3f33f24de1ee132fc (diff) |
python-bareos: added convenience functions
The Director Console Protocol >= 18.2.4 offers a lot more connection parameters.
Add util functions to the classes to help providing the same set of parameters to all command line tools.
Allow password as string parameter. It will be converted to Bareos.Util.Password during initialization.
Also added a fallback to old Director Console protocol (12.4),
if authentication to Director fails.
If protocolversion is set exclipietly, there will be no automatic fallback.
Diffstat (limited to 'python-bareos')
-rw-r--r-- | python-bareos/bareos/bsock/directorconsole.py | 84 | ||||
-rw-r--r-- | python-bareos/bareos/bsock/filedaemon.py | 51 | ||||
-rw-r--r-- | python-bareos/bareos/bsock/lowlevel.py | 134 | ||||
-rw-r--r-- | python-bareos/bareos/bsock/protocolmessages.py | 3 | ||||
-rw-r--r-- | python-bareos/bareos/exceptions.py | 7 | ||||
-rwxr-xr-x | python-bareos/bin/bareos-fd-connect.py | 30 | ||||
-rwxr-xr-x | python-bareos/bin/bareos-jsonrpc-server.py | 41 | ||||
-rwxr-xr-x | python-bareos/bin/bconsole-json.py | 38 | ||||
-rwxr-xr-x | python-bareos/bin/bconsole.py | 38 |
9 files changed, 268 insertions, 158 deletions
diff --git a/python-bareos/bareos/bsock/directorconsole.py b/python-bareos/bareos/bsock/directorconsole.py index 81c35ca13..449f7de51 100644 --- a/python-bareos/bareos/bsock/directorconsole.py +++ b/python-bareos/bareos/bsock/directorconsole.py @@ -11,7 +11,69 @@ from bareos.bsock.protocolversions import ProtocolVersions import bareos.exceptions class DirectorConsole(LowLevel): - '''use to send and receive the response to Bareos File Daemon''' + '''use to send and receive the response to Bareos Director Daemon''' + + @staticmethod + def argparser_add_default_command_line_arguments(argparser): + """ + Every command line program must offer a similar set of parameter + to connect to a Bareos Director. + This method adds the required parameter to an existing ArgParser object. + Parameter required to initialize a DirectorConsole class + are stored in variables prefixed with BAREOS_. + + Use the argparser_get_bareos_parameter method to retrieve the relevant parameter + (with the BAREOS_ prefix removed). + + Example: + argparser = argparse.ArgumentParser(description='Console to Bareos Director.') + DirectorConsole.argparser_add_default_command_line_arguments(argparser) + args = argparser.parse_args() + bareos_args = DirectorConsole.argparser_get_bareos_parameter(args) + director = DirectorConsole(**bareos_args) + + @param argparser: ArgParser + @type name: ArgParser + """ + argparser.add_argument('--name', + default="*UserAgent*", + help="use this to access a specific Bareos director named console. Otherwise it connects to the default console (\"*UserAgent*\").", dest='BAREOS_name') + + argparser.add_argument('-p', '--password', + help="Password to authenticate to a Bareos Director console.", + required=True, + dest='BAREOS_password') + + argparser.add_argument('--port', + default=9101, + help="Bareos Director network port.", + dest='BAREOS_port') + + #argparser.add_argument('--dirname', help="Bareos Director name") + argparser.add_argument('--address', + default="localhost", + help="Bareos Director network address.", + dest='BAREOS_address') + + argparser.add_argument('--protocolversion', + default=ProtocolVersions.last, + type=int, + help=u'Specify the protocol version to use. Default: {0} (current).'.format(ProtocolVersions.last), + dest='BAREOS_protocolversion') + + argparser.add_argument('--pam-username', + help="Username to authenticate against PAM on top off the normal authentication.", + dest='BAREOS_pam_username') + + argparser.add_argument('--pam-password', + help="Password to authenticate against PAM on top off the normal authentication.", + dest='BAREOS_pam_password') + + argparser.add_argument('--tls-psk-require', + help="Allow only encrypted connections. Default: False.", + action='store_true', + dest='BAREOS_tls_psk_require') + def __init__(self, address="localhost", @@ -19,7 +81,7 @@ class DirectorConsole(LowLevel): dirname=None, name="*UserAgent*", password=None, - protocolversion=ProtocolVersions.last, + protocolversion=None, pam_username=None, pam_password=None, tls_psk_enable=True, @@ -31,15 +93,15 @@ class DirectorConsole(LowLevel): self.tls_psk_enable=tls_psk_enable self.tls_psk_require=tls_psk_require self.identity_prefix = u'R_CONSOLE' - self.protocolversion = protocolversion - if self.protocolversion: - self.protocol_messages.set_version(self.protocolversion) + if protocolversion is not None: + self.requested_protocol_version = int(protocolversion) + self.protocol_messages.set_version(self.requested_protocol_version) self.connect(address, port, dirname, ConnectionType.DIRECTOR, name, password) - self.auth(name=name, password=password) self._init_connection() + self.max_reconnects = 1 - def get_and_evaluate_auth_responses(self): + def finalize_authentication(self): code, text = self.receive_and_evaluate_response_message() self.logger.debug(u'code: {0}'.format(code)) @@ -55,15 +117,15 @@ class DirectorConsole(LowLevel): if code == ProtocolMessageIds.PamRequired: self.logger.debug(u'PAM request: {0}'.format(text)) if (not self.pam_username) or (not self.pam_password): - raise bareos.exceptions.AuthenticationError("PAM authentication is requested, but no PAM credentials given. Giving up.\n"); + raise bareos.exceptions.PamAuthenticationError("PAM authentication is requested, but no PAM credentials given. Giving up.\n"); self.send(ProtocolMessages.pam_user_credentials(self.pam_username, self.pam_password)) try: code, text = self.receive_and_evaluate_response_message() except bareos.exceptions.ConnectionLostError as e: - raise bareos.exceptions.AuthenticationError(u'PAM authentication failed.') + raise bareos.exceptions.PamAuthenticationError(u'PAM authentication failed.') else: if (self.pam_username) or (self.pam_password): - raise bareos.exceptions.AuthenticationError("PAM credentials provided, but this Director console does not offer PAM login. Giving up.\n"); + raise bareos.exceptions.PamAuthenticationError("PAM credentials provided, but this Director console does not offer PAM login. Giving up.\n"); # @@ -76,7 +138,7 @@ class DirectorConsole(LowLevel): raise bareos.exceptions.AuthenticationError("Received unexcepted message: {0} {1} (expecting auth ok)".format(code, text)) - if self.protocolversion >= ProtocolVersions.bareos_18_2: + if self.get_protocol_version() >= ProtocolVersions.bareos_18_2: # # Handle info message. # diff --git a/python-bareos/bareos/bsock/filedaemon.py b/python-bareos/bareos/bsock/filedaemon.py index 6f4658de2..e18ea7aa7 100644 --- a/python-bareos/bareos/bsock/filedaemon.py +++ b/python-bareos/bareos/bsock/filedaemon.py @@ -12,6 +12,54 @@ import shlex class FileDaemon(LowLevel): '''use to send and receive the response to Bareos File Daemon''' + @staticmethod + def argparser_add_default_command_line_arguments(argparser): + """ + Every command line program must offer a similar set of parameter + to connect to a Bareos File Daemon. + This method adds the required parameter to an existing ArgParser object. + Parameter required to initialize a FileDaemon class + are stored in variables prefixed with BAREOS_. + + Use the argparser_get_bareos_parameter method to retrieve the relevant parameter + (with the BAREOS_ prefix removed). + + Example: + argparser = argparse.ArgumentParser(description='Console to Bareos Director.') + DirectorConsole.argparser_add_default_command_line_arguments(argparser) + args = argparser.parse_args() + bareos_args = DirectorConsole.argparser_get_bareos_parameter(args) + director = DirectorConsole(**bareos_args) + + @param argparser: ArgParser + @type name: ArgParser + """ + argparser.add_argument('--name', + help="Name of the Director resource in the File Daemon.", + required=True, + dest='BAREOS_name') + + argparser.add_argument('-p', '--password', + help="Password to authenticate to a Bareos File Daemon.", + required=True, + dest='BAREOS_password') + + argparser.add_argument('--port', + default=9102, + help="Bareos File Daemon network port.", + dest='BAREOS_port') + + argparser.add_argument('--address', + default="localhost", + help="Bareos File Daemon network address.", + dest='BAREOS_address') + + argparser.add_argument('--tls-psk-require', + help="Allow only encrypted connections. Default: False.", + action='store_true', + dest='BAREOS_tls_psk_require') + + def __init__(self, address="localhost", port=9102, @@ -28,11 +76,10 @@ class FileDaemon(LowLevel): # but using the interface provided for Directors. self.identity_prefix = u'R_DIRECTOR' self.connect(address, port, dirname, ConnectionType.FILEDAEMON, name, password) - self.auth(name=name, password=password) self._init_connection() - def get_and_evaluate_auth_responses(self): + def finalize_authentication(self): code, text = self.receive_and_evaluate_response_message() self.logger.debug(u'code: {0}'.format(code)) diff --git a/python-bareos/bareos/bsock/lowlevel.py b/python-bareos/bareos/bsock/lowlevel.py index 22ac023f5..795de2be1 100644 --- a/python-bareos/bareos/bsock/lowlevel.py +++ b/python-bareos/bareos/bsock/lowlevel.py @@ -42,6 +42,26 @@ class LowLevel(object): Low Level socket methods to communicate with the bareos-director. """ + @staticmethod + def argparser_get_bareos_parameter(args): + """ + This method is usally used together with the method argparser_add_default_command_line_arguments. + + @param args: Arguments retrieved by ArgumentParser.parse_args() + @type args: ArgParser.Namespace + + @return: returns the relevant parameter from args to initialize a connection. + @rtype: dict + """ + result = {} + for key,value in vars(args).items(): + if value is not None: + if key.startswith('BAREOS_'): + bareoskey=key.split('BAREOS_', 1)[1] + result[bareoskey]=value + return result + + def __init__(self): self.logger = logging.getLogger() self.logger.debug("init") @@ -54,10 +74,11 @@ class LowLevel(object): self.dirname = None self.socket = None self.auth_credentials_valid = False + self.max_reconnects = 0 self.tls_psk_enable = True self.tls_psk_require = False self.connection_type = None - self.protocolversion = ProtocolVersions.last + self.requested_protocol_version = None self.protocol_messages = ProtocolMessages() # identity_prefix have to be set in each class self.identity_prefix = u'R_NONE' @@ -66,33 +87,42 @@ class LowLevel(object): def __del__(self): self.close() - def connect(self, address, port, dirname, type, name = None, password = None): + def connect(self, address, port, dirname, connection_type, name = None, password = None): self.address = address self.port = int(port) if dirname: self.dirname = dirname else: self.dirname = address - self.connection_type = type + self.connection_type = connection_type self.name = name - self.password = password + if isinstance(password, Password): + self.password = password + else: + self.password = Password(password) return self.__connect() def __connect(self): connected = False - if self.tls_psk_require and not self.is_tls_psk_available(): - raise bareos.exceptions.ConnectionError(u'TLS-PSK is required, but sslpsk module not loaded/available.') + connected_plain = False + auth = False + if self.tls_psk_require: + if not self.is_tls_psk_available(): + raise bareos.exceptions.ConnectionError(u'TLS-PSK is required, but sslpsk module not loaded/available.') + if not self.tls_psk_enable: + raise bareos.exceptions.ConnectionError(u'TLS-PSK is required, but not enabled.') if self.tls_psk_enable and self.is_tls_psk_available(): try: self.__connect_tls_psk() except (bareos.exceptions.ConnectionError, ssl.SSLError) as e: + self._handleSocketError(e) if self.tls_psk_require: raise else: - self.logger.warn(u'Failed to connect via TLS-PSK. Trying plain connection.') + self.logger.warning(u'Failed to connect via TLS-PSK. Trying plain connection.') else: connected = True self.logger.debug("Encryption: {0}".format(self.socket.cipher())) @@ -100,9 +130,29 @@ class LowLevel(object): if not connected: self.__connect_plain() connected = True + connected_plain = True self.logger.debug("Encryption: None") - return connected + if connected: + try: + auth = self.auth() + except bareos.exceptions.PamAuthenticationError: + raise + except bareos.exceptions.AuthenticationError: + if self.connection_type == ConnectionType.DIRECTOR \ + and self.requested_protocol_version is None \ + and self.get_protocol_version() > ProtocolVersions.bareos_12_4 \ + : + # reconnect and try old protocol + self.logger.warning("Failed to connect using protocol version {0}. Trying protocol version {1}. ".format(self.get_protocol_version(), ProtocolVersions.bareos_12_4)) + self.close() + self.__connect_plain() + self.protocol_messages.set_version(ProtocolVersions.bareos_12_4) + auth = self.auth() + else: + raise + + return auth def __connect_plain(self): @@ -157,17 +207,19 @@ class LowLevel(object): '''Checks if we have all required modules for TLS-PSK.''' return 'sslpsk' in sys.modules + def get_protocol_version(self): + return self.protocol_messages.get_version() - def auth(self, name, password): + def get_cipher(self): + if hasattr(self.socket, 'cipher'): + return self.socket.cipher() + else: + return None + + def auth(self): ''' Login to a Bareos Daemon. - @param name: Own name. - @type name: str - - @param password: Password. - @type password: bareos.bsock.Password - @return: True, if the authentication succeeds. In earlier versions, authentication failures returned False. However, now an authentication failure raises an exception. @@ -175,14 +227,7 @@ class LowLevel(object): @raise bareos.exceptions.AuthenticationError: if authentication fails. ''' - if not isinstance(password, Password): - raise bareos.exceptions.AuthenticationError("password must by of type bareos.Password() not %s" % (type(password))) - self.password = password - self.name = name - return self.__auth() - - def __auth(self): bashed_name = self.protocol_messages.hello(self.name, type=self.connection_type) # send the bash to the director self.send(bashed_name) @@ -190,13 +235,14 @@ class LowLevel(object): try: (ssl, result_compatible, result) = self._cram_md5_respond(password=self.password.md5(), tls_remote_need=0) except bareos.exceptions.SignalReceivedException as e: + self._handleSocketError(e) raise bareos.exceptions.AuthenticationError('Received unexcepted signal: {0}'.format(str(e))) if not result: raise bareos.exceptions.AuthenticationError("failed (in response)") if not self._cram_md5_challenge(clientname=self.name, password=self.password.md5(), tls_local_need=0, compatible=True): raise bareos.exceptions.AuthenticationError("failed (in challenge)") - self.get_and_evaluate_auth_responses() + self.finalize_authentication() return self.auth_credentials_valid @@ -225,9 +271,10 @@ class LowLevel(object): def reconnect(self): result = False - if self.auth_credentials_valid: + if self.max_reconnects > 0: try: - if self.__connect() and self.__auth() and self._init_connection(): + self.max_reconnects -= 1 + if self.__connect() and self._init_connection(): result = True except socket.error: self.logger.warning("failed to reconnect") @@ -240,10 +287,10 @@ class LowLevel(object): ''' if isinstance(command, list): command = " ".join(command) - return self.__call(command, 0) + return self._send_a_command_and_receive_result(command) - def __call(self, command, count): + def _send_a_command_and_receive_result(self, command): ''' Send a command and receive the result. If connection is lost, try to reconnect. @@ -254,9 +301,10 @@ class LowLevel(object): result = self.recv_msg() except (bareos.exceptions.SocketEmptyHeader, bareos.exceptions.ConnectionLostError) as e: self.logger.error("connection problem (%s): %s" % (type(e).__name__, str(e))) - if count == 0: - if self.reconnect(): - return self.__call(command, count+1) + if self.reconnect(): + return self._send_a_command_and_receive_result(command, count+1) + else: + raise return result @@ -291,7 +339,7 @@ class LowLevel(object): msg = b'' # get the message while length > 0: - self.logger.debug(" submsg len: " + str(length)) + self.logger.debug("expecting {0} bytes.".format(length)) submsg = self.socket.recv(length) if len(submsg) == 0: errormsg = u'Failed to retrieve data. Assuming the connection is lost.' @@ -304,7 +352,7 @@ class LowLevel(object): def recv(self): ''' - Receive a single Director message. + Receive a single message. This is, header (4 bytes): if > 0: length of the following message @@ -326,7 +374,7 @@ class LowLevel(object): return msg - def recv_msg(self, regex=b'^\d\d\d\d OK.*$', timeout=None): + def recv_msg(self, regex=b'^\d\d\d\d OK.*$'): ''' Receive a full Director message. @@ -343,13 +391,19 @@ class LowLevel(object): timeouts = 0 while True: # get the message header - self.socket.settimeout(0.1) try: header = self.__get_header() - except socket.timeout: - # only log every 100 timeouts - if timeouts % 100 == 0: - self.logger.debug("timeout (%i) on receiving header" % (timeouts)) + except (socket.timeout, ssl.SSLError) as exception: + # When using a SSL connection, + # a timeout is raised as + # ssl.SSLError exception with message: 'The read operation timed out'. + # ssl.SSLError is inherited from socket.error. + # Because we can't be sure, + # that it is really a timeout, we log it. + if isinstance(exception, ssl.SSLError) and self.logger.isEnabledFor(logging.DEBUG): + #self.logger.exception('On SSL connections, timeout are raised as ssl.SSLError exceptions:') + self.logger.debug('{0}'.format(repr(exception))) + self.logger.debug("timeout (%i) on receiving header" % (timeouts)) timeouts+=1 else: if header <= 0: @@ -430,8 +484,8 @@ class LowLevel(object): sys.stdout.write(b'\n') - def __get_header(self): - header = self.recv_bytes(4) + def __get_header(self, timeout = 10): + header = self.recv_bytes(4, timeout) return self.__get_header_data(header) diff --git a/python-bareos/bareos/bsock/protocolmessages.py b/python-bareos/bareos/bsock/protocolmessages.py index 8c9a3d95b..59683d3ef 100644 --- a/python-bareos/bareos/bsock/protocolmessages.py +++ b/python-bareos/bareos/bsock/protocolmessages.py @@ -19,6 +19,9 @@ class ProtocolMessages(): def set_version(self, protocolversion): self.protocolversion = protocolversion + def get_version(self): + return self.protocolversion + def hello(self, name, type=ConnectionType.DIRECTOR): if type == ConnectionType.FILEDAEMON: return bytearray("Hello Director %s calling\n" % (name), 'utf-8') diff --git a/python-bareos/bareos/exceptions.py b/python-bareos/bareos/exceptions.py index 7fd19531e..82945f890 100644 --- a/python-bareos/bareos/exceptions.py +++ b/python-bareos/bareos/exceptions.py @@ -39,6 +39,13 @@ class AuthenticationError(ConnectionError): pass +class PamAuthenticationError(AuthenticationError): + """ + error during PAM Authentication + """ + pass + + class SignalReceivedException(Error): """ received a signal during a connection. diff --git a/python-bareos/bin/bareos-fd-connect.py b/python-bareos/bin/bareos-fd-connect.py index bd505531f..839b3ff46 100755 --- a/python-bareos/bin/bareos-fd-connect.py +++ b/python-bareos/bin/bareos-fd-connect.py @@ -7,14 +7,11 @@ import logging import sys def getArguments(): - parser = argparse.ArgumentParser(description='Connect to Bareos File Daemon.') - parser.add_argument('-d', '--debug', action='store_true', help="enable debugging output") - parser.add_argument('--name', help="Name of the Director resource in the File Daemon", required=True) - parser.add_argument('-p', '--password', help="password to authenticate to a Bareos File Daemon", required=True) - parser.add_argument('--port', default=9102, help="Bareos File Daemon network port") - parser.add_argument('address', nargs='?', default="localhost", help="Bareos File Daemon network address") - parser.add_argument('command', nargs='*', help="Command to send to the Bareos File Daemon") - args = parser.parse_args() + argparser = argparse.ArgumentParser(description='Connect to Bareos File Daemon.') + argparser.add_argument('-d', '--debug', action='store_true', help="enable debugging output") + bareos.bsock.FileDaemon.argparser_add_default_command_line_arguments(argparser) + argparser.add_argument('command', nargs='*', help="Command to send to the Bareos File Daemon") + args = argparser.parse_args() return args if __name__ == '__main__': @@ -25,20 +22,11 @@ if __name__ == '__main__': if args.debug: logger.setLevel(logging.DEBUG) + bareos_args = bareos.bsock.FileDaemon.argparser_get_bareos_parameter(args) + logger.debug('options: %s' % (bareos_args)) try: - options = [ 'address', 'port', 'name' ] - parameter = {} - for i in options: - if hasattr(args, i) and getattr(args,i) != None: - logger.debug( "%s: %s" %(i, getattr(args,i))) - parameter[i] = getattr(args,i) - else: - logger.debug( '%s: ""' %(i)) - logger.debug('options: %s' % (parameter)) - password = bareos.bsock.Password(args.password) - parameter['password']=password - bsock=FileDaemon(**parameter) - except RuntimeError as e: + bsock=FileDaemon(**bareos_args) + except (bareos.exceptions.Error) as e: print(str(e)) sys.exit(1) logger.debug( "authentication successful" ) diff --git a/python-bareos/bin/bareos-jsonrpc-server.py b/python-bareos/bin/bareos-jsonrpc-server.py index ffc12491d..c676192ec 100755 --- a/python-bareos/bin/bareos-jsonrpc-server.py +++ b/python-bareos/bin/bareos-jsonrpc-server.py @@ -1,7 +1,9 @@ #!/usr/bin/python +from __future__ import print_function import argparse import bareos.bsock +import bareos.exceptions import inspect import logging # pip install python-jsonrpc @@ -61,20 +63,16 @@ def bconsole_methods_to_jsonrpc(bconsole_methods): methods = RequestHandler.methods for i in tuples: methods[i[0]] = getattr(bconsole_methods, i[0]) - print i[0] - print methods + print(i[0]) + print(methods) RequestHandler.methods=methods def getArguments(): - parser = argparse.ArgumentParser(description='Run Bareos Director JSON-RPC proxy.' ) - parser.add_argument('-d', '--debug', action='store_true', help="enable debugging output") - parser.add_argument('--name', default="*UserAgent*", help="use this to access a specific Bareos director named console. Otherwise it connects to the default console (\"*UserAgent*\")") - parser.add_argument('-p', '--password', help="password to authenticate to a Bareos Director console", required=True) - parser.add_argument('--port', default=9101, help="Bareos Director network port") - parser.add_argument('--dirname', help="Bareos Director name") - parser.add_argument('address', nargs='?', default="localhost", help="Bareos Director network address") - args = parser.parse_args() + argparser = argparse.ArgumentParser(description='Run Bareos Director JSON-RPC proxy.' ) + argparser.add_argument('-d', '--debug', action='store_true', help="enable debugging output") + bareos.bsock.DirectorConsoleJson.argparser_add_default_command_line_arguments(argparser) + args = argparser.parse_args() return args @@ -86,20 +84,11 @@ if __name__ == '__main__': if args.debug: logger.setLevel(logging.DEBUG) + bareos_args = bareos.bsock.DirectorConsoleJson.argparser_get_bareos_parameter(args) + logger.debug('options: %s' % (bareos_args)) try: - options = [ 'address', 'port', 'dirname', 'name' ] - parameter = {} - for i in options: - if hasattr(args, i) and getattr(args,i) != None: - logger.debug( "%s: %s" %(i, getattr(args,i))) - parameter[i] = getattr(args, i) - else: - logger.debug( '%s: ""' %(i)) - logger.debug('options: %s' % (parameter)) - password = bareos.bsock.Password(args.password) - parameter['password']=password - director = bareos.bsock.DirectorConsoleJson(**parameter) - except RuntimeError as e: + director = bareos.bsock.DirectorConsoleJson(**bareos_args) + except (bareos.exceptions.ConnectionError) as e: print(str(e)) sys.exit(1) logger.debug( "authentication successful" ) @@ -108,13 +97,13 @@ if __name__ == '__main__': bconsole_methods_to_jsonrpc( bconsole_methods ) - print bconsole_methods.call("list jobs last") + print(bconsole_methods.call("list jobs last")) # Threading HTTP-Server http_server = pyjsonrpc.ThreadingHttpServer( server_address = ('localhost', 8080), RequestHandlerClass = RequestHandler ) - print "Starting HTTP server ..." - print "URL: http://localhost:8080" + print("Starting HTTP server ...") + print("URL: http://localhost:8080") http_server.serve_forever() diff --git a/python-bareos/bin/bconsole-json.py b/python-bareos/bin/bconsole-json.py index e610c2774..84f2aee87 100755 --- a/python-bareos/bin/bconsole-json.py +++ b/python-bareos/bin/bconsole-json.py @@ -4,22 +4,14 @@ from __future__ import print_function import argparse import bareos.bsock import bareos.exceptions -from bareos.bsock.protocolversions import ProtocolVersions import logging import sys def getArguments(): - parser = argparse.ArgumentParser(description='Console to Bareos Director.' ) - parser.add_argument('-d', '--debug', action='store_true', help="enable debugging output") - parser.add_argument('--name', default="*UserAgent*", help="use this to access a specific Bareos director named console. Otherwise it connects to the default console (\"*UserAgent*\")") - parser.add_argument('-p', '--password', help="password to authenticate to a Bareos Director console", required=True) - parser.add_argument('--port', default=9101, help="Bareos Director network port") - parser.add_argument('--dirname', help="Bareos Director name") - parser.add_argument('--protocolversion', - default=ProtocolVersions.last, - help=u'Specify the protocol version to use. Default: {0} (current)'.format(ProtocolVersions.last)) - parser.add_argument('address', nargs='?', default="localhost", help="Bareos Director network address") - args = parser.parse_args() + argparser = argparse.ArgumentParser(description='Console to Bareos Director.') + argparser.add_argument('-d', '--debug', action='store_true', help="enable debugging output") + bareos.bsock.DirectorConsoleJson.argparser_add_default_command_line_arguments(argparser) + args = argparser.parse_args() return args if __name__ == '__main__': @@ -30,25 +22,13 @@ if __name__ == '__main__': if args.debug: logger.setLevel(logging.DEBUG) + bareos_args = bareos.bsock.DirectorConsoleJson.argparser_get_bareos_parameter(args) + logger.debug('options: %s' % (bareos_args)) try: - options = [ 'address', 'port', 'dirname', 'name' ] - parameter = {} - for i in options: - if hasattr(args, i) and getattr(args,i) != None: - logger.debug( "%s: %s" %(i, getattr(args,i))) - parameter[i] = getattr(args, i) - else: - logger.debug( '%s: ""' %(i)) - logger.debug('options: %s' % (parameter)) - password = bareos.bsock.Password(args.password) - parameter['password']=password - try: - director = bareos.bsock.DirectorConsoleJson(**parameter) - except (bareos.exceptions.ConnectionError) as e: - print(str(e)) - sys.exit(1) - except RuntimeError as e: + director = bareos.bsock.DirectorConsoleJson(**bareos_args) + except (bareos.exceptions.Error) as e: print(str(e)) sys.exit(1) + logger.debug( "authentication successful" ) director.interactive() diff --git a/python-bareos/bin/bconsole.py b/python-bareos/bin/bconsole.py index 6dd1eceae..0f2167dcf 100755 --- a/python-bareos/bin/bconsole.py +++ b/python-bareos/bin/bconsole.py @@ -4,22 +4,14 @@ from __future__ import print_function import argparse import bareos.bsock import bareos.exceptions -from bareos.bsock.protocolversions import ProtocolVersions import logging import sys def getArguments(): - parser = argparse.ArgumentParser(description='Console to Bareos Director.' ) - parser.add_argument('-d', '--debug', action='store_true', help="enable debugging output") - parser.add_argument('--name', default="*UserAgent*", help="use this to access a specific Bareos director named console. Otherwise it connects to the default console (\"*UserAgent*\")") - parser.add_argument('-p', '--password', help="password to authenticate to a Bareos Director console", required=True) - parser.add_argument('--port', default=9101, help="Bareos Director network port") - parser.add_argument('--dirname', help="Bareos Director name") - parser.add_argument('--protocolversion', - default=ProtocolVersions.last, - help=u'Specify the protocol version to use. Default: {0} (current)'.format(ProtocolVersions.last)) - parser.add_argument('address', nargs='?', default="localhost", help="Bareos Director network address") - args = parser.parse_args() + argparser = argparse.ArgumentParser(description='Console to Bareos Director.') + argparser.add_argument('-d', '--debug', action='store_true', help="enable debugging output") + bareos.bsock.DirectorConsole.argparser_add_default_command_line_arguments(argparser) + args = argparser.parse_args() return args if __name__ == '__main__': @@ -30,25 +22,13 @@ if __name__ == '__main__': if args.debug: logger.setLevel(logging.DEBUG) + bareos_args = bareos.bsock.DirectorConsole.argparser_get_bareos_parameter(args) + logger.debug('options: %s' % (bareos_args)) try: - options = [ 'address', 'port', 'dirname', 'name' ] - parameter = {} - for i in options: - if hasattr(args, i) and getattr(args,i) != None: - logger.debug("%s: %s" %(i, getattr(args,i))) - parameter[i] = getattr(args,i) - else: - logger.debug( '%s: ""' %(i)) - logger.debug('options: %s' % (parameter)) - password = bareos.bsock.Password(args.password) - parameter['password']=password - try: - director = bareos.bsock.DirectorConsole(**parameter) - except (bareos.exceptions.ConnectionError) as e: - print(str(e)) - sys.exit(1) - except RuntimeError as e: + director = bareos.bsock.DirectorConsole(**bareos_args) + except (bareos.exceptions.Error) as e: print(str(e)) sys.exit(1) + logger.debug( "authentication successful" ) director.interactive() |