def _connect(self):
        if not self.connected:
            host = self.get_option('host')
            port = self.get_option('port') or 443
            user = self.get_option('user')
            passwd = self.get_option('password')

            self.queue_message(
                'vvv',
                "Connection to IBM ISAM Appliance established for user: {0} -> {1}"
                .format(user, 'https://{0}:{1}'.format(host, port)))
            # Create appliance object to be used for all calls
            if user == '' or user is None:
                u = ApplianceUser(password=passwd)
            else:
                u = ApplianceUser(username=user, password=passwd)

            # FIXME - add AdminProxy options and handle that here
            #
            ## Create appliance object to be used for all calls
            ## if adminProxy hostname is set, use the ISAMApplianceAdminProxy
            # if adminProxyHostname == '' or adminProxyHostname is None or omitAdminProxy:
            #    self.isam_server = ISAMAppliance(hostname=host, user=u, lmi_port=port)
            # else:
            #    #self.isam_server = ISAMApplianceAdminProxy(adminProxyHostname=adminProxyHostname, user=u, hostname=appliance, adminProxyProtocol=adminProxyProtocol, adminProxyPort=adminProxyPort, adminProxyApplianceShortName=adminProxyApplianceShortName)
            #    pass
            self.isam_server = ISAMAppliance(hostname=host,
                                             user=u,
                                             lmi_port=port)
            self._sub_plugin = {'name': 'isam_server', 'obj': self.isam_server}

            self._connected = True
def main():
    module = AnsibleModule(argument_spec=dict(
        log=dict(required=False,
                 default='INFO',
                 choices=['DEBUG', 'INFO', 'ERROR', 'CRITICAL']),
        appliance=dict(required=True),
        lmi_port=dict(required=False, default=443, type='int'),
        action=dict(required=True),
        force=dict(required=False, default=False, type='bool'),
        username=dict(required=False),
        password=dict(required=True),
        isamapi=dict(required=False, type='dict'),
        adminProxyProtocol=dict(required=False,
                                default='https',
                                choices=['http', 'https']),
        adminProxyHostname=dict(required=False),
        adminProxyPort=dict(required=False, default=443, type='int'),
        adminProxyApplianceShortName=dict(required=False,
                                          default=False,
                                          type='bool'),
        omitAdminProxy=dict(required=False, default=False, type='bool')),
                           supports_check_mode=True)

    module.debug('Started isam module')

    # Process all Arguments
    logLevel = module.params['log']
    force = module.params['force']
    action = module.params['action']
    appliance = module.params['appliance']
    lmi_port = module.params['lmi_port']
    username = module.params['username']
    password = module.params['password']
    adminProxyProtocol = module.params['adminProxyProtocol']
    adminProxyHostname = module.params['adminProxyHostname']
    adminProxyPort = module.params['adminProxyPort']
    adminProxyApplianceShortName = module.params[
        'adminProxyApplianceShortName']
    omitAdminProxy = module.params['omitAdminProxy']

    # Setup logging for format, set log level and redirect to string
    strlog = StringIO()
    DEFAULT_LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format':
                '[%(asctime)s] [PID:%(process)d TID:%(thread)d] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] %(message)s'
            },
        },
        'handlers': {
            'default': {
                'level': logLevel,
                'formatter': 'standard',
                'class': 'logging.StreamHandler',
                'stream': strlog
            },
        },
        'loggers': {
            '': {
                'handlers': ['default'],
                'level': logLevel,
                'propagate': True
            },
            'requests.packages.urllib3.connectionpool': {
                'handlers': ['default'],
                'level': 'ERROR',
                'propagate': True
            }
        }
    }
    logging.config.dictConfig(DEFAULT_LOGGING)

    # Create appliance object to be used for all calls
    if username == '' or username is None:
        u = ApplianceUser(password=password)
    else:
        u = ApplianceUser(username=username, password=password)

    # Create appliance object to be used for all calls
    # if adminProxy hostname is set, use the ISAMApplianceAdminProxy
    if adminProxyHostname == '' or adminProxyHostname is None or omitAdminProxy:
        isam_server = ISAMAppliance(hostname=appliance,
                                    user=u,
                                    lmi_port=lmi_port)
    else:
        isam_server = ISAMApplianceAdminProxy(
            adminProxyHostname=adminProxyHostname,
            user=u,
            hostname=appliance,
            adminProxyProtocol=adminProxyProtocol,
            adminProxyPort=adminProxyPort,
            adminProxyApplianceShortName=adminProxyApplianceShortName)

    # Create options string to pass to action method
    options = 'isamAppliance=isam_server, force=' + str(force)
    if module.check_mode is True:
        options = options + ', check_mode=True'
    if isinstance(module.params['isamapi'], dict):
        for key, value in module.params['isamapi'].iteritems():
            if isinstance(value, basestring):
                options = options + ', ' + key + '="' + value + '"'
            else:
                options = options + ', ' + key + '=' + str(value)
    module.debug('Option to be passed to action: ' + options)

    # Dynamically process the action to be invoked
    # Simple check to restrict calls to just "isam" ones for safety
    if action.startswith('ibmsecurity.isam.'):
        try:
            module_name, method_name = action.rsplit('.', 1)
            module.debug('Action method to be imported from module: ' +
                         module_name)
            module.debug('Action method name is: ' + method_name)
            mod = importlib.import_module(module_name)
            func_ptr = getattr(
                mod, method_name)  # Convert action to actual function pointer
            func_call = 'func_ptr(' + options + ')'

            startd = datetime.datetime.now()

            # Execute requested 'action'
            ret_obj = eval(func_call)

            endd = datetime.datetime.now()
            delta = endd - startd

            ret_obj['stdout'] = strlog.getvalue()
            ret_obj['stdout_lines'] = strlog.getvalue().split()
            ret_obj['start'] = str(startd)
            ret_obj['end'] = str(endd)
            ret_obj['delta'] = str(delta)
            ret_obj['cmd'] = action + "(" + options + ")"
            ret_obj['ansible_facts'] = isam_server.facts

            module.exit_json(**ret_obj)

        except ImportError:
            module.fail_json(
                name=action,
                msg='Error> action belongs to a module that is not found!',
                log=strlog.getvalue())
        except AttributeError:
            module.fail_json(
                name=action,
                msg=
                'Error> invalid action was specified, method not found in module!',
                log=strlog.getvalue())
        except TypeError:
            module.fail_json(
                name=action,
                msg=
                'Error> action does not have the right set of arguments or there is a code bug! Options: '
                + options,
                log=strlog.getvalue())
        except IBMError as e:
            module.fail_json(name=action, msg=str(e), log=strlog.getvalue())
    else:
        module.fail_json(
            name=action,
            msg='Error> invalid action specified, needs to be isam!',
            log=strlog.getvalue())
# Function to pretty print JSON data
def p(jdata):
    pp = pprint.PrettyPrinter(indent=2)
    pp.pprint(jdata)


if __name__ == "__main__":
    """
    This test program should not execute when imported, which would otherwise
    cause problems when generating the documentation.
    """
    # Create a user credential for ISAM appliance
    u = ApplianceUser(username="******", password="******")
    # Create an ISAM appliance with above credential
    isam_server = ISAMAppliance(hostname="192.168.1.2", user=u, lmi_port=443)

    # Get the current SNMP monitoring setup details
    p(ibmsecurity.isam.base.snmp_monitoring.get(isamAppliance=isam_server))
    # Set the V2 SNMP monitoring
    p(
        ibmsecurity.isam.base.snmp_monitoring.set_v1v2(
            isamAppliance=isam_server, community="IBM"))
    # Commit or Deploy the changes
    p(ibmsecurity.isam.appliance.commit(isamAppliance=isam_server))

    #junction_data=ibmsecurity.isam.web.reverse_proxy.junctions.get(isamAppliance=isam_server,junctionname="/fin_acc",reverseproxy_id="account01")
    junction_data = ibmsecurity.isam.web.reverse_proxy.junctions.export(
        isamAppliance=isam_server,
        junctionname="/fin_acc",
        reverseproxy_id="account01",
def main():
    module = AnsibleModule(argument_spec=dict(log=dict(
        required=False,
        default='INFO',
        choices=['DEBUG', 'INFO', 'ERROR', 'CRITICAL']),
                                              action=dict(required=True),
                                              appliance1=dict(required=True),
                                              lmi_port1=dict(required=False,
                                                             default=443,
                                                             type='int'),
                                              username1=dict(required=False),
                                              password1=dict(required=True,
                                                             no_log=True),
                                              appliance2=dict(required=True),
                                              lmi_port2=dict(required=False,
                                                             default=443,
                                                             type='int'),
                                              username2=dict(required=False),
                                              password2=dict(required=True,
                                                             no_log=True),
                                              isamapi=dict(required=False,
                                                           type='dict')),
                           supports_check_mode=False)

    module.debug('Started isamcompare module')

    # Process all Arguments
    logLevel = module.params['log']
    action = module.params['action']
    appliance1 = module.params['appliance1']
    lmi_port1 = module.params['lmi_port1']
    username1 = module.params['username1']
    password1 = module.params['password1']
    appliance2 = module.params['appliance2']
    lmi_port2 = module.params['lmi_port2']
    username2 = module.params['username2']
    password2 = module.params['password2']

    # Setup logging for format, set log level and redirect to string
    strlog = StringIO()
    DEFAULT_LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format':
                '[%(asctime)s] [PID:%(process)d TID:%(thread)d] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] %(message)s'
            },
        },
        'handlers': {
            'default': {
                'level': logLevel,
                'formatter': 'standard',
                'class': 'logging.StreamHandler',
                'stream': strlog
            },
        },
        'loggers': {
            '': {
                'handlers': ['default'],
                'level': logLevel,
                'propagate': True
            },
            'requests.packages.urllib3.connectionpool': {
                'handlers': ['default'],
                'level': 'ERROR',
                'propagate': True
            }
        }
    }
    logging.config.dictConfig(DEFAULT_LOGGING)

    # Create appliance object to be used for all calls
    if username1 == '' or username1 is None:
        u1 = ApplianceUser(password=password1)
    else:
        u1 = ApplianceUser(username=username1, password=password1)
    isam_server1 = ISAMAppliance(hostname=appliance1,
                                 user=u1,
                                 lmi_port=lmi_port1)
    if username2 == '' or username2 is None:
        u2 = ApplianceUser(password=password2)
    else:
        u2 = ApplianceUser(username=username2, password=password2)
    isam_server2 = ISAMAppliance(hostname=appliance2,
                                 user=u2,
                                 lmi_port=lmi_port2)

    # Create options string to pass to action method
    options = 'isamAppliance1=isam_server1, isamAppliance2=isam_server2'
    if isinstance(module.params['isamapi'], dict):
        for key, value in module.params['isamapi'].items():
            if isinstance(value, basestring):
                options = options + ', ' + key + '="' + value + '"'
            else:
                options = options + ', ' + key + '=' + str(value)
    module.debug('Option to be passed to action: ' + options)

    # Dynamically process the module to be compared
    # Simple check to restrict calls to just "isam" ones for safety
    if action.startswith('ibmsecurity.isam.'):
        try:
            mod = importlib.import_module(action)
            method_name = 'compare'  # Standard function to be implemented in every module
            func_ptr = getattr(
                mod,
                method_name)  # Convert 'compare' to actual function pointer
            func_call = 'func_ptr(' + options + ')'

            startd = datetime.datetime.now()

            # Execute compare for given action
            ret_obj = eval(func_call)

            endd = datetime.datetime.now()
            delta = endd - startd

            ret_obj['stdout'] = strlog.getvalue()
            ret_obj['stdout_lines'] = strlog.getvalue().split()
            ret_obj['start'] = str(startd)
            ret_obj['end'] = str(endd)
            ret_obj['delta'] = str(delta)
            ret_obj['cmd'] = action + ".compare(" + options + ")"
            srv_facts = {}
            srv_facts['server1'] = isam_server1.facts
            srv_facts['server2'] = isam_server2.facts
            ret_obj['ansible_facts'] = srv_facts

            module.exit_json(**ret_obj)

        except ImportError:
            module.fail_json(
                name=action,
                msg='Error> action belongs to a module that is not found!',
                log=strlog.getvalue())
        except AttributeError:
            module.fail_json(
                name=action,
                msg=
                'Error> invalid action was specified, method not found in module!',
                log=strlog.getvalue())
        except TypeError:
            module.fail_json(
                name=action,
                msg=
                'Error> action does not have the right set of arguments or there is a code bug! Options: '
                + options,
                log=strlog.getvalue())
        except IBMError as e:
            module.fail_json(name=action, msg=str(e), log=strlog.getvalue())
    else:
        module.fail_json(
            name=action,
            msg='Error> invalid action specified, needs to be isam!',
            log=strlog.getvalue())
Exemple #5
0
            'handlers': ['default'],
            'propagate': True
        }
    }
}
logging.config.dictConfig(DEFAULT_LOGGING)

def p(jdata):
    pp = pprint.PrettyPrinter(indent=2)
    pp.pprint(jdata)
    print(yaml.safe_dump(jdata, encoding='utf-8', allow_unicode=True))

ip=raw_input("Please enter the IP address or hostname of the ISAM appliance:")
pwd=raw_input("Please enter the password for the ISAM appliance user:"******"admin@local", password=pwd)
isam9_server3 = ISAMAppliance(ip, u)

################ PRODUCT ACTIVATION ################
# print isam.base.activation.set(isam9_server2, code="9A08-84CC-599A-5CC2-C4D9-ACD3-AD70-B4D6", id="federation")

################ LMI APPLIANCE PASSWORD CHANGE ################
#p(ibmsecurity.isam.base.admin.get(isamAppliance=isam9_server3))
#newpwd=raw_input("Please enter the new password for the ISAM appliance user:"******"9.55.253.49")

################ CHANGING HOST RECORDS ################
#print ibmsecurity.isam.base.host_records.get(isam9_server3)
Exemple #6
0
def main():
    module = AnsibleModule(argument_spec=dict(
        log=dict(default='INFO',
                 choices=['DEBUG', 'INFO', 'ERROR', 'CRITICAL']),
        appliance=dict(required=True),
        lmi_port=dict(required=False, default=443, type='int'),
        username=dict(required=False),
        password=dict(required=True, no_log=True),
        isamuser=dict(required=False),
        isampwd=dict(required=True, no_log=True),
        isamdomain=dict(required=False, default='Default'),
        commands=dict(required=True, type='list'),
        adminProxyProtocol=dict(required=False,
                                default='https',
                                choices=['http', 'https']),
        adminProxyHostname=dict(required=False),
        adminProxyPort=dict(required=False, default=443, type='int'),
        adminProxyApplianceShortName=dict(required=False,
                                          default=False,
                                          type='bool'),
        omitAdminProxy=dict(required=False, default=False, type='bool')),
                           supports_check_mode=False)

    module.debug('Started isamadmin module')

    # Process all Arguments
    logLevel = module.params['log']
    appliance = module.params['appliance']
    lmi_port = module.params['lmi_port']
    username = module.params['username']
    password = module.params['password']
    isamuser = module.params['isamuser']
    isampwd = module.params['isampwd']
    isamdomain = module.params['isamdomain']
    commands = module.params['commands']
    adminProxyProtocol = module.params['adminProxyProtocol']
    adminProxyHostname = module.params['adminProxyHostname']
    adminProxyPort = module.params['adminProxyPort']
    adminProxyApplianceShortName = module.params[
        'adminProxyApplianceShortName']
    omitAdminProxy = module.params['omitAdminProxy']

    # Setup logging for format, set log level and redirect to string
    strlog = StringIO()
    DEFAULT_LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format':
                '[%(asctime)s] [PID:%(process)d TID:%(thread)d] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] %(message)s'
            },
        },
        'handlers': {
            'default': {
                'level': logLevel,
                'formatter': 'standard',
                'class': 'logging.StreamHandler',
                'stream': strlog
            },
        },
        'loggers': {
            '': {
                'handlers': ['default'],
                'level': logLevel,
                'propagate': True
            },
            'requests.packages.urllib3.connectionpool': {
                'handlers': ['default'],
                'level': 'ERROR',
                'propagate': True
            }
        }
    }
    logging.config.dictConfig(DEFAULT_LOGGING)

    # Create appliance object to be used for all calls
    if username == '' or username is None:
        u = ApplianceUser(password=password)
    else:
        u = ApplianceUser(username=username, password=password)

    # Create appliance object to be used for all calls
    # if adminProxy hostname is set, use the ISAMApplianceAdminProxy
    if adminProxyHostname == '' or adminProxyHostname is None or omitAdminProxy:
        isam_server = ISAMAppliance(hostname=appliance,
                                    user=u,
                                    lmi_port=lmi_port)
    else:
        isam_server = ISAMApplianceAdminProxy(
            adminProxyHostname=adminProxyHostname,
            user=u,
            hostname=appliance,
            adminProxyProtocol=adminProxyProtocol,
            adminProxyPort=adminProxyPort,
            adminProxyApplianceShortName=adminProxyApplianceShortName)

    if isamuser == '' or isamuser is None:
        iu = ISAMUser(password=isampwd)
    else:
        iu = ISAMUser(username=isamuser, password=isampwd)

    try:
        import ibmsecurity.isam.web.runtime.pdadmin

        startd = datetime.datetime.now()

        ret_obj = ibmsecurity.isam.web.runtime.pdadmin.execute(
            isamAppliance=isam_server,
            isamUser=iu,
            admin_domain=isamdomain,
            commands=commands)

        endd = datetime.datetime.now()
        delta = endd - startd

        ret_obj['stdout'] = strlog.getvalue()
        ret_obj['stdout_lines'] = strlog.getvalue().split()
        ret_obj['start'] = str(startd)
        ret_obj['end'] = str(endd)
        ret_obj['delta'] = str(delta)
        ret_obj[
            'cmd'] = "ibmsecurity.isam.config_fed_dir.runtime.pdadmin.execute(isamAppliance=isam_server, isamUser=iu, commands=" + str(
                commands) + ")"
        ret_obj['ansible_facts'] = isam_server.facts

        module.exit_json(**ret_obj)

    except ImportError:
        module.fail_json(name='pdadmin',
                         msg='Error> Unable to import pdadmin module!',
                         log=strlog.getvalue())
    except AttributeError:
        module.fail_json(
            name='pdadmin',
            msg='Error> Error finding execute function of pdadmin module',
            log=strlog.getvalue())
    except TypeError:
        module.fail_json(
            name='pdadmin',
            msg=
            'Error> pdadmin has wrong set of arguments or there is a bug in code!',
            log=strlog.getvalue())
    except IBMError as e:
        module.fail_json(name='pdadmin', msg=str(e), log=strlog.getvalue())