def flush_aaa_cache(appliances=[],
                    credentials=[],
                    timeout=120,
                    no_check_hostname=False,
                    Domain="",
                    aaa_policy="",
                    web=False):
    """Flushes the AAA Cache of the specified aaa_policy in the
specified Domain.

Parameters:

* `-a, --appliances`: The hostname(s), ip address(es), environment name(s)
or alias(es) of the appliances you would like to affect. For details
on configuring environments please see the comments in
`environments.conf` located in `$MAST_HOME/etc/default`. For details
on configuring aliases, please see the comments in `hosts.conf` located in
`$MAST_HOME/etc/default`. To pass multiple arguments to this parameter,
use multiple entries of the form `[-a appliance1 [-a appliance2...]]`
* `-c, --credentials`: The credentials to use for authenticating to the
appliances. Should be either one set to use for all appliances
or one set for each appliance. Credentials should be in the form
`username:password`. To pass multiple credentials to this parameter, use
multiple entries of the form `[-c credential1 [-c credential2...]]`. 
When referencing multiple appliances with multiple credentials, 
there must be a one-to-one correspondence of credentials to appliances:
`[-a appliance1 [-a appliance2...]] [-c credential1 [-c credential2...]]` 
If you would prefer to not use plain-text passwords, 
you can use the output of `$ mast-system xor <username:password>`.
* `-t, --timeout`: The timeout in seconds to wait for a response from
an appliance for any single request. __NOTE__ Program execution may
halt if a timeout is reached.
* `-n, --no-check-hostname`: If specified SSL verification will be turned
off when sending commands to the appliances.
* `-D, --Domain`: The domain where the aaa_policy resides
* `-A, --aaa-policy`: the AAAPolicy who's cache you would like to flush
* `-w, --web`: __For Internel Use Only, will be removed in future versions.
DO NOT USE.__"""
    logger = make_logger("mast.accounts")
    check_hostname = not no_check_hostname
    env = datapower.Environment(appliances,
                                credentials,
                                timeout,
                                check_hostname=check_hostname)
    msg = "Attempting to flush AAA cache on {}".format(str(env.appliances))
    logger.info(msg)
    if not web:
        print msg

    kwargs = {"PolicyName": aaa_policy, 'domain': Domain}
    responses = env.perform_action('FlushAAACache', **kwargs)
    logger.debug("Responses received {}".format(str(responses)))

    if not web:
        for host, resp in responses.items():
            print "{}\n{}".format(host, "=" * len(host))
            pprint_xml(resp.xml)
    else:
        return util.render_boolean_results_table(
            responses, suffix="flush_aaa_cache"), util.render_history(env)
def flush_rbm_cache(appliances=[],
                    credentials=[],
                    timeout=120,
                    no_check_hostname=False,
                    Domain="",
                    web=False):
    """Flush the RBM Cache in the specified Domain

Parameters:

* `-a, --appliances`: The hostname(s), ip address(es), environment name(s)
or alias(es) of the appliances you would like to affect. For details
on configuring environments please see the comments in
`environments.conf` located in `$MAST_HOME/etc/default`. For details
on configuring aliases, please see the comments in `hosts.conf` located in
`$MAST_HOME/etc/default`. To pass multiple arguments to this parameter,
use multiple entries of the form `[-a appliance1 [-a appliance2...]]`
* `-c, --credentials`: The credentials to use for authenticating to the
appliances. Should be either one set to use for all appliances
or one set for each appliance. Credentials should be in the form
`username:password`. To pass multiple credentials to this parameter, use
multiple entries of the form `[-c credential1 [-c credential2...]]`. 
When referencing multiple appliances with multiple credentials, 
there must be a one-to-one correspondence of credentials to appliances:
`[-a appliance1 [-a appliance2...]] [-c credential1 [-c credential2...]]` 
If you would prefer to not use plain-text passwords, 
you can use the output of `$ mast-system xor <username:password>`.
* `-t, --timeout`: The timeout in seconds to wait for a response from
an appliance for any single request. __NOTE__ Program execution may
halt if a timeout is reached.
* `-n, --no-check-hostname`: If specified SSL verification will be turned
off when sending commands to the appliances.
* `-D, --Domain`: The domain for which to flush the RBM Cache
* `-w, --web`: __For Internel Use Only, will be removed in future versions.
DO NOT USE.__"""
    logger = make_logger("mast.accounts")
    check_hostname = not no_check_hostname
    env = datapower.Environment(
        appliances,
        credentials,
        timeout,
        check_hostname=check_hostname)
    msg = "Attempting to flush RBM cache on {}".format(str(env.appliances))
    logger.info(msg)
    if not web:
        print msg

    responses = env.perform_action('FlushRBMCache', **{'domain': Domain})
    logger.debug("Responses received {}".format(str(responses)))

    if not web:
        for host, resp in responses.items():
            print "{}\n{}".format(host, "="*len(host))
            pprint_xml(resp.xml)
    else:
        return util.render_boolean_results_table(
            responses, suffix="flush_rbm_cache"), util.render_history(env)
def main(
    appliances=[],
    credentials=[],
    timeout=120,
    no_check_hostname=False,
    dry_run=False,
    save_config=False,
):
    check_hostname = not no_check_hostname
    env = datapower.Environment(hostnames=appliances,
                                credentials=credentials,
                                timeout=timeout,
                                check_hostname=check_hostname)
    allaterror = etree.fromstring(
        '<LogEvents><Class class="LogLabel">all</Class><Priority>error</Priority></LogEvents>'
    )
    for appliance in env.appliances:
        print(appliance.hostname)
        for domain in appliance.domains:
            changed = False
            print("\t{}".format(domain))
            config = appliance.get_config("LogTarget",
                                          "default-log",
                                          domain=domain,
                                          persisted=False)
            config = etree.fromstring(str(config))
            #config = config.xpath(r"/env:Envelope/env:Body/dp:response/dp:config/LogTarget", nsmap=nsmap)
            config = config.xpath(
                r'/*[local-name()="Envelope"]/*[local-name()="Body"]/*[local-name()="response"]/*[local-name()="config"]/*[local-name()="LogTarget"]'
            )[0]
            if len(
                    config.xpath(
                        './LogEvents[not(./Class/text()="all") or not(./Priority/text()="error")]'
                    )):
                changed = True
                #pprint_xml(config)
                for nodeset in config.xpath(r'./*[local-name()="LogEvents"]'):
                    config.remove(nodeset)
                config.append(allaterror)
                #pprint_xml_str(etree.tostring(config))
                appliance.request.clear()
                request = appliance.request.request(domain=domain).set_config
                request.append(config)
                for nodeset in config.xpath(r'.//*'):
                    if "read-only" in nodeset.attrib:
                        nodeset.attrib.pop("read-only")
                #print(appliance.request)
                if not dry_run:
                    print(appliance.send_request(boolean=True))
                else:
                    pprint_xml(allaterror)
                print(" ")
            if save_config and not dry_run and changed:
                appliance.SaveConfig(domain=domain)
def _import(appliances=[],
            credentials=[],
            timeout=120,
            no_check_hostname=False,
            Domain=[],
            file_in=None,
            deployment_policy=None,
            dry_run=False,
            overwrite_files=True,
            overwrite_objects=True,
            rewrite_local_ip=True,
            source_type='ZIP',
            out_dir="tmp/",
            web=False):
    """Import a service/object into the specified appliances

Parameters:

* `-a, --appliances`: The hostname(s), ip address(es), environment name(s)
or alias(es) of the appliances you would like to affect. For details
on configuring environments please see the comments in
`environments.conf` located in `$MAST_HOME/etc/default`. For details
on configuring aliases, please see the comments in `hosts.conf` located in
`$MAST_HOME/etc/default`. To pass multiple arguments to this parameter,
use multiple entries of the form `[-a appliance1 [-a appliance2...]]`
* `-c, --credentials`: The credentials to use for authenticating to the
appliances. Should be either one set to use for all appliances
or one set for each appliance. Credentials should be in the form
`username:password`. To pass multiple credentials to this parameter, use
multiple entries of the form `[-c credential1 [-c credential2...]]`.
When referencing multiple appliances with multiple credentials,
there must be a one-to-one correspondence of credentials to appliances:
`[-a appliance1 [-a appliance2...]] [-c credential1 [-c credential2...]]`
If you would prefer to not use plain-text passwords,
you can use the output of `$ mast-system xor <username:password>`.
* `-t, --timeout`: The timeout in seconds to wait for a response from
an appliance for any single request. __NOTE__ Program execution may
halt if a timeout is reached.
* `-n, --no-check-hostname`: If specified SSL verification will be turned
off when sending commands to the appliances.
* `-D. --Domain`: The domain into which the configuration will be imported
* `-f, --file-in`: The file to import into the specified domain. This
__MUST__ match the format specified in source_type
* `-d, --deployment-policy`: The deployment policy to use for the import
(must already exist on the appliances)
* `--dry-run`: Whether to do a dry-run (nothing will be imported)
* `-N, --no-overwrite-files`: If specified, no files will be overwritten
as part of the import
* `--no-overwrite-objects`: If specified, no objects will be overwritten
as part of the import
* `--no-rewrite-local-ip`: If specified, no local ip addresses will be
rewritten as part of the import
* `-s, --source-type`: The type of file to import. Can be "XML" or "ZIP"
* `-o, --out-dir`: The directory to output artifacts generated by this
script
* `-w, --web`: __For Internel Use Only, will be removed in future versions.
DO NOT USE.__"""
    logger = make_logger("mast.developer")
    t = Timestamp()

    check_hostname = not no_check_hostname
    env = datapower.Environment(
        appliances,
        credentials,
        timeout,
        check_hostname=check_hostname)
    msg = "Attempting to import {} to {}".format(file_in, str(env.appliances))
    logger.info(msg)
    if not web:
        print msg

    results = {}
    out_dir = os.path.join(out_dir, "import_results", t.timestamp)
    os.makedirs(out_dir)
    for appliance in env.appliances:
        if not web:
            print appliance.hostname
        results[appliance.hostname] = {}
        domains = Domain
        if "all-domains" in domains:
            domains = appliance.domains
        for domain in domains:
            if not web:
                print "\t", domain
            kwargs = {
                'domain': domain,
                'zip_file': file_in,
                'deployment_policy': deployment_policy,
                'dry_run': dry_run,
                'overwrite_files': overwrite_files,
                'overwrite_objects': overwrite_objects,
                'rewrite_local_ip': rewrite_local_ip,
                'source_type': source_type}

            resp = appliance.do_import(**kwargs)
            results[appliance.hostname][domain] = resp
            if not web:
                pprint_xml(resp.xml)
            logger.debug("Response received: {}".format(str(resp)))


            filename = os.path.join(
                out_dir,
                "{}-{}-import_results.xml".format(
                    appliance.hostname,
                    domain
                )
            )
            with open(filename, 'wb') as fout:
                fout.write(resp.pretty)
    if web:
        return util.render_see_download_table(
            results, suffix="import"), util.render_history(env)
def add_group(appliances=[],
              credentials=[],
              timeout=120,
              no_check_hostname=False,
              save_config=False,
              name=None,
              access_policies=[],
              web=False):
    """Adds a user group to the specified appliances.

Parameters:

* `-a, --appliances`: The hostname(s), ip address(es), environment name(s)
or alias(es) of the appliances you would like to affect. For details
on configuring environments please see the comments in
`environments.conf` located in `$MAST_HOME/etc/default`. For details
on configuring aliases, please see the comments in `hosts.conf` located in
`$MAST_HOME/etc/default`. To pass multiple arguments to this parameter,
use multiple entries of the form `[-a appliance1 [-a appliance2...]]`
* `-c, --credentials`: The credentials to use for authenticating to the
appliances. Should be either one set to use for all appliances
or one set for each appliance. Credentials should be in the form
`username:password`. To pass multiple credentials to this parameter, use
multiple entries of the form `[-c credential1 [-c credential2...]]`. 
When referencing multiple appliances with multiple credentials, 
there must be a one-to-one correspondence of credentials to appliances:
`[-a appliance1 [-a appliance2...]] [-c credential1 [-c credential2...]]`
If you would prefer to not use plain-text passwords, 
you can use the output of `$ mast-system xor <username:password>`.
* `-t, --timeout`: The timeout in seconds to wait for a response from
an appliance for any single request. __NOTE__ Program execution may
halt if a timeout is reached.
* `-n, --no-check-hostname`: If specified SSL verification will be turned
off when sending commands to the appliances.
* `-s, --save-config`: If specified the configuration on the appliances
will be saved
* `-N, --name`: The name of the group to add
* `-A, --access-policies`: The access policies which will be associated
with this group
* `-w, --web`: __For Internel Use Only, will be removed in future versions.
DO NOT USE.__"""
    logger = make_logger("mast.accounts")
    check_hostname = not no_check_hostname
    env = datapower.Environment(
        appliances,
        credentials,
        timeout,
        check_hostname=check_hostname)

    kwargs = {'name': name, 'access_policies': access_policies}
    msg = "Adding group {} to {}".format(name, str(env.appliances))
    logger.info(msg)
    if not web:
        print msg
    resp = env.perform_async_action('add_group', **kwargs)
    logger.debug("responses received {}".format(str(resp)))
    if not web:
        for host, resp in resp.items():
            print "{}\n{}".format(host, "="*len(host))
            pprint_xml(resp.xml)
    else:
        output = util.render_boolean_results_table(resp, suffix="add_group")

    if save_config:
        kwargs = {'domain': 'default'}
        msg = "Saving configuration in the default domain of {}".format(str(env.appliances))
        logger.info(msg)
        if not web:
            print msg
        resp = env.perform_async_action('SaveConfig', **kwargs)
        logger.debug("Responses received {}".format(str(resp)))
        if not web:
            for host, resp in resp.items():
                print "{}\n{}".format(host, "="*len(host))
                pprint_xml(resp.xml)
        else:
            output += util.render_boolean_results_table(
                resp, suffix="save_config")
    if web:
        return output, util.render_history(env)
def change_password(appliances=[],
                    credentials=[],
                    timeout=120,
                    no_check_hostname=False,
                    save_config=False,
                    User="",
                    password="",
                    web=False):
    """Changes the specified user's password to the specified password.

Parameters:

* `-a, --appliances`: The hostname(s), ip address(es), environment name(s)
or alias(es) of the appliances you would like to affect. For details
on configuring environments please see the comments in
`environments.conf` located in `$MAST_HOME/etc/default`. For details
on configuring aliases, please see the comments in `hosts.conf` located in
`$MAST_HOME/etc/default`. To pass multiple arguments to this parameter,
use multiple entries of the form `[-a appliance1 [-a appliance2...]]`
* `-c, --credentials`: The credentials to use for authenticating to the
appliances. Should be either one set to use for all appliances
or one set for each appliance. Credentials should be in the form
`username:password`. To pass multiple credentials to this parameter, use
multiple entries of the form `[-c credential1 [-c credential2...]]`. 
When referencing multiple appliances with multiple credentials, 
there must be a one-to-one correspondence of credentials to appliances:
`[-a appliance1 [-a appliance2...]] [-c credential1 [-c credential2...]]` 
If you would prefer to not use plain-textpasswords, 
you can use the output of `$ mast-system xor <username:password>`.
* `-t, --timeout`: The timeout in seconds to wait for a response from
an appliance for any single request. __NOTE__ Program execution may
halt if a timeout is reached.
* `-n, --no-check-hostname`: If specified SSL verification will be turned
off when sending commands to the appliances.
* `-s, --save-config`: If specified the configuration on the appliances will
be saved
* `-U, --User`: The name of the user whose password you are changing
* `-p, --password`: The new password for the specified user. NOTE: You may need to
place quotations around the argument passed if using special characters as these
might be incorrectly interpreted by your shell.
* `-w, --web`: __For Internel Use Only, will be removed in future versions.
DO NOT USE.__"""
    logger = make_logger("mast.accounts")
    check_hostname = not no_check_hostname
    env = datapower.Environment(
        appliances,
        credentials,
        timeout,
        check_hostname=check_hostname)
    msg = "Attempting to change password for {} on {}".format(User, str(env.appliances))
    logger.info(msg)
    if not web:
        print msg

    kwargs = {'username': User, 'password': password}
    resp = env.perform_async_action('change_password', **kwargs)
    logger.debug("Responses received {}".format(str(resp)))

    if not web:
        for host, resp in resp.items():
            print "{}\n{}".format(host, "="*len(host))
            pprint_xml(resp.xml)
    else:
        output = util.render_boolean_results_table(
            resp, suffix="change_password")

    if save_config:
        msg = "Attempting to save config of default domain on {}".format(str(env.appliances))
        logger.info(msg)
        if not web:
            print msg
        resp = env.perform_async_action('SaveConfig', **{'domain': 'default'})
        logger.debug("Responses received {}".format(str(resp)))
        if not web:
            for host, resp in resp.items():
                print "{}\n{}".format(host, "="*len(host))
                pprint_xml(resp.xml)
        else:
            output += util.render_boolean_results_table(
                resp, suffix="save_config")
    if web:
        return output, util.render_history(env)
def _import(appliances=[],
            credentials=[],
            timeout=120,
            no_check_hostname=False,
            Domain=[],
            file_in=None,
            deployment_policy=None,
            deployment_policy_variables=None,
            dry_run=False,
            overwrite_files=True,
            overwrite_objects=True,
            rewrite_local_ip=True,
            source_type='ZIP',
            out_dir="tmp/",
            web=False):
    """Import a service/object into the specified appliances

Parameters:

* `-a, --appliances`: The hostname(s), ip address(es), environment name(s)
or alias(es) of the appliances you would like to affect. For details
on configuring environments please see the comments in
`environments.conf` located in `$MAST_HOME/etc/default`. For details
on configuring aliases, please see the comments in `hosts.conf` located in
`$MAST_HOME/etc/default`. To pass multiple arguments to this parameter,
use multiple entries of the form `[-a appliance1 [-a appliance2...]]`
* `-c, --credentials`: The credentials to use for authenticating to the
appliances. Should be either one set to use for all appliances
or one set for each appliance. Credentials should be in the form
`username:password`. To pass multiple credentials to this parameter, use
multiple entries of the form `[-c credential1 [-c credential2...]]`.
When referencing multiple appliances with multiple credentials,
there must be a one-to-one correspondence of credentials to appliances:
`[-a appliance1 [-a appliance2...]] [-c credential1 [-c credential2...]]`
If you would prefer to not use plain-text passwords,
you can use the output of `$ mast-system xor <username:password>`.
* `-t, --timeout`: The timeout in seconds to wait for a response from
an appliance for any single request. __NOTE__ Program execution may
halt if a timeout is reached.
* `-n, --no-check-hostname`: If specified SSL verification will be turned
off when sending commands to the appliances.
* `-D. --Domain`: The domain into which the configuration will be imported
* `-f, --file-in`: The file to import into the specified domain. This
__MUST__ match the format specified in source_type
* `-d, --deployment-policy`: The deployment policy to use for the import
(must already exist on the appliances)
* `--dry-run`: Whether to do a dry-run (nothing will be imported)
* `-N, --no-overwrite-files`: If specified, no files will be overwritten
as part of the import
* `--no-overwrite-objects`: If specified, no objects will be overwritten
as part of the import
* `--no-rewrite-local-ip`: If specified, no local ip addresses will be
rewritten as part of the import
* `-s, --source-type`: The type of file to import. Can be "XML" or "ZIP"
* `-o, --out-dir`: The directory to output artifacts generated by this
script
* `-w, --web`: __For Internel Use Only, will be removed in future versions.
DO NOT USE.__"""
    logger = make_logger("mast.developer")
    t = Timestamp()

    check_hostname = not no_check_hostname
    env = datapower.Environment(
        appliances,
        credentials,
        timeout,
        check_hostname=check_hostname)
    msg = "Attempting to import {} to {}".format(file_in, str(env.appliances))
    logger.info(msg)
    if not web:
        print msg

    results = {}
    out_dir = os.path.join(out_dir, "import_results", t.timestamp)
    os.makedirs(out_dir)
    for appliance in env.appliances:
        if not web:
            print appliance.hostname
        results[appliance.hostname] = {}
        domains = Domain
        if "all-domains" in domains:
            domains = appliance.domains
        for domain in domains:
            if not web:
                print "\t", domain
            kwargs = {
                'domain': domain,
                'zip_file': file_in,
                'deployment_policy': deployment_policy,
                'deployment_policy_variables': deployment_policy_variables,
                'dry_run': dry_run,
                'overwrite_files': overwrite_files,
                'overwrite_objects': overwrite_objects,
                'rewrite_local_ip': rewrite_local_ip,
                'source_type': source_type}

            resp = appliance.do_import(**kwargs)
            results[appliance.hostname][domain] = resp
            if not web:
                pprint_xml(resp.xml)
            logger.debug("Response received: {}".format(str(resp)))


            filename = os.path.join(
                out_dir,
                "{}-{}-import_results.xml".format(
                    appliance.hostname,
                    domain
                )
            )
            with open(filename, 'wb') as fout:
                fout.write(resp.pretty)
    if web:
        return util.render_see_download_table(
            results, suffix="import"), util.render_history(env)
def add_group(appliances=[],
              credentials=[],
              timeout=120,
              no_check_hostname=False,
              save_config=False,
              name=None,
              access_policies=[],
              web=False):
    """Adds a user group to the specified appliances.

Parameters:

* `-a, --appliances`: The hostname(s), ip address(es), environment name(s)
or alias(es) of the appliances you would like to affect. For details
on configuring environments please see the comments in
`environments.conf` located in `$MAST_HOME/etc/default`. For details
on configuring aliases, please see the comments in `hosts.conf` located in
`$MAST_HOME/etc/default`. To pass multiple arguments to this parameter,
use multiple entries of the form `[-a appliance1 [-a appliance2...]]`
* `-c, --credentials`: The credentials to use for authenticating to the
appliances. Should be either one set to use for all appliances
or one set for each appliance. Credentials should be in the form
`username:password`. To pass multiple credentials to this parameter, use
multiple entries of the form `[-c credential1 [-c credential2...]]`. 
When referencing multiple appliances with multiple credentials, 
there must be a one-to-one correspondence of credentials to appliances:
`[-a appliance1 [-a appliance2...]] [-c credential1 [-c credential2...]]`
If you would prefer to not use plain-text passwords, 
you can use the output of `$ mast-system xor <username:password>`.
* `-t, --timeout`: The timeout in seconds to wait for a response from
an appliance for any single request. __NOTE__ Program execution may
halt if a timeout is reached.
* `-n, --no-check-hostname`: If specified SSL verification will be turned
off when sending commands to the appliances.
* `-s, --save-config`: If specified the configuration on the appliances
will be saved
* `-N, --name`: The name of the group to add
* `-A, --access-policies`: The access policies which will be associated
with this group
* `-w, --web`: __For Internel Use Only, will be removed in future versions.
DO NOT USE.__"""
    logger = make_logger("mast.accounts")
    check_hostname = not no_check_hostname
    env = datapower.Environment(appliances,
                                credentials,
                                timeout,
                                check_hostname=check_hostname)

    kwargs = {'name': name, 'access_policies': access_policies}
    msg = "Adding group {} to {}".format(name, str(env.appliances))
    logger.info(msg)
    if not web:
        print msg
    resp = env.perform_async_action('add_group', **kwargs)
    logger.debug("responses received {}".format(str(resp)))
    if not web:
        for host, resp in resp.items():
            print "{}\n{}".format(host, "=" * len(host))
            pprint_xml(resp.xml)
    else:
        output = util.render_boolean_results_table(resp, suffix="add_group")

    if save_config:
        kwargs = {'domain': 'default'}
        msg = "Saving configuration in the default domain of {}".format(
            str(env.appliances))
        logger.info(msg)
        if not web:
            print msg
        resp = env.perform_async_action('SaveConfig', **kwargs)
        logger.debug("Responses received {}".format(str(resp)))
        if not web:
            for host, resp in resp.items():
                print "{}\n{}".format(host, "=" * len(host))
                pprint_xml(resp.xml)
        else:
            output += util.render_boolean_results_table(resp,
                                                        suffix="save_config")
    if web:
        return output, util.render_history(env)
def change_password(appliances=[],
                    credentials=[],
                    timeout=120,
                    no_check_hostname=False,
                    save_config=False,
                    User="",
                    password="",
                    web=False):
    """Changes the specified user's password to the specified password.

Parameters:

* `-a, --appliances`: The hostname(s), ip address(es), environment name(s)
or alias(es) of the appliances you would like to affect. For details
on configuring environments please see the comments in
`environments.conf` located in `$MAST_HOME/etc/default`. For details
on configuring aliases, please see the comments in `hosts.conf` located in
`$MAST_HOME/etc/default`. To pass multiple arguments to this parameter,
use multiple entries of the form `[-a appliance1 [-a appliance2...]]`
* `-c, --credentials`: The credentials to use for authenticating to the
appliances. Should be either one set to use for all appliances
or one set for each appliance. Credentials should be in the form
`username:password`. To pass multiple credentials to this parameter, use
multiple entries of the form `[-c credential1 [-c credential2...]]`. 
When referencing multiple appliances with multiple credentials, 
there must be a one-to-one correspondence of credentials to appliances:
`[-a appliance1 [-a appliance2...]] [-c credential1 [-c credential2...]]` 
If you would prefer to not use plain-textpasswords, 
you can use the output of `$ mast-system xor <username:password>`.
* `-t, --timeout`: The timeout in seconds to wait for a response from
an appliance for any single request. __NOTE__ Program execution may
halt if a timeout is reached.
* `-n, --no-check-hostname`: If specified SSL verification will be turned
off when sending commands to the appliances.
* `-s, --save-config`: If specified the configuration on the appliances will
be saved
* `-U, --User`: The name of the user whose password you are changing
* `-p, --password`: The new password for the specified user. NOTE: You may need to
place quotations around the argument passed if using special characters as these
might be incorrectly interpreted by your shell.
* `-w, --web`: __For Internel Use Only, will be removed in future versions.
DO NOT USE.__"""
    logger = make_logger("mast.accounts")
    check_hostname = not no_check_hostname
    env = datapower.Environment(appliances,
                                credentials,
                                timeout,
                                check_hostname=check_hostname)
    msg = "Attempting to change password for {} on {}".format(
        User, str(env.appliances))
    logger.info(msg)
    if not web:
        print msg

    kwargs = {'username': User, 'password': password}
    resp = env.perform_async_action('change_password', **kwargs)
    logger.debug("Responses received {}".format(str(resp)))

    if not web:
        for host, resp in resp.items():
            print "{}\n{}".format(host, "=" * len(host))
            pprint_xml(resp.xml)
    else:
        output = util.render_boolean_results_table(resp,
                                                   suffix="change_password")

    if save_config:
        msg = "Attempting to save config of default domain on {}".format(
            str(env.appliances))
        logger.info(msg)
        if not web:
            print msg
        resp = env.perform_async_action('SaveConfig', **{'domain': 'default'})
        logger.debug("Responses received {}".format(str(resp)))
        if not web:
            for host, resp in resp.items():
                print "{}\n{}".format(host, "=" * len(host))
                pprint_xml(resp.xml)
        else:
            output += util.render_boolean_results_table(resp,
                                                        suffix="save_config")
    if web:
        return output, util.render_history(env)
Example #10
0
def main(appliances=[],
         credentials=[],
         timeout=120,
         no_check_hostname=False,
         domains=[],
         obj_class="",
         obj_name_filter="",
         obj_filter="",
         mods=[],
         dry_run=False,
         save_config=False):
    check_hostname = not no_check_hostname
    env = datapower.Environment(appliances,
                                credentials,
                                timeout=timeout,
                                check_hostname=check_hostname)
    if obj_name_filter:
        obj_name_filter = re.compile(obj_name_filter)
    else:
        obj_name_filter = re.compile(".*")

    if obj_filter:
        obj_filter = re.compile(obj_filter)
    else:
        obj_filter = re.compile(".*")

    for appliance in env.appliances:
        print appliance.hostname
        _domains = domains
        if "all-domains" in domains:
            _domains = appliance.domains
        for domain in _domains:
            print "\t", domain
            print "\t\t", obj_class
            config = appliance.get_config(_class=obj_class, domain=domain)
            objs = config.xml.findall(datapower.CONFIG_XPATH)
            objs = filter(lambda x: obj_name_filter.search(x.get("name")),
                          objs)
            objs = filter(
                lambda x: obj_filter.search(datapower.etree.tostring(x)), objs)
            for obj in objs:
                name = obj.get("name")
                print "\t\t\t{}".format(name)
                appliance.request.clear()
                request = appliance.request.request(
                    domain=domain).modify_config()[obj_class](name=name)

                parsed_mods = tree()
                for mod in mods:
                    k, v = mod.split("=")
                    if "/" in k:
                        ks = k.split("/")
                        level = parsed_mods
                        for _k in ks:
                            last_level = level
                            level = level[_k]
                        last_level[_k] = v
                    else:
                        parsed_mods[k] = v

                def append_mods(request, mods):
                    for k, v in mods.items():
                        if k.startswith("(vector-add)"):
                            k = k.replace("(vector-add)", "")
                            for node in obj.findall(k):
                                request.append(node)
                        if isinstance(v, defaultdict):
                            append_mods(request[k], v)
                        else:
                            request[k](v)

                append_mods(request, parsed_mods)

                if dry_run:
                    pprint_xml(obj)
                    pprint_xml_str(str(appliance.request))
                    continue
                else:
                    resp = appliance.send_request()
                if resp:
                    print "\t\t\t\tOK"
                else:
                    print "\t\t\t\tERROR, see log for details"
            if save_config and not dry_run:
                appliance.SaveConfig(domain=domain)