def main(cls, argv): """ Sets up API and LDAP connection for the tool, then runs the rest of the plumbing. """ # Check if the IPA server is configured before attempting to migrate try: installutils.check_server_configuration() except RuntimeError as e: sys.exit(e) # Finalize API api.bootstrap(in_server=True, context='server') api.finalize() # Setup LDAP connection try: api.Backend.ldap2.connect() cls.ldap = api.Backend.ldap2 except gssapi.exceptions.GSSError as e: sys.exit("Must have Kerberos credentials to migrate Winsync users. Error: %s" % e) except errors.ACIError as e: sys.exit("Outdated Kerberos credentials. Use kdestroy and kinit to update your ticket.") except errors.DatabaseError as e: sys.exit("Cannot connect to the LDAP database. Please check if IPA is running.") super(WinsyncMigrate, cls).main(argv)
def get_api_env(): # get api.env if not api.isdone("bootstrap"): # Workaround for FreeIPA 4.4, use host keytab to fetch LDAP # schema cache. os.environ["KRB5CCNAME"] = "/tmp/krb5cc_workaround" os.environ["KRB5_CLIENT_KTNAME"] = "/etc/krb5.keytab" try: api.bootstrap(context="cli") api.finalize() finally: os.environ.pop("KRB5_CLIENT_KTNAME") subprocess.Popen(["kdestroy", "-q"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() os.environ.pop("KRB5CCNAME") result = {} for name in dir(api.env): if name.startswith("_"): continue value = getattr(api.env, name) if isinstance(value, (str, text, bool, int)): result[name] = value elif isinstance(value, DN): result[name] = str(value) return result
def create_application(): api.bootstrap(context="server", confdir=paths.ETC_IPA, log=None) try: api.finalize() except Exception as e: logger.error("Failed to start IPA: %s", e) raise # speed up first request to each worker by 200ms populate_schema_cache() # collect garbage and freeze all objects that are currently tracked by # cyclic garbage collector. We assume that vast majority of currently # loaded objects won't be removed in requests. This speeds up GC # collections and improve CoW memory handling. gc.collect() if hasattr(gc, "freeze"): # Python 3.7+ gc.freeze() # This is the WSGI callable: def application(environ, start_response): if not environ["wsgi.multithread"]: return api.Backend.wsgi_dispatch(environ, start_response) else: logger.error("IPA does not work with the threaded MPM, " "use the pre-fork MPM") raise RuntimeError("threaded MPM detected") return application
def run(self): api.bootstrap(in_server=True, confdir=paths.ETC_IPA) api.finalize() try: api.Backend.ldap2.connect(ccache=os.environ.get('KRB5CCNAME'), autobind=AUTOBIND_DISABLED) except (gssapi.exceptions.GSSError, errors.ACIError): raise admintool.ScriptError( "Unable to connect to LDAP! Did you kinit?") try: # Parse tokens for keypkg in self.doc.getKeyPackages(): try: api.Command.otptoken_add(keypkg.id, no_qrcode=True, **keypkg.options) except Exception as e: logger.warning("Error adding token: %s", e) else: logger.info("Added token: %s", keypkg.id) keypkg.remove() finally: api.Backend.ldap2.disconnect() # Write out the XML file without the tokens that succeeded. self.doc.save(self.output)
def init_api(self, **overrides): overrides.setdefault('confdir', paths.ETC_IPA) api.bootstrap(in_server=True, context='restore', **overrides) api.finalize() self.instances = [installutils.realm_to_serverid(api.env.realm)] self.backends = ['userRoot', 'ipaca']
def use_api_as_principal(principal, keytab): with ipautil.private_ccache() as ccache_file: try: old_principal = getattr(context, "principal", None) name = gssapi.Name(principal, gssapi.NameType.kerberos_principal) store = {"ccache": ccache_file, "client_keytab": keytab} gssapi.Credentials(name=name, usage="initiate", store=store) # Finalize API when TGT obtained using host keytab exists if not api.isdone("finalize"): api.finalize() # Now we have a TGT, connect to IPA try: if api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.disconnect() api.Backend.rpcclient.connect() yield except gssapi.exceptions.GSSError as e: raise Exception( "Unable to bind to IPA server. Error initializing " "principal %s in %s: %s" % (principal, keytab, str(e))) finally: if api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.disconnect() setattr(context, "principal", old_principal)
def get_api_env(): # get api.env if not api.isdone('bootstrap'): # Workaround for FreeIPA 4.4, use host keytab to fetch LDAP # schema cache. os.environ['KRB5CCNAME'] = '/tmp/krb5cc_workaround' os.environ['KRB5_CLIENT_KTNAME'] = '/etc/krb5.keytab' try: api.bootstrap(context='cli') api.finalize() finally: os.environ.pop('KRB5_CLIENT_KTNAME') subprocess.Popen(['kdestroy', '-q'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() os.environ.pop('KRB5CCNAME') result = {} for name in dir(api.env): if name.startswith('_'): continue value = getattr(api.env, name) if isinstance(value, (str, text, bool, int)): result[name] = value elif isinstance(value, DN): result[name] = str(value) return result
def run(self): check_client_configuration() old_krb5ccname = os.environ.get('KRB5CCNAME') os.environ['KRB5_CLIENT_KTNAME'] = '/etc/krb5.keytab' os.environ['KRB5CCNAME'] = "MEMORY:" try: api.bootstrap(context='cli_installer', confdir=paths.ETC_IPA) api.finalize() api.Backend.rpcclient.connect() run_with_args(api) api.Backend.rpcclient.disconnect() except errors.CCacheError: logger.error( "Unable to obtain credentials for %s from /etc/krb5.keytab", FQDN ) raise finally: if old_krb5ccname is None: del os.environ['KRB5CCNAME'] else: os.environ['KRB5CCNAME'] = old_krb5ccname
def run(self): api.bootstrap(in_server=True) api.finalize() conn = ldap2(api) try: ccache = krbV.default_context().default_ccache() conn.connect(ccache=ccache) except (krbV.Krb5Error, errors.ACIError): raise admintool.ScriptError("Unable to connect to LDAP! Did you kinit?") try: # Parse tokens for keypkg in self.doc.getKeyPackages(): try: api.Command.otptoken_add(keypkg.id, no_qrcode=True, **keypkg.options) except Exception as e: self.log.warn("Error adding token: %s", e) else: self.log.info("Added token: %s", keypkg.id) keypkg.remove() finally: conn.disconnect() # Write out the XML file without the tokens that succeeded. self.doc.save(self.output)
def run(self): api.bootstrap(in_server=True) api.finalize() conn = ldap2() try: ccache = krbV.default_context().default_ccache() conn.connect(ccache=ccache) except (krbV.Krb5Error, errors.ACIError): raise admintool.ScriptError( "Unable to connect to LDAP! Did you kinit?") try: # Parse tokens for keypkg in self.doc.getKeyPackages(): try: api.Command.otptoken_add(keypkg.id, no_qrcode=True, **keypkg.options) except Exception as e: self.log.warn("Error adding token: %s", e) else: self.log.info("Added token: %s", keypkg.id) keypkg.remove() finally: conn.disconnect() # Write out the XML file without the tokens that succeeded. self.doc.save(self.output)
def run(self): api.bootstrap(in_server=True, confdir=paths.ETC_IPA) api.finalize() try: api.Backend.ldap2.connect(ccache=os.environ.get('KRB5CCNAME'), autobind=AUTOBIND_DISABLED) except (gssapi.exceptions.GSSError, errors.ACIError): raise admintool.ScriptError("Unable to connect to LDAP! Did you kinit?") try: # Parse tokens for keypkg in self.doc.getKeyPackages(): try: api.Command.otptoken_add(keypkg.id, no_qrcode=True, **keypkg.options) except Exception as e: logger.warning("Error adding token: %s", e) else: logger.info("Added token: %s", keypkg.id) keypkg.remove() finally: api.Backend.ldap2.disconnect() # Write out the XML file without the tokens that succeeded. self.doc.save(self.output)
def run(api): error = None try: (_options, argv) = api.bootstrap_with_global_options(context='cli') try: check_client_configuration() except ScriptError as e: sys.exit(e) for klass in cli_plugins: api.add_plugin(klass) api.finalize() if not 'config_loaded' in api.env and not 'help' in argv: raise NotConfiguredError() sys.exit(api.Backend.cli.run(argv)) except KeyboardInterrupt: print('') logger.info('operation aborted') except PublicError as e: error = e except Exception as e: logger.exception('%s: %s', e.__class__.__name__, str(e)) error = InternalError() if error is not None: assert isinstance(error, PublicError) logger.error(error.strerror) sys.exit(error.rval)
def example(): # 1. Initialize ipalib # # Run ./python-api.py --help to see the global options. Some useful # options: # # -v Produce more verbose output # -d Produce full debugging output # -e in_server=True Force running in server mode # -e xmlrpc_uri=https://foo.com/ipa/xml # Connect to a specific server api.bootstrap_with_global_options(context='example') api.finalize() # You will need to create a connection. If you're in_server, call # Backend.ldap.connect(), otherwise Backend.rpcclient.connect(). if api.env.in_server: api.Backend.ldap2.connect() else: api.Backend.rpcclient.connect() # Now that you're connected, you can make calls to api.Command.whatever(): print('The admin user:'******'admin'))
def initialize(self, framework, config, options=None): super().initialize(framework, config) installutils.check_server_configuration() if not api.isdone('bootstrap'): api.bootstrap(in_server=True, context='ipahealthcheck', log=None) if not api.isdone('finalize'): api.finalize()
def api_connect(context=None): """ Initialize IPA API with the provided context. `context` can be any of: * `server` (default) * `ansible-freeipa` * `cli_installer` """ env = Env() env._bootstrap() env._finalize_core(**dict(DEFAULT_CONFIG)) # available contexts are 'server', 'ansible-freeipa' and 'cli_installer' if context is None: context = 'server' api.bootstrap(context=context, debug=env.debug, log=None) api.finalize() if api.env.in_server: backend = api.Backend.ldap2 else: backend = api.Backend.rpcclient if not backend.isconnected(): backend.connect(ccache=os.environ.get('KRB5CCNAME', None))
def pytest_cmdline_main(config): kwargs = dict( context=u'cli', in_server=False, fallback=False ) # FIXME: workaround for https://pagure.io/freeipa/issue/8317 kwargs.update(in_tree=True) if not os.path.isfile(os.path.expanduser('~/.ipa/default.conf')): # dummy domain/host for machines without ~/.ipa/default.conf kwargs.update(domain=u'ipa.test', server=u'master.ipa.test') api.bootstrap(**kwargs) for klass in cli_plugins: api.add_plugin(klass) # XXX workaround until https://fedorahosted.org/freeipa/ticket/6408 has # been resolved. if os.path.isfile(api.env.conf_default): api.finalize() if config.option.verbose: print('api.env: ') pprint.pprint({k: api.env[k] for k in api.env}) print("uname: {}".format(os.uname())) print("euid: {}, egid: {}".format(os.geteuid(), os.getegid())) print("working dir: {}".format(os.path.abspath(os.getcwd()))) print('sys.version: {}'.format(sys.version))
def validate_options(self, needs_root=True): super(KRAInstall, self).validate_options(needs_root=True) installutils.check_server_configuration() api.bootstrap(in_server=True, confdir=paths.ETC_IPA) api.finalize()
def __init__(self, context, ldap_pass): ipa_api.bootstrap_with_global_options(context=context) ipa_api.finalize() ipa_api.Backend.xmlclient.connect() self.ldap_pass = ldap_pass self.ldapmod = LDAPMOD + [ldap_pass, ]
def initialize(): ''' This function initializes the FreeIPA/IPA API. This function requires no arguments. A kerberos key must be present in the users keyring in order for this to work. IPA default configuration directory is /etc/ipa, this path could be overridden with IPA_CONFDIR environment variable. ''' api.bootstrap(context='cli') if not os.path.isdir(api.env.confdir): print("WARNING: IPA configuration directory (%s) is missing. " "Environment variable IPA_CONFDIR could be used to override " "default path." % api.env.confdir) if LooseVersion(IPA_VERSION) >= LooseVersion('4.6.2'): # With ipalib < 4.6.0 'server' and 'domain' have default values # ('localhost:8888', 'example.com'), newer versions don't and # DNS autodiscovery is broken, then one of jsonrpc_uri / xmlrpc_uri is # required. # ipalib 4.6.0 is unusable (https://pagure.io/freeipa/issue/7132) # that's why 4.6.2 is explicitely tested. if 'server' not in api.env or 'domain' not in api.env: sys.exit("ERROR: ('jsonrpc_uri' or 'xmlrpc_uri') or 'domain' are not " "defined in '[global]' section of '%s' nor in '%s'." % (api.env.conf, api.env.conf_default)) api.finalize() try: api.Backend.rpcclient.connect() except AttributeError: # FreeIPA < 4.0 compatibility api.Backend.xmlclient.connect() return api
def main(cls, argv): """ Sets up API and LDAP connection for the tool, then runs the rest of the plumbing. """ # Check if the IPA server is configured before attempting to migrate try: installutils.check_server_configuration() except RuntimeError as e: sys.exit(e) # Finalize API api.bootstrap(in_server=True, context='server', confdir=paths.ETC_IPA) api.finalize() # Setup LDAP connection try: api.Backend.ldap2.connect() cls.ldap = api.Backend.ldap2 except gssapi.exceptions.GSSError as e: sys.exit( "Must have Kerberos credentials to migrate Winsync users. Error: %s" % e) except errors.ACIError as e: sys.exit( "Outdated Kerberos credentials. Use kdestroy and kinit to update your ticket." ) except errors.DatabaseError as e: sys.exit( "Cannot connect to the LDAP database. Please check if IPA is running." ) super(WinsyncMigrate, cls).main(argv)
def run(self): if not is_ipa_configured(): print("IPA is not configured.") return 2 if not cainstance.is_ca_installed_locally(): print("CA is not installed on this server.") return 3 api.bootstrap(in_server=True, confdir=paths.ETC_IPA) api.finalize() api.Backend.ldap2.connect() state = acme_state(api) with state as ca_api: if self.command == Command.ENABLE: self.check_san_status() ca_api.enable() elif self.command == Command.DISABLE: ca_api.disable() elif self.command == Command.STATUS: status = "enabled" if dogtag.acme_status() else "disabled" print("ACME is {}".format(status)) return 0 else: raise RuntimeError('programmer error: unhandled enum case') return 0
def run(self): check_client_configuration() api.bootstrap(context='cli_installer', confdir=paths.ETC_IPA) api.finalize() server = urlsplit(api.env.jsonrpc_uri).hostname ldap_uri = ipaldap.get_ldap_uri(server) ldap = ipaldap.LDAPClient(ldap_uri) tmpdir = tempfile.mkdtemp(prefix="tmp-") ccache_name = os.path.join(tmpdir, 'ccache') try: principal = str('host/%s@%s' % (api.env.host, api.env.realm)) kinit_keytab(principal, paths.KRB5_KEYTAB, ccache_name) os.environ['KRB5CCNAME'] = ccache_name api.Backend.rpcclient.connect() try: result = api.Backend.rpcclient.forward( 'ca_is_enabled', version=u'2.107', ) ca_enabled = result['result'] except (errors.CommandError, errors.NetworkError): result = api.Backend.rpcclient.forward( 'env', server=True, version=u'2.0', ) ca_enabled = result['result']['enable_ra'] ldap.gssapi_bind() certs = certstore.get_ca_certs(ldap, api.env.basedn, api.env.realm, ca_enabled) if ca_enabled: lwcas = api.Command.ca_find()['result'] else: lwcas = [] api.Backend.rpcclient.disconnect() finally: shutil.rmtree(tmpdir) server_fstore = sysrestore.FileStore(paths.SYSRESTORE) if server_fstore.has_files(): self.update_server(certs) try: # pylint: disable=import-error,ipa-forbidden-import from ipaserver.install import cainstance # pylint: enable=import-error,ipa-forbidden-import cainstance.add_lightweight_ca_tracking_requests(lwcas) except Exception: logger.exception( "Failed to add lightweight CA tracking requests") self.update_client(certs)
def __init__(self): if self.__kerberos_has_ticket() is False: self.__kerberos_init() if api.isdone('finalize') is False: api.bootstrap_with_global_options(context='api') api.finalize() api.Backend.rpcclient.connect() self.redis = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB, password=settings.REDIS_PASSWORD)
def init_api(self, **overrides): api.bootstrap(in_server=False, context='restore', **overrides) api.finalize() self.instances = [ installutils.realm_to_serverid(api.env.realm), 'PKI-IPA' ] self.backends = ['userRoot', 'ipaca']
def run(self): super(LDAPUpdater, self).run() api.bootstrap( in_server=True, context='updates', debug=self.options.debug, ) api.finalize()
def run(self): fstore = sysrestore.FileStore(paths.IPA_CLIENT_SYSRESTORE) if (not fstore.has_files() and not os.path.exists(paths.IPA_DEFAULT_CONF)): raise admintool.ScriptError( "IPA client is not configured on this system.") api.bootstrap(context='cli_installer') api.finalize() server = urlsplit(api.env.jsonrpc_uri).hostname ldap = ipaldap.IPAdmin(server) tmpdir = tempfile.mkdtemp(prefix="tmp-") ccache_name = os.path.join(tmpdir, 'ccache') try: principal = str('host/%s@%s' % (api.env.host, api.env.realm)) ipautil.kinit_keytab(principal, paths.KRB5_KEYTAB, ccache_name) os.environ['KRB5CCNAME'] = ccache_name api.Backend.rpcclient.connect() try: result = api.Backend.rpcclient.forward( 'ca_is_enabled', version=u'2.107', ) ca_enabled = result['result'] except (errors.CommandError, errors.NetworkError): result = api.Backend.rpcclient.forward( 'env', server=True, version=u'2.0', ) ca_enabled = result['result']['enable_ra'] ldap.do_sasl_gssapi_bind() certs = certstore.get_ca_certs(ldap, api.env.basedn, api.env.realm, ca_enabled) # find lightweight CAs (on renewal master only) lwcas = [] for ca_obj in api.Command.ca_find()['result']: if IPA_CA_CN not in ca_obj['cn']: lwcas.append(ca_obj) api.Backend.rpcclient.disconnect() finally: shutil.rmtree(tmpdir) server_fstore = sysrestore.FileStore(paths.SYSRESTORE) if server_fstore.has_files(): self.update_server(certs) for entry in lwcas: self.server_track_lightweight_ca(entry) self.update_client(certs)
def __init__(self, config, username, gateway_hostgroup): super(IPA, self).__init__(username, gateway_hostgroup) api.bootstrap(context='cli') api.finalize() try: api.Backend.rpcclient.connect() except AttributeError: api.Backend.xmlclient.connect() #FreeIPA < 4.0 compatibility self.api = api
def run(self): check_client_configuration() api.bootstrap(context='cli_installer', confdir=paths.ETC_IPA) api.finalize() api.Backend.rpcclient.connect() run_with_args(api) api.Backend.rpcclient.disconnect()
def run(self): super(ServerUpgrade, self).run() api.bootstrap(in_server=True, context='updates') api.finalize() options = self.options if not options.skip_version_check: # check IPA version and data version try: installutils.check_version() except (installutils.UpgradePlatformError, installutils.UpgradeDataNewerVersionError) as e: raise admintool.ScriptError( 'Unable to execute IPA upgrade: %s' % e, 1) except installutils.UpgradeMissingVersionError as e: self.log.info("Missing version: %s", e) except installutils.UpgradeVersionError: # Ignore other errors pass else: self.log.info("Skipping version check") self.log.warning("Upgrade without version check may break your " "system") realm = krbV.default_context().default_realm schema_files = [os.path.join(ipautil.SHARE_DIR, f) for f in dsinstance.ALL_SCHEMA_FILES] data_upgrade = IPAUpgrade(realm, schema_files=schema_files) try: data_upgrade.create_instance() except BadSyntax: raise admintool.ScriptError( 'Bad syntax detected in upgrade file(s).', 1) except RuntimeError: raise admintool.ScriptError('IPA upgrade failed.', 1) else: if data_upgrade.modified: self.log.info('Update complete') else: self.log.info('Update complete, no data were modified') # store new data version after upgrade installutils.store_version() # FIXME: remove this when new installer will be ready # execute upgrade of configuration cmd = ['ipa-upgradeconfig', ] if options.verbose: cmd.append('--debug') if options.quiet: cmd.append('--quiet') self.log.info('Executing ipa-upgradeconfig, please wait') ipautil.run(cmd)
def main(): """ Main routine for the ansible module. """ module = AnsibleModule( argument_spec=dict( principal = dict(default='admin'), ccache = dict(required=False, type='path'), fqdn = dict(required=True), certificates = dict(required=False, type='list'), sshpubkey= dict(required=False), ipaddress = dict(required=False), random = dict(default=False, type='bool'), state = dict(default='present', choices=[ 'present', 'absent' ]), ansible_python_interpreter = dict(required=False), ), supports_check_mode=True, ) principal = module.params.get('principal', 'admin') ccache = module.params.get('ccache') fqdn = unicode(module.params.get('fqdn')) state = module.params.get('state') try: os.environ['KRB5CCNAME']=ccache cfg = dict( context='ansible_module', confdir=paths.ETC_IPA, in_server=False, debug=False, verbose=0, ) api.bootstrap(**cfg) api.finalize() api.Backend.rpcclient.connect() changed = False try: result = api.Command.host_show(fqdn, all=True) host = result['result'] except errors.NotFound: host = None if state == 'present' or state == 'disabled': changed = ensure_host_present(module, api, host) elif state == 'absent': changed = ensure_host_absent(module, api, host) except Exception as e: module.fail_json(msg="ipaclient_get_otp module failed : %s" % str(e)) finally: run([paths.KDESTROY], raiseonerr=False, env=os.environ) module.exit_json(changed=changed, host=host)
def api_connect(): """Initialize and connect to FreeIPA's RPC server. """ # delay initialization of API for pre-forking web servers if not api.isdone("bootstrap"): api.bootstrap(context="cli") api.finalize() if not api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.connect()
def api_connect(): """Initialize and connect to FreeIPA's RPC server. """ # delay initialization of API for pre-forking web servers if not api.isdone('bootstrap'): api.bootstrap(context='cli') api.finalize() if not api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.connect()
def api_bootstrap_finalize(env): # pylint: disable=no-member xmlrpc_uri = 'https://{}/ipa/xml'.format(ipautil.format_netloc(env.host)) api.bootstrap(in_server=True, context='installer', confdir=paths.ETC_IPA, ldap_uri=installutils.realm_to_ldapi_uri(env.realm), xmlrpc_uri=xmlrpc_uri) # pylint: enable=no-member api.finalize()
def run(self): super(ServerUpgrade, self).run() api.bootstrap(in_server=True, context='updates') api.finalize() options = self.options if not options.skip_version_check: # check IPA version and data version try: installutils.check_version() except (installutils.UpgradePlatformError, installutils.UpgradeDataNewerVersionError) as e: raise admintool.ScriptError( 'Unable to execute IPA upgrade: %s' % e, 1) except installutils.UpgradeMissingVersionError as e: self.log.info("Missing version: %s", e) except installutils.UpgradeVersionError: # Ignore other errors pass else: self.log.info("Skipping version check") self.log.warning("Upgrade without version check may break your " "system") realm = krbV.default_context().default_realm data_upgrade = IPAUpgrade(realm) data_upgrade.create_instance() if data_upgrade.badsyntax: raise admintool.ScriptError( 'Bad syntax detected in upgrade file(s).', 1) elif data_upgrade.upgradefailed: raise admintool.ScriptError('IPA upgrade failed.', 1) elif data_upgrade.modified: self.log.info('Data update complete') else: self.log.info('Data update complete, no data were modified') # store new data version after upgrade installutils.store_version() # FIXME: remove this when new installer will be ready # execute upgrade of configuration cmd = [ 'ipa-upgradeconfig', ] if options.verbose: cmd.append('--debug') if options.quiet: cmd.append('--quiet') self.log.info('Executing ipa-upgradeconfig, please wait') ipautil.run(cmd)
def api_connect(): """ Create environment, initialize api and connect to ldap2 """ env = Env() env._bootstrap() env._finalize_core(**dict(DEFAULT_CONFIG)) api.bootstrap(context='server', debug=env.debug, log=None) api.finalize() api.Backend.ldap2.connect()
def run(self): super(ServerUpgrade, self).run() api.bootstrap(in_server=True, context='updates', confdir=paths.ETC_IPA) api.finalize() try: server.upgrade_check(self.options) server.upgrade() except RuntimeError as e: raise admintool.ScriptError(str(e))
def __init__(self, config, username, gateway_hostgroup): super(IPA, self).__init__(username, gateway_hostgroup) logging.info("IPA: loaded") api.bootstrap(context='cli') api.finalize() try: api.Backend.rpcclient.connect() except AttributeError: api.Backend.xmlclient.connect() # FreeIPA < 4.0 compatibility self.api = api self.default_ssh_port = config.ssh_port
def run(self): api.bootstrap(in_server=True) api.finalize() self.pkcs12_fname = self.args[0] if self.options.dirsrv: self.install_dirsrv_cert() if self.options.http: self.install_http_cert()
def initialize(): ''' This function initializes the FreeIPA/IPA API. This function requires no arguments. A kerberos key must be present in the users keyring in order for this to work. ''' api.bootstrap(context='cli') api.finalize() api.Backend.rpcclient.connect() return api
def validate_options(self): options = self.options super(ReplicaPrepare, self).validate_options(needs_root=True) installutils.check_server_configuration() if not options.ip_address: if options.reverse_zone: self.option_parser.error("You cannot specify a --reverse-zone " "option without the --ip-address option") if options.no_reverse: self.option_parser.error("You cannot specify a --no-reverse " "option without the --ip-address option") elif options.reverse_zone and options.no_reverse: self.option_parser.error("You cannot specify a --reverse-zone " "option together with --no-reverse") #Automatically disable pkinit w/ dogtag until that is supported options.setup_pkinit = False # If any of the PKCS#12 options are selected, all are required. pkcs12_req = (options.dirsrv_pkcs12, options.http_pkcs12) pkcs12_opt = (options.pkinit_pkcs12,) if any(pkcs12_req + pkcs12_opt) and not all(pkcs12_req): self.option_parser.error( "--dirsrv_pkcs12 and --http_pkcs12 are required if any " "PKCS#12 options are used.") if len(self.args) < 1: self.option_parser.error( "must provide the fully-qualified name of the replica") elif len(self.args) > 1: self.option_parser.error( "must provide exactly one name for the replica") else: [self.replica_fqdn] = self.args api.bootstrap(in_server=True) api.finalize() if api.env.host == self.replica_fqdn: raise admintool.ScriptError("You can't create a replica on itself") if not api.env.enable_ra and not options.http_pkcs12: raise admintool.ScriptError( "Cannot issue certificates: a CA is not installed. Use the " "--http_pkcs12, --dirsrv_pkcs12 options to provide custom " "certificates.") config_dir = dsinstance.config_dirname( dsinstance.realm_to_serverid(api.env.realm)) if not ipautil.dir_exists(config_dir): raise admintool.ScriptError( "could not find directory instance: %s" % config_dir)
def __init__(self): try: self.ntries = CONF.connect_retries except cfg.NoSuchOptError: self.ntries = 1 if not ipalib_imported: return self.ccache = "MEMORY:" + str(uuid.uuid4()) os.environ['KRB5CCNAME'] = self.ccache if self._ipa_client_configured() and not api.isdone('finalize'): api.bootstrap(context='novajoin') api.finalize()
def run(self): super(ServerUpgrade, self).run() api.bootstrap(in_server=True, context='updates') import ipaserver.plugins.dogtag # ensure profile backend gets loaded api.finalize() try: server.upgrade_check(self.options) server.upgrade() except RuntimeError as e: raise admintool.ScriptError(str(e))
def run(self): api.bootstrap(in_server=True) api.finalize() api.Backend.ldap2.connect(bind_pw=self.options.dirman_password) if self.options.dirsrv: self.install_dirsrv_cert() if self.options.http: self.install_http_cert() api.Backend.ldap2.disconnect()
def run(self): super(IpaAdvise, self).run() api.bootstrap(in_server=False, context='advise') api.finalize() # With no argument, print the list out and exit if not self.args: self.print_config_list() return else: keyword = self.args[0].replace('-', '_') self.print_advice(keyword)
def validate_options(self, needs_root=True): super(KRAInstall, self).validate_options(needs_root=True) installutils.check_server_configuration() if self.options.unattended and self.options.password is None: self.option_parser.error( "Directory Manager password must be specified using -p" " in unattended mode" ) api.bootstrap(in_server=True) api.finalize()
def validate_options(self): options = self.options super(ReplicaPrepare, self).validate_options(needs_root=True) installutils.check_server_configuration() if not options.ip_addresses: if options.reverse_zones: self.option_parser.error("You cannot specify a --reverse-zone " "option without the --ip-address option") if options.no_reverse: self.option_parser.error("You cannot specify a --no-reverse " "option without the --ip-address option") elif options.reverse_zones and options.no_reverse: self.option_parser.error("You cannot specify a --reverse-zone " "option together with --no-reverse") #Automatically disable pkinit w/ dogtag until that is supported options.setup_pkinit = False # If any of the PKCS#12 options are selected, all are required. cert_file_req = (options.dirsrv_cert_files, options.http_cert_files) cert_file_opt = (options.pkinit_cert_files,) if any(cert_file_req + cert_file_opt) and not all(cert_file_req): self.option_parser.error( "--dirsrv-cert-file and --http-cert-file are required if any " "PKCS#12 options are used.") if len(self.args) < 1: self.option_parser.error( "must provide the fully-qualified name of the replica") elif len(self.args) > 1: self.option_parser.error( "must provide exactly one name for the replica") else: [self.replica_fqdn] = self.args api.bootstrap(in_server=True) api.finalize() # Connect to LDAP, connection is closed at the end of run() api.Backend.ldap2.connect() self.check_for_supported_domain_level() if api.env.host == self.replica_fqdn: raise admintool.ScriptError("You can't create a replica on itself") config_dir = dsinstance.config_dirname( installutils.realm_to_serverid(api.env.realm)) if not ipautil.dir_exists(config_dir): raise admintool.ScriptError( "could not find directory instance: %s" % config_dir)
def run(self): super(ServerUpgrade, self).run() api.bootstrap(in_server=True, context='updates') api.finalize() api.Backend.ldap2.connect() try: server.upgrade_check(self.options) server.upgrade() except RuntimeError as e: raise admintool.ScriptError(str(e)) api.Backend.ldap2.disconnect()
def run(self): command = self.command api.bootstrap(in_server=True, confdir=paths.ETC_IPA) api.finalize() self.ldap_connect() try: if command == 'renew': return self.renew() elif command == 'install': return self.install() finally: api.Backend.ldap2.disconnect()
def run(self): api.bootstrap(in_server=True) api.finalize() conn = api.Backend.ldap2 conn.connect(bind_dn=DN(('cn', 'directory manager')), bind_pw=self.options.dirman_password) if self.options.dirsrv: self.install_dirsrv_cert() if self.options.http: self.install_http_cert() conn.disconnect()
def initialize(): ''' This function initializes the FreeIPA/IPA API. This function requires no arguments. A kerberos key must be present in the users keyring in order for this to work. ''' api.bootstrap(context='cli') api.finalize() try: api.Backend.rpcclient.connect() except AttributeError: #FreeIPA < 4.0 compatibility api.Backend.xmlclient.connect() return api