""" Scripts helpers """ import argparse import getpass import logging import os.path import socket import sys log = logging.getLogger(__name__) def init_logging(options, name, report=None): """Initialize logging from calling script options""" logformat = f"%(asctime)s - {name} - %(levelname)s - %(message)s" if options.debug: loglevel = logging.DEBUG elif options.verbose: loglevel = logging.INFO else: loglevel = logging.WARNING handlers = [] if options.logfile: handlers.append(logging.FileHandler(options.logfile)) if not options.logfile or options.console: handlers.append(logging.StreamHandler()) if report: handlers.append(report.get_handler()) logging.basicConfig(level=loglevel, format=logformat, handlers=handlers) def get_default_opt_value(config, default_config, key): """Retreive default option value from config or default config dictionaries""" if config and key in config: return config[key] return default_config.get(key) def get_opts_parser(desc=None, just_try=False, just_one=False, progress=False, config=None): """Retrieve options parser""" default_config = dict(logfile=None) parser = argparse.ArgumentParser(description=desc) parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", help="Enable verbose mode" ) parser.add_argument( "-d", "--debug", action="store_true", dest="debug", help="Enable debug mode" ) parser.add_argument( "-l", "--log-file", action="store", type=str, dest="logfile", help=f'Log file path (default: {get_default_opt_value(config, default_config, "logfile")})', default=get_default_opt_value(config, default_config, "logfile"), ) parser.add_argument( "-C", "--console", action="store_true", dest="console", help="Always log on console (even if log file is configured)", ) if just_try: parser.add_argument( "-j", "--just-try", action="store_true", dest="just_try", help="Enable just-try mode" ) if just_one: parser.add_argument( "-J", "--just-one", action="store_true", dest="just_one", help="Enable just-one mode" ) if progress: parser.add_argument( "-p", "--progress", action="store_true", dest="progress", help="Enable progress bar" ) return parser def add_email_opts(parser, config=None, **defaults): """Add email options""" email_opts = parser.add_argument_group("Email options") default_config = dict( smtp_host="127.0.0.1", smtp_port=25, smtp_ssl=False, smtp_tls=False, smtp_user=None, smtp_password=None, smtp_debug=False, email_encoding=sys.getdefaultencoding(), sender_name=getpass.getuser(), sender_email=f"{getpass.getuser()}@{socket.gethostname()}", catch_all=False, templates_path=None, ) default_config.update(defaults) email_opts.add_argument( "--smtp-host", action="store", type=str, dest="email_smtp_host", help=f'SMTP host (default: {get_default_opt_value(config, default_config, "smtp_host")})', default=get_default_opt_value(config, default_config, "smtp_host"), ) email_opts.add_argument( "--smtp-port", action="store", type=int, dest="email_smtp_port", help=f'SMTP port (default: {get_default_opt_value(config, default_config, "smtp_port")})', default=get_default_opt_value(config, default_config, "smtp_port"), ) email_opts.add_argument( "--smtp-ssl", action="store_true", dest="email_smtp_ssl", help=f'Use SSL (default: {get_default_opt_value(config, default_config, "smtp_ssl")})', default=get_default_opt_value(config, default_config, "smtp_ssl"), ) email_opts.add_argument( "--smtp-tls", action="store_true", dest="email_smtp_tls", help=f'Use TLS (default: {get_default_opt_value(config, default_config, "smtp_tls")})', default=get_default_opt_value(config, default_config, "smtp_tls"), ) email_opts.add_argument( "--smtp-user", action="store", type=str, dest="email_smtp_user", help=( f'SMTP username (default: {get_default_opt_value(config, default_config, "smtp_user")})' ), default=get_default_opt_value(config, default_config, "smtp_user"), ) email_opts.add_argument( "--smtp-password", action="store", type=str, dest="email_smtp_password", help=( "SMTP password (default:" f' {get_default_opt_value(config, default_config, "smtp_password")})' ), default=get_default_opt_value(config, default_config, "smtp_password"), ) email_opts.add_argument( "--smtp-debug", action="store_true", dest="email_smtp_debug", help=( "Debug SMTP connection (default:" f' {get_default_opt_value(config, default_config, "smtp_debug")})' ), default=get_default_opt_value(config, default_config, "smtp_debug"), ) email_opts.add_argument( "--email-encoding", action="store", type=str, dest="email_encoding", help=( "SMTP encoding (default:" f' {get_default_opt_value(config, default_config, "email_encoding")})' ), default=get_default_opt_value(config, default_config, "email_encoding"), ) email_opts.add_argument( "--sender-name", action="store", type=str, dest="email_sender_name", help=( f'Sender name (default: {get_default_opt_value(config, default_config, "sender_name")})' ), default=get_default_opt_value(config, default_config, "sender_name"), ) email_opts.add_argument( "--sender-email", action="store", type=str, dest="email_sender_email", help=( "Sender email (default:" f' {get_default_opt_value(config, default_config, "sender_email")})' ), default=get_default_opt_value(config, default_config, "sender_email"), ) email_opts.add_argument( "--catch-all", action="store", type=str, dest="email_catch_all", help=( "Catch all sent email: specify catch recipient email address " f'(default: {get_default_opt_value(config, default_config, "catch_all")})' ), default=get_default_opt_value(config, default_config, "catch_all"), ) email_opts.add_argument( "--templates-path", action="store", type=str, dest="email_templates_path", help=( "Load templates from specify directory " f'(default: {get_default_opt_value(config, default_config, "templates_path")})' ), default=get_default_opt_value(config, default_config, "templates_path"), ) def init_email_client(options, **kwargs): """Initialize email client from calling script options""" from mylib.email import EmailClient # pylint: disable=import-outside-toplevel log.info("Initialize Email client") return EmailClient(options=options, initialize=True, **kwargs) def add_sftp_opts(parser): """Add SFTP options to argpase.ArgumentParser""" sftp_opts = parser.add_argument_group("SFTP options") sftp_opts.add_argument( "-H", "--sftp-host", action="store", type=str, dest="sftp_host", help="SFTP Host (default: localhost)", default="localhost", ) sftp_opts.add_argument( "--sftp-port", action="store", type=int, dest="sftp_port", help="SFTP Port (default: 22)", default=22, ) sftp_opts.add_argument( "-u", "--sftp-user", action="store", type=str, dest="sftp_user", help="SFTP User" ) sftp_opts.add_argument( "-P", "--sftp-password", action="store", type=str, dest="sftp_password", help="SFTP Password", ) sftp_opts.add_argument( "--sftp-known-hosts", action="store", type=str, dest="sftp_known_hosts", help="SFTP known_hosts file path (default: ~/.ssh/known_hosts)", default=os.path.expanduser("~/.ssh/known_hosts"), ) sftp_opts.add_argument( "--sftp-auto-add-unknown-host-key", action="store_true", dest="sftp_auto_add_unknown_host_key", help="Auto-add unknown SSH host key", ) return sftp_opts