Esempio n. 1
0
def test_batch_until():

    pool = arcomm.batch([HOST, HOST], ['show clock'], condition=r'\:[0-5]0',
                 timeout=30, sleep=.1)

    for res in pool:
        assert isinstance(res, arcomm.ResponseStore)
Esempio n. 2
0
def test_batch_callback():
    def _cb(response):
        global batch_called_back
        assert isinstance(response, arcomm.response.ResponseStore)
        batch_called_back = 'test_batch_called_back'

    response = arcomm.batch([HOST], ["configure", "hostname veos-01"], callback=_cb)
    for r in response:
        pass

    assert batch_called_back == 'test_batch_called_back'
Esempio n. 3
0
def main():
    from argparse import ArgumentParser
    parser = ArgumentParser(prog="arcomm")
    arg = parser.add_argument

    arg("endpoints", nargs="*")

    arg("-v", "--version", action="store_true", help="display version info")

    arg("--protocol",
        help=("set the protocol. By default 'eapi' is used."),
        choices=["eapi", "eapi+https", "mock", "ssh"])

    arg("-u",
        "--username",
        default="admin",
        help="specifies the username on the switch")

    arg("-p", "--password", default=None, help="specifies users password")

    arg("--no-password",
        action="store_true",
        help="specifies no password required for user")

    arg("-s", "--secret-file", help="read passwords from file")

    arg("--authorize", action="store_true")

    arg("-a",
        "--authorize-password",
        default=None,
        help=("use if a password is needed for elevated prvilges"))

    arg("-t",
        "--timeout",
        type=int,
        default=30,
        help=("change the timeout from the default of 30 seconds"))

    arg("--hosts-file", help="path to file containing list of hosts")

    arg("--script",
        help=("path to a script file containing commands to "
              "execute. template variables will be processed if "
              "Jinja2 is installed and `--variables` is also "
              "supplied on the command line"))

    arg("--variables",
        help=("replacements for template variables in script "
              "file (must be JSON formatted)"))

    ssh_group = parser.add_argument_group('SSH Options', '')
    ssh_arg = ssh_group.add_argument

    ssh_arg("--identity-file", help="specifies identity file")

    eapi_group = parser.add_argument_group('eAPI Options', '')

    eapi_arg = eapi_group.add_argument

    eapi_arg("--encoding",
             default="text",
             choices=["json", "text"],
             help="control output formatting")

    eapi_arg("--no-verify",
             action="store_true",
             help="when using eAPI over HTTPS, don't verify certificate")

    eapi_arg("--private-key", help="specifies private key file")
    eapi_arg("--certificate", help="specifies client certificate file")

    args = parser.parse_args()

    options = {}
    endpoints = []

    if args.version:
        parser.exit(0, arcomm.__version__ + "\n")

    if args.hosts_file:
        endpoints = arcomm.util.load_endpoints(args.hosts_file)
    else:
        endpoints = args.endpoints

    if not endpoints:
        raise ValueError('no endpoints')

    if args.authorize_password:
        options['authorize'] = args.authorize_password
    elif args.authorize:
        options['authorize'] = ''

    username = args.username

    if args.no_password:
        password = ""
    else:
        password = args.password

    if not username:
        username = getpass.getuser()

    if args.secret_file:
        with open(args.secret_file, "r") as stream:
            secrets = yaml.load(stream)
            password = secrets.get(username)

    if password is None:
        password = getpass.getpass("password for {}: ".format(username))

    options['creds'] = arcomm.BasicCreds(args.username, password)

    if args.protocol:
        options['protocol'] = args.protocol

    options['timeout'] = args.timeout

    options['encoding'] = args.encoding

    options['verify'] = not args.no_verify

    script = []

    if args.script:
        with open(args.script, 'r') as fh:
            script = fh.read()
            script = script.splitlines()
    elif not sys.stdin.isatty():
        for line in sys.stdin:
            script.append(line)
    else:
        isatty = sys.stdin.isatty()
        if isatty:
            print("Enter commands (one per line).")
            print("Enter '.' alone to send or 'Crtl-C' to quit.")
            try:
                while True:
                    line = input('> ')
                    if line == ".":
                        break
                    script.append(line)
            except (KeyboardInterrupt, SystemExit):
                print("Commands aborted.")
                sys.exit()
        else:
            for line in sys.stdin:
                script.append(line)

    if args.variables:
        import jinja2
        replacements = json.loads(args.variables)
        script = "\n".join(script)
        template = jinja2.Template(script)
        script = template.render(replacements)
        script = script.splitlines()

    for res in arcomm.batch(endpoints, script, **options):
        print('---')
        if options['encoding'] == 'json':
            print(res.to_json())
        else:
            print(res.to_yaml())
    print('...')
Esempio n. 4
0
def test_batch(protocol):
    pool = arcomm.batch([HOST, HOST], ['show version', 'sleep'], protocol=protocol)

    for res in pool:
        assert isinstance(res, arcomm.ResponseStore)
Esempio n. 5
0
def test_batch():
    for res in arcomm.batch([HOST, HOST], ['show version']):
        assert isinstance(res, arcomm.ResponseStore)
Esempio n. 6
0
def main():
    from argparse import ArgumentParser
    parser = ArgumentParser(prog="arcomm")
    arg = parser.add_argument

    arg("endpoints", nargs="*")

    arg("-v", "--version", action="store_true", help="display version info")

    arg("--protocol", help=("set the protocol. By default 'eapi' is used."),
        choices=["eapi", "eapi+https", "mock", "ssh"])

    arg("-u", "--username", default="admin",
        help="specifies the username on the switch")

    arg("-p", "--password", default=None, help="specifies users password")

    arg("--no-password", action="store_true",
        help="specifies no password required for user")

    arg("-s", "--secret-file", help="read passwords from file")

    arg("--authorize", action="store_true")

    arg("-a", "--authorize-password", default=None,
        help=("use if a password is needed for elevated prvilges"))

    arg("-t", "--timeout", type=int, default=30,
        help=("change the timeout from the default of 30 seconds"))

    arg("--hosts-file", help="path to file containing list of hosts")

    arg("--script", help=("path to a script file containing commands to "
                          "execute. template variables will be processed if "
                          "Jinja2 is installed and `--variables` is also "
                          "supplied on the command line"))

    arg("--variables", help=("replacements for template variables in script "
                             "file (must be JSON formatted)"))



    ssh_group = parser.add_argument_group('SSH Options', '')
    ssh_arg = ssh_group.add_argument

    ssh_arg("--identity-file", help="specifies identity file")

    eapi_group = parser.add_argument_group('eAPI Options', '')

    eapi_arg = eapi_group.add_argument

    eapi_arg("--encoding", default="text", choices=["json", "text"],
             help="control output formatting")

    eapi_arg("--no-verify", action="store_true",
             help="when using eAPI over HTTPS, don't verify certificate")

    eapi_arg("--private-key", help="specifies private key file")
    eapi_arg("--certificate", help="specifies client certificate file")

    args = parser.parse_args()

    options = {}
    endpoints = []

    if args.version:
        parser.exit(0, arcomm.__version__ + "\n")

    if args.hosts_file:
        endpoints = arcomm.util.load_endpoints(args.hosts_file)
    else:
        endpoints = args.endpoints

    if not endpoints:
        raise ValueError('no endpoints')

    if args.authorize_password:
        options['authorize'] = args.authorize_password
    elif args.authorize:
        options['authorize'] = ''

    username = args.username

    if args.no_password:
        password = ""
    else:
        password = args.password

    if not username:
        username = getpass.getuser()

    if args.secret_file:
        with open(args.secret_file, "r") as stream:
            secrets = yaml.load(stream)
            password = secrets.get(username)

    if password is None:
        password = getpass.getpass("password for {}: ".format(username))

    options['creds'] = arcomm.BasicCreds(args.username, password)

    if args.protocol:
        options['protocol'] = args.protocol

    options['timeout'] = args.timeout

    options['encoding'] = args.encoding

    options['verify'] = not args.no_verify

    script = []

    if args.script:
        with open(args.script, 'r') as fh:
            script = fh.read()
            script = script.splitlines()
    elif not sys.stdin.isatty():
        for line in sys.stdin:
            script.append(line)
    else:
        isatty = sys.stdin.isatty()
        if isatty:
            print("Enter commands (one per line).")
            print("Enter '.' alone to send or 'Crtl-C' to quit.")
            try:
                while True:
                    line = input('> ')
                    if line == ".":
                        break
                    script.append(line)
            except (KeyboardInterrupt, SystemExit):
                print("Commands aborted.")
                sys.exit()
        else:
            for line in sys.stdin:
                script.append(line)

    if args.variables:
        import jinja2
        replacements = json.loads(args.variables)
        script = "\n".join(script)
        template = jinja2.Template(script)
        script = template.render(replacements)
        script = script.splitlines()

    for res in arcomm.batch(endpoints, script, **options):
        print('---')
        if options['encoding'] == 'json':
            print(res.to_json())
        else:
            print(res.to_yaml())
    print('...')
Esempio n. 7
0
def main():
    from argparse import ArgumentParser
    parser = ArgumentParser(prog="arcomm")
    arg = parser.add_argument

    arg("endpoints", nargs="*")

    arg("-v", "--version", action="store_true", help="Display version info")

    arg("--protocol", help=("Set the protocol. By default 'eapi' is used. "
                            "Note: eapi and eapi+http are the same"),
        choices=["eapi", "eapi+http", "eapi+https", "ssh"])

    arg("--encoding", default="text", choices=["json", "text"],
        help="Control output formatting")

    arg("-u", "--username", help="Specifies the username on the switch")

    arg("-p", "--password", default="", help="Specifies users password.")

    arg("--authorize", action="store_true")

    arg("-a", "--authorize-password", default=None,
        help=("Use if a password is needed for elevated prvilges"))

    arg("-t", "--timeout", type=int, default=30,
        help=("Change the timeout from the default of 30 seconds"))

    arg("--hosts-file", help="Path to file containing list of hosts")

    arg("--script", help=("Path to a script file containing commands to "
                          "execute. template variables will be processed if "
                          "Jinja2 is installed and `--variables` is also "
                          "supplied on the command line"))

    arg("--variables", help=("Replacements for template variables in script "
                             "file (must be JSON formatted)"))

    args = parser.parse_args()

    options = {}
    endpoints = []

    if args.version:
        parser.exit(0, arcomm.__version__ + "\n")

    if args.hosts_file:
        endpoints = arcomm.util.load_endpoints(args.hosts_file)
    else:
        endpoints = args.endpoints

    if not endpoints:
        raise ValueError('no endpoints')

    if args.authorize_password:
        options['authorize'] = args.authorize_password
    elif args.authorize:
        options['authorize'] = ''

    if args.username:
        password = args.password or ''
        options['creds'] = arcomm.BasicCreds(args.username, password)

    if args.protocol:
        options['protocol'] = args.protocol

    options['timeout'] = args.timeout

    options['encoding'] = args.encoding

    script = []

    if args.script:
        with open(path, 'r') as fh:
            script = fh.read()
            script = script.splitlines()
    elif not sys.stdin.isatty():
        for line in sys.stdin:
            script.append(line)
    else:
        isatty = sys.stdin.isatty()
        if isatty:
            print "Enter commands (one per line)."
            print "Enter '.' alone to send or 'Crtl-C' to quit."
            try:
                while True:
                    line = raw_input('> ')
                    if line == ".":
                        break
                    script.append(line)
            except (KeyboardInterrupt, SystemExit):
                print "Commands aborted."
                sys.exit()
        else:
            for line in sys.stdin:
                script.append(line)

    if args.variables:
        import jinja2
        replacements = json.loads(args.variables)
        script = "\n".join(script)
        template = jinja2.Template(script)
        script = template.render(replacements)
        script = script.splitlines()

    for res in arcomm.batch(args.endpoints, script, **options):
        print '---'
        if options['encoding'] == 'json':
            to_json(res)
        else:
            to_yaml(res)
    print '...'