Example #1
0
 def __init__(self, *args, **kwargs):
     Script.__init__(self, *args, **kwargs)
     self.runner = None
     self.mode = ''
     self.add_argument('--version',
                       action='store_true',
                       help='show version')
Example #2
0
    def __init__(self, oid, reload_interval=60):
        Script.__init__(self)
        self.log = Logger('snmp').default_stream

        self.reload_interval = reload_interval
        self.last_reload = None

        self.add_argument('-g', '--get', help='SNMP GET request')
        self.add_argument('-n', '--next', help='SNMP GET request')
        self.add_argument('-t', '--tree', action='store_true', help='Show OID tree')

        self.tree = Tree(oid)
Example #3
0
    def __init__(self, oid, reload_interval=60):
        Script.__init__(self)
        self.log = Logger('snmp').default_stream

        self.reload_interval = reload_interval
        self.last_reload = None

        self.add_argument('-g', '--get', help='SNMP GET request')
        self.add_argument('-n', '--next', help='SNMP GET request')
        self.add_argument('-t',
                          '--tree',
                          action='store_true',
                          help='Show OID tree')

        self.tree = Tree(oid)
Example #4
0
    def parse_args(self, *args, **kwargs):
        args = Script.parse_args(self, *args, **kwargs)

        if args.inventory is None:
            self.exit(1, 'Could not detect default inventory path')

        if 'pattern' in args and not Inventory(args.inventory).list_hosts(args.pattern):
            self.exit(1, 'No hosts matched')

        if args.ask_pass:
            args.remote_pass = getpass.getpass('Enter remote user password: '******'Enter sudo password: '******'sudo %s ' % args.sudo_user
        elif args.su:
            self.mode = 'su %s ' % args.su_user

        return args
Example #5
0
    def parse_args(self, *args, **kwargs):
        args = Script.parse_args(self, *args, **kwargs)

        if args.version:
            self.show_version()
            self.exit(0)

        if args.inventory is None:
            self.exit(1, 'Could not detect default inventory path')

        if 'pattern' in args and not Inventory(args.inventory).list_hosts(args.pattern):
            self.exit(1, 'No hosts matched')

        if args.ask_pass:
            args.remote_pass = getpass.getpass('Enter remote user password: '******'Enter become password: '******'become %s ' % args.become_user
        elif args.su:
            self.mode = 'su %s ' % args.su_user

        if args.vault_password_file:
            args.vault_pass = utils.read_vault_file(args.vault_password_file)
        else:
            args.vault_pass = False

        return args
Example #6
0
    def parse_args(self, *args, **kwargs):
        args = Script.parse_args(self, *args, **kwargs)

        if args.version:
            self.show_version()
            self.exit(0)

        if args.inventory is None:
            self.exit(1, 'Could not detect default inventory path')

        if 'pattern' in args and not Inventory(args.inventory).list_hosts(
                args.pattern):
            self.exit(1, 'No hosts matched')

        if args.ask_pass:
            args.remote_pass = getpass.getpass('Enter remote user password: '******'Enter sudo password: '******'sudo %s ' % args.sudo_user
        elif args.su:
            self.mode = 'su %s ' % args.su_user

        return args
Example #7
0
    def __init__(self, oid_map={}, index_cache_path=None):
        Script.__init__(self)

        self.oid_map = oid_map
        self.add_argument("-H", "--host", help="SNMP host to connect")
        self.add_argument("-p", "--port", type=int, default=161, help="SNMP server port")
        self.add_argument("-1", dest="snmpv1", action="store_true", help="Use SNMP v1")
        self.add_argument("-2", dest="snmpv2c", action="store_true", help="Use SNMP v2c")
        self.add_argument("-3", dest="snmpv3", action="store_true", help="Use SNMP v3")
        self.add_argument("-C", "--community", help="SNMP v1/v2c community")
        self.add_argument("-U", "--username", help="SNMP v3 username")
        self.add_argument("-a", "--authProtocol", help="SNMP v3 auth protocol")
        self.add_argument("-A", "--authPass", help="SNMP v3 auth password")
        self.add_argument("-x", "--privProtocol", help="SNMP v3 priv protocol")
        self.add_argument("-X", "--privPass", help="SNMP v3 priv password")
        self.add_argument("-t", "--timeout", type=int, default=1, help="SNMP query timeout")
        self.add_argument("-r", "--retries", type=int, default=5, help="SNMP query retries")
        self.add_argument("-f", "--cache-path", default=index_cache_path, help="Result index cache path")
Example #8
0
    def __init__(self,oid_map={},index_cache_path=None):
        Script.__init__(self)

        self.oid_map = oid_map
        self.add_argument('-H','--host',help='SNMP host to connect')
        self.add_argument('-p','--port',type=int,default=161,help='SNMP server port')
        self.add_argument('-1',dest='snmpv1',action='store_true',help='Use SNMP v1')
        self.add_argument('-2',dest='snmpv2c',action='store_true',help='Use SNMP v2c')
        self.add_argument('-3',dest='snmpv3',action='store_true',help='Use SNMP v3')
        self.add_argument('-C','--community',help='SNMP v1/v2c community')
        self.add_argument('-U','--username',help='SNMP v3 username')
        self.add_argument('-a','--authProtocol',help='SNMP v3 auth protocol')
        self.add_argument('-A','--authPass',help='SNMP v3 auth password')
        self.add_argument('-x','--privProtocol',help='SNMP v3 priv protocol')
        self.add_argument('-X','--privPass',help='SNMP v3 priv password')
        self.add_argument('-t','--timeout',type=int,default=1,help='SNMP query timeout')
        self.add_argument('-r','--retries',type=int,default=5,help='SNMP query retries')
        self.add_argument('-f','--cache-path',default=index_cache_path,help='Result index cache path')
Example #9
0
def main():
    """
    Main function  for vyos-config script
    """

    script = Script()

    script.add_subcommand(ListCommand())

    script.run()
Example #10
0
    def parse_args(self):
        args = Script.parse_args(self)
        self.address = args.host
        self.port = args.port
        self.timeout = args.timeout
        self.retries = args.retries
        self.index_cache_path = args.cache_path

        if args.snmpv3 and args.username and args.authPass:
            self.auth = SNMPv3Auth(args.username,args.authPass,args.privPass,args.authProtocol,args.privProtocol)
        elif args.snmpv2c and args.community:
            self.auth = SNMPv2cAuth(args.community)
        elif args.snmpv1 and args.community:
            self.auth = SNMPv1Auth(args.community)
        else:
            raise ScriptError('No SNMP authentication method provided')

        return args
Example #11
0
    def parse_args(self):
        args = Script.parse_args(self)
        self.address = args.host
        self.port = args.port
        self.timeout = args.timeout
        self.retries = args.retries
        self.index_cache_path = args.cache_path

        if args.snmpv3 and args.username and args.authPass:
            self.auth = SNMPv3Auth(args.username, args.authPass, args.privPass, args.authProtocol, args.privProtocol)
        elif args.snmpv2c and args.community:
            self.auth = SNMPv2cAuth(args.community)
        elif args.snmpv1 and args.community:
            self.auth = SNMPv1Auth(args.community)
        else:
            raise ScriptError("No SNMP authentication method provided")

        return args
Example #12
0
 def __init__(self, description=None):
     object.__setattr__(self, 'state_code', NAGIOS_INITIAL_STATE)
     self.message = 'UNINITIALIZED'
     self.parser = Script(description=description)
Example #13
0
def main():
    script = Script()
    script.add_argument('--config', default=DEFAULT_CONFIG_PATH, help='Virtual machine directory')

    c = script.add_subcommand(ListCommand('list', 'List VMs'))

    c = script.add_subcommand(StartCommand('start', 'Start VM'))
    c.add_argument('patterns', nargs='*', help='VM name patterns')

    c = script.add_subcommand(StopCommand('stop', 'Stop VM'))
    c.add_argument('patterns', nargs='*', help='VM name patterns')

    c = script.add_subcommand(AutoResumeCommand('resume', 'Autoresume headless VMs'))
    c.add_argument('patterns', nargs='*', help='VM name patterns')

    c = script.add_subcommand(SuspendCommand('suspend', 'Suspend VM'))
    c.add_argument('--autoresume', action='store_true', help='Set autoresume flag')
    c.add_argument('patterns', nargs='*', help='VM name patterns')

    c = script.add_subcommand(StatusCommand('status', 'Show status of VMs'))
    c.add_argument('patterns', nargs='*', help='VM name patterns')

    c = script.add_subcommand(DetailsCommand('details', 'Show VM details'))
    c.add_argument('patterns', nargs='*', help='VM name patterns')

    script.parse_args()
Example #14
0
def main():

    script = Script(description='Update music player library metadata')
    script.add_argument('-c', '--codec', help='Music library default codec')
    script.add_argument('-l', '--music-path', help='Music library path')
    script.add_argument('-p',
                        '--position',
                        type=int,
                        help='Start from given position in library')
    script.add_argument('-m',
                        '--metadata',
                        action='store_true',
                        help='Update metadata')
    args = script.parse_args()

    client = Client()

    script.log.info('Loading music player library playlist')

    if args.position:
        try:
            client.library.jump(args.position)
        except ValueError:
            script.exit(
                1, 'Invalid position: {0} ({1:d} entries)'.format(
                    (args.position, len(client.library))))

    try:
        tree = MusicTree(tree_path=args.music_path)
        tree.load()
        tree_paths = tree.realpaths
    except Exception as e:
        script.exit(1, e)

    processed = 0
    progress_interval = PROGRESS_INTERVAL
    progress_start = time.time()
    start = time.time()
    app_files = {}

    script.log.info('Checking library files against music player database')

    for entry in client.library:
        processed += 1
        if processed % progress_interval == 0:
            progress_time = float(time.time() - progress_start)
            progress_rate = int(progress_interval / progress_time)
            script.log.info('Index {0:d} ({1:d} entries per second)'.format(
                processed, progress_rate))
            progress_start = time.time()

        try:
            if entry.path is None:
                try:
                    client.library.delete(entry)
                except MusicPlayerError as e:
                    print(e)
                continue
        except TypeError as e:
            print('Error processing entry {0}: {1}'.format(entry, e))
            continue

        try:
            path = normalized(os.path.realpath(entry.path))
        except AttributeError:
            script.log.info('Removing invalid entry (no path defined)')
            try:
                client.library.delete(entry)
            except MusicPlayerError as e:
                print(e)
            continue

        if path not in tree_paths:
            if not os.path.isfile(path):
                script.log.info('Removing non-existing: "}0}"'.format(path))
                try:
                    client.library.delete(entry)
                except MusicPlayerError as e:
                    print(e)
            else:
                script.log.info('File outside tree: {0}'.format(path))

        elif path not in app_files:
            app_files[path] = entry
            if args.metadata:
                mtime = os.stat(path).st_mtime
                if int(entry.modification_date.strftime('%s')) >= mtime:
                    continue

                song = Track(entry.path)
                if entry.syncTags(song):
                    client.library.__next = entry.index

        else:
            script.log.info('Removing duplicate: {0}'.format(entry.path))
            try:
                client.library.delete(entry)
            except MusicPlayerError as e:
                print(e)

    loadtime = float(time.time() - start)
    script.log.info('Checked {0:d} files in {1:4.2f} seconds'.format(
        processed, loadtime))

    start = time.time()
    processed = 0

    script.log.info('Checking music player database against tree files')

    if args.position is None:

        for path in sorted(tree_paths.keys()):

            if path not in app_files:
                script.log.info('Adding: {0}'.format(path))
                try:
                    client.library.add(path)
                except ValueError as e:
                    print(e)

            processed += 1
            if processed % 1000 == 0:
                script.log.debug('Processed: {0:d} entries'.format(processed))

    loadtime = float(time.time() - start)
    script.log.info('Checked {0:d} files in {1:2.2f} seconds'.format(
        processed, loadtime))
Example #15
0
class NagiosPlugin(object):
    """Nagios plugin base class

    Implementation of nagios plugin in python

    See examples directory in source code for usage
    """
    def __init__(self, description=None):
        object.__setattr__(self, 'state_code', NAGIOS_INITIAL_STATE)
        self.message = 'UNINITIALIZED'
        self.parser = Script(description=description)

    def __repr__(self):
        return '{0} {1}'.format(self.state_message, self.message)

    def __setattr__(self, attr, value):
        if attr == 'state':
            self.set_state(value)
        object.__setattr__(self, attr, value)

    @property
    def state_message(self):
        return NAGIOS_STATES[self.state_code]

    def set_state(self, value):
        """Set nagios plugin state

        Sets internal state to provided value, which can be integer from 0 to 3
        or one of strings 'OK', 'WARNING', 'CRITICAL', 'UNKNOWN'

        Silently refuses to lower plugin state to less critical error. UNKNOWN
        state can always be overwritten.
        """
        try:
            value = int(value)
            if value not in NAGIOS_STATES.keys():
                raise ValueError
        except ValueError:
            pass

        if value in NAGIOS_STATES.keys():
            state_code = int(value)
        else:
            for k,v in NAGIOS_STATES.items():
                if value == v:
                    state_code = k
                    break

        if state_code not in NAGIOS_STATES.keys():
            raise AttributeError('Attempt to set invalid plugin state {0}'.format(value))

        # Silently ignore lowering of error state for a plugin
        if self.state_code != NAGIOS_INITIAL_STATE and self.state_code > state_code:
            self.parser.log.debug('Refuse lowering state from {0} to {1}'.format(self.state_code, state_code))
            return

        object.__setattr__(self, 'state_code', state_code)

    def add_argument(self, *args, **kwargs):
        """Add CLI argument

        Add CLI argument. Uses argparse.ArgumentParser.add_argument syntax

        """
        self.parser.add_argument(*args, **kwargs)

    def parse_args(self, *args, **kwargs):
        """Parse arguments

        Parse self.parser arguments. Called automatically from self.run()

        """
        self.args = self.parser.parse_args(*args, **kwargs)
        return self.args

    def error(self, message, code=2):
        """Exit with error

        Exit with error code (must be valid nagios state code)

        Writes error message to stdout

        """
        try:
            code = int(code)
            if code not in NAGIOS_STATES.keys():
                raise ValueError
        except ValueError:
            raise AttributeError('Invalid error code {0}'.format(code))

        sys.stdout.write('Error running plugin: {0}\n'.format(message))
        sys.exit(code)

    def exit(self):
        """Return nagios message and exit

        Print self.state_message + self.message to stdout for nagios and
        exit with self.state_code code

        """
        sys.stdout.write('{0} {1}\n'.format(self.state_message, self.message))
        sys.exit(self.state_code)

    def run(self):
        """Run the plugin

        Run the plugin:
          - Parse arguments
          - Set message to empty
          - run self.check_plugin_status() callback
          - run self.exit()

        If check_plugin_status raises NagiosPluginError, state is set to
        critical and error message is appended to message before exit
        """
        args = self.parse_args()
        self.message = ''

        try:
            self.check_plugin_status()
        except NagiosPluginError, emsg:
            self.state = 'CRITICAL'
            self.message += '{0}'.format(emsg)

        self.exit()
Example #16
0
def main():

    script = Script()

    c = script.add_subcommand(
        InfoCommand('info', 'Show playing track information'))
    c.add_argument('-v',
                   '--verbose',
                   action='store_true',
                   help='Verbose messages')

    c = script.add_subcommand(PlayCommand('play', 'Play/pause/jump to file'))
    c.add_argument('track', nargs='?', help='Track to play')

    c = script.add_subcommand(StopCommand('stop', 'Stop playback'))

    c = script.add_subcommand(
        PreviousTrackCommand('previous', 'Play previous tracks'))
    c = script.add_subcommand(NextTrackCommand('next', 'Play next tracks'))

    c = script.add_subcommand(
        ShuffleModeCommand('shuffle', 'Toggle or show suffle mode'))
    c.add_argument('mode',
                   nargs='?',
                   choices=(
                       'enable',
                       'disable',
                   ),
                   help='Enable or disable shuffle mode')

    c = script.add_subcommand(
        VolumeCommand('volume', 'Adjust or show playback volume'))
    c.add_argument('volume', nargs='?', help='Value to set')

    c = script.add_subcommand(
        UpdateIndexCommand('update-index', 'Update track index database'))

    c = script.add_subcommand(
        LookupDBCommand('lookup-index', 'Lookup track index from database'))
    c.add_argument('paths', nargs='*', help='Track paths to lookup')

    script.run()
Example #17
0
 def __init__(self, *args, **kwargs):
     Script.__init__(self, *args, **kwargs)
     self.runner = None
     self.mode = ''
Example #18
0
 def __init__(self, description=None):
     object.__setattr__(self, 'state_code', NAGIOS_INITIAL_STATE)
     self.message = 'UNINITIALIZED'
     self.parser = Script(description=description)
Example #19
0
 def __init__(self, *args, **kwargs):
     Script.__init__(self, *args, **kwargs)
     self.runner = None
     self.mode = ''
     self.add_argument('--version', action='store_true', help='show version')
Example #20
0
def main():
    script = Script('pytunes-playlists',
                    'Import and export music player playlists')

    c = script.add_subcommand(ListCommand('list', 'List playlists'))
    c.add_argument('-s',
                   '--smart-playlists',
                   action='store_true',
                   help='Include smart playlists')
    c.add_argument('-y',
                   '--yearly',
                   action='store_true',
                   help='Order listed tracks by year')
    c.add_argument('-f', '--format', help='List formatting string')
    c.add_argument('playlists', nargs='*', help='Playlists to process')

    c = script.add_subcommand(
        ExportFilesCommand('export-files', 'Export playlists as files'))
    c.add_argument('-s',
                   '--smart-playlists',
                   action='store_true',
                   help='Include smart playlists')
    c.add_argument('-y',
                   '--yearly',
                   action='store_true',
                   help='Order exported tracks by year')
    c.add_argument('-f', '--format', help='Filename formatting string')
    c.add_argument('playlists', nargs='*', help='Playlists to process')

    c = script.add_subcommand(ExportCommand('export', 'Export m3u playlists'))
    script.add_argument('-D',
                        '--directory',
                        default=DEFAULT_DIRECTORY,
                        help='Playlist directory for m3u files')
    c.add_argument('-s',
                   '--smart-playlists',
                   action='store_true',
                   help='Include smart playlists')
    c.add_argument('-E',
                   '--ignore-empty',
                   action='store_true',
                   help='Ignore empty playlists')
    c.add_argument('playlists', nargs='*', help='Playlists to process')

    c = script.add_subcommand(ImportCommand('import', 'Import playlists'))
    c.add_argument('-s',
                   '--smart-playlists',
                   action='store_true',
                   help='Include smart playlists')
    c.add_argument('playlists', nargs='*', help='Playlists to process')

    c = script.add_subcommand(CreateCommand('create', 'Create playlists'))
    c.add_argument('names', nargs='*', help='Names of playlists to create')

    c = script.add_subcommand(RemoveCommand('remove', 'Remove playlists'))
    c.add_argument('names', nargs='*', help='Names of playlists to create')

    script.run()
Example #21
0
def main():

    script = Script()
    script.add_argument('-f',
                        '--log-file',
                        default=DEFAULT_LOGFILE,
                        help='Log file')
    script.add_argument('-c',
                        '--configuration-file',
                        default=DEFAULT_CONFIGURATION_PATH,
                        help='Log file')
    script.add_argument('-h', '--redis-host', help='Redis host')
    script.add_argument('-r', '--redis-auth', help='Redis auth')
    args = script.parse_args()

    try:
        configuration = DaemonConfiguration(
            args.configuration_file,
            args.log_file,
            args.redis_host,
            args.redis_auth,
        )
    except Exception as e:
        script.exit(1, e)

    try:
        Daemon(**configuration).run()
    except MusicPlayerError as e:
        script.exit(1, e)
Example #22
0
class NagiosPlugin(object):
    """Nagios plugin base class

    Implementation of nagios plugin in python

    See examples directory in source code for usage
    """
    def __init__(self, description=None):
        object.__setattr__(self, 'state_code', NAGIOS_INITIAL_STATE)
        self.message = 'UNINITIALIZED'
        self.parser = Script(description=description)

    def __repr__(self):
        return '{0} {1}'.format(self.state_message, self.message)

    def __setattr__(self, attr, value):
        if attr == 'state':
            self.set_state(value)
        object.__setattr__(self, attr, value)

    @property
    def state_message(self):
        return NAGIOS_STATES[self.state_code]

    def set_state(self, value):
        """Set nagios plugin state

        Sets internal state to provided value, which can be integer from 0 to 3
        or one of strings 'OK', 'WARNING', 'CRITICAL', 'UNKNOWN'

        Silently refuses to lower plugin state to less critical error. UNKNOWN
        state can always be overwritten.
        """
        try:
            value = int(value)
            if value not in NAGIOS_STATES.keys():
                raise ValueError
        except ValueError:
            pass

        if value in NAGIOS_STATES.keys():
            state_code = int(value)
        else:
            for k, v in NAGIOS_STATES.items():
                if value == v:
                    state_code = k
                    break

        if state_code not in NAGIOS_STATES.keys():
            raise AttributeError(
                'Attempt to set invalid plugin state {0}'.format(value))

        # Silently ignore lowering of error state for a plugin
        if self.state_code != NAGIOS_INITIAL_STATE and self.state_code > state_code:
            self.parser.log.debug(
                'Refuse lowering state from {0} to {1}'.format(
                    self.state_code, state_code))
            return

        object.__setattr__(self, 'state_code', state_code)

    def add_argument(self, *args, **kwargs):
        """Add CLI argument

        Add CLI argument. Uses argparse.ArgumentParser.add_argument syntax

        """
        self.parser.add_argument(*args, **kwargs)

    def parse_args(self, *args, **kwargs):
        """Parse arguments

        Parse self.parser arguments. Called automatically from self.run()

        """
        self.args = self.parser.parse_args(*args, **kwargs)
        return self.args

    def error(self, message, code=2):
        """Exit with error

        Exit with error code (must be valid nagios state code)

        Writes error message to stdout

        """
        try:
            code = int(code)
            if code not in NAGIOS_STATES.keys():
                raise ValueError
        except ValueError:
            raise AttributeError('Invalid error code {0}'.format(code))

        sys.stdout.write('Error running plugin: {0}\n'.format(message))
        sys.exit(code)

    def exit(self):
        """Return nagios message and exit

        Print self.state_message + self.message to stdout for nagios and
        exit with self.state_code code

        """
        sys.stdout.write('{0} {1}\n'.format(self.state_message, self.message))
        sys.exit(self.state_code)

    def run(self):
        """Run the plugin

        Run the plugin:
          - Parse arguments
          - Set message to empty
          - run self.check_plugin_status() callback
          - run self.exit()

        If check_plugin_status raises NagiosPluginError, state is set to
        critical and error message is appended to message before exit
        """
        args = self.parse_args()
        self.message = ''

        try:
            self.check_plugin_status()
        except NagiosPluginError, emsg:
            self.state = 'CRITICAL'
            self.message += '{0}'.format(emsg)

        self.exit()
Example #23
0
def main():
    script = Script()
    script.add_argument('--config',
                        default=DEFAULT_CONFIG_PATH,
                        help='Virtual machine directory')

    script.add_subcommand(ListCommand())
    script.add_subcommand(StatusCommand())
    script.add_subcommand(StartCommand())
    script.add_subcommand(StopCommand())
    script.add_subcommand(ResumeCommand())
    script.add_subcommand(SuspendCommand())
    script.add_subcommand(DetailsCommand())

    script.parse_args()