def __init__(self, screen, test): self.screen = screen self.test = test self.size = snack._snack.size() self.drawFrame() self.alreadyRegistered = 0 try: self.serverType = rhnreg.getServerType() except up2dateErrors.InvalidProtocolError: FatalErrorWindow(screen, _("You specified an invalid protocol." + "Only https and http are allowed.")) self.windows = [ AlreadyRegisteredSubscriptionManagerWindow, AlreadyRegisteredWindow, StartWindow, SatelliteUrlWindow, ConnectWindow, InfoWindow, OSReleaseWindow, HardwareWindow, PackagesWindow, SendWindow, SendingWindow, ReviewWindow, FinishWindow ] self.serverURL = config.getServerlURL()[0] if not cfg['sslCACert']: cfg.set('sslCACert', '/usr/share/rhn/RHN-ORG-TRUSTED-SSL-CERT') self.sslCACert = cfg['sslCACert']
def get_available_channels(user, password): """ return list of available child channels """ modified_servers = [] servers = config.getServerlURL() for server in servers: scheme, netloc, path, query, fragment = urlparse.urlsplit(server) modified_servers.append(urlparse.urlunsplit((scheme, netloc, '/rpc/api', query, fragment))) client = rhnserver.RhnServer(serverOverride=modified_servers) try: key = client.auth.login(user, password) except xmlrpclib.Fault: exc = sys.exc_info()[1] systemExit(1, "Error during client authentication: %s" % exc.faultString) system_id = re.sub('^ID-', '', rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())[0][0]['system_id']) result = [] try: channels = client.system.listChildChannels(key, int(system_id)) except xmlrpclib.Fault: exc = sys.exc_info()[1] systemExit(1, "Error when listing child channels: %s" % exc.faultString) for channel in channels: if 'LABEL' in channel: result.extend([channel['LABEL']]) else: result.extend([channel['label']]) return result
def getChannels(force=None, label_whitelist=None, timeout=None): """ return rhnChannelList containing list of channel we are subscribed to """ cfg = config.initUp2dateConfig() global selected_channels if not selected_channels and not force: selected_channels = rhnChannelList() s = rhnserver.RhnServer(timeout=timeout) if not up2dateAuth.getSystemId(): raise up2dateErrors.NoSystemIdError(_("Unable to Locate SystemId")) up2dateChannels = s.up2date.listChannels(up2dateAuth.getSystemId()) for chan in up2dateChannels: if label_whitelist and not chan['label'] in label_whitelist: continue channel = rhnChannel(type='up2date', url=config.getServerlURL()) for key in chan.keys(): if key == "last_modified": channel['version'] = chan['last_modified'] else: channel[key] = chan[key] selected_channels.addChannel(channel) if len(selected_channels.list) == 0: raise up2dateErrors.NoChannelsError( _("This system may not be updated until it is associated with a channel." )) return selected_channels
def getChannels(force=None, label_whitelist=None, timeout=None): """ return rhnChannelList containing list of channel we are subscribed to """ cfg = config.initUp2dateConfig() global selected_channels if not selected_channels and not force: selected_channels = rhnChannelList() s = rhnserver.RhnServer(timeout=timeout) if not up2dateAuth.getSystemId(): raise up2dateErrors.NoSystemIdError(_("Unable to Locate SystemId")) up2dateChannels = s.up2date.listChannels(up2dateAuth.getSystemId()) for chan in up2dateChannels: if label_whitelist and not chan['label'] in label_whitelist: continue channel = rhnChannel(type = 'up2date', url = config.getServerlURL()) for key in chan.keys(): if key == "last_modified": channel['version'] = chan['last_modified'] else: channel[key] = chan[key] selected_channels.addChannel(channel) if len(selected_channels.list) == 0: raise up2dateErrors.NoChannelsError(_("This system may not be updated until it is associated with a channel.")) return selected_channels
def _init(): cfg = config.initUp2dateConfig() cfg_dict = dict(cfg.items()) server_url = config.getServerlURL() cfg_dict['proto'], cfg_dict['server_name'] = utils.parse_url(server_url[0], scheme="https")[:2] if len(server_url) > 1: cfg_dict['server_list'] = server_url local_config.init('rhncfg-client', defaults=cfg_dict) set_debug_level(int(local_config.get('debug_level') or 0)) set_logfile("/var/log/rhncfg-actions")
def get_available_channels(user, password): """ return list of available child channels """ cfg = config.initUp2dateConfig() satellite_url = config.getServerlURL()[0] scheme, netloc, path, query, fragment = urlparse.urlsplit(satellite_url) satellite_url = urlparse.urlunsplit((scheme, netloc, '/rpc/api', query, fragment)) client = xmlrpclib.Server(satellite_url, verbose=0) try: key = client.auth.login(user, password) except xmlrpclib.Fault, exc: systemExit(1, "Error during client authentication: %s" % exc.faultString)
def get_available_channels(user, password): """ return list of available child channels """ modified_servers = [] servers = config.getServerlURL() for server in servers: scheme, netloc, path, query, fragment = urlparse.urlsplit(server) modified_servers.append(urlparse.urlunsplit((scheme, netloc, '/rpc/api', query, fragment))) client = rhnserver.RhnServer(serverOverride=modified_servers) try: key = client.auth.login(user, password) except xmlrpclib.Fault, exc: systemExit(1, "Error during client authentication: %s" % exc.faultString)
def get_available_channels(user, password): """ return list of available child channels """ cfg = config.initUp2dateConfig() satellite_url = config.getServerlURL()[0] scheme, netloc, path, query, fragment = urlparse.urlsplit(satellite_url) satellite_url = urlparse.urlunsplit( (scheme, netloc, '/rpc/api', query, fragment)) client = xmlrpclib.Server(satellite_url, verbose=0) try: key = client.auth.login(user, password) except xmlrpclib.Fault, exc: systemExit(1, "Error during client authentication: %s" % exc.faultString)
def read_config(self): ret = {} # Read from the global config first config_file = self.options.cfg self._config = osad_config.init('osad', config_file=config_file) config_keys = ['debug_level', 'osa_ssl_cert', 'logfile', 'run_rhn_check', 'rhn_check_command', 'enable_failover'] for key in config_keys: ret[key] = osad_config.get(key) try: server_url = osad_config.get('server_url') except osad_config.InterpolationError, e: server_url = config.getServerlURL()[0]
def get_available_channels(user, password): """ return list of available child channels """ modified_servers = [] servers = config.getServerlURL() for server in servers: scheme, netloc, path, query, fragment = urlparse.urlsplit(server) modified_servers.append( urlparse.urlunsplit((scheme, netloc, '/rpc/api', query, fragment))) client = rhnserver.RhnServer(serverOverride=modified_servers) try: key = client.auth.login(user, password) except xmlrpclib.Fault, exc: systemExit(1, "Error during client authentication: %s" % exc.faultString)
def main(): (options, args, num_args) = verify_command_line() values = {} valuesdel = [] i = 0 if not options.delete_values: while (i < num_args): values[args[i]] = args[i + 1] i = i + 2 else: while (i < num_args): valuesdel.insert(i, args[i]) i = i + 1 url = None if options.url: url = options.url else: url = munge_server_url(config.getServerlURL()[0]) s = create_server_obj(url) sid = get_sys_id() if not sid: system_exit(1, "Could not determine systemid") try: session = s.auth.login(options.username, options.password) if options.list_values: ret = s.system.get_custom_values(session, int(sid)) elif options.delete_values: ret = s.system.delete_custom_values(session, int(sid), valuesdel) else: ret = s.system.set_custom_values(session, int(sid), values) except xmlrpclib.Fault, e: if e.faultCode == -1: system_exit( 1, "Error code: %s\nInvalid login information.\n" % e.faultCode) else: system_exit(1, "Error code: %s\n%s\n" % (e.faultCode, e.faultString))
def main(): (options, args, num_args) = verify_command_line() values = {} valuesdel = [] i = 0 if not options.delete_values: while (i < num_args): values[args[i]] = args[i+1] i = i + 2 else: while (i < num_args): valuesdel.insert(i, args[i]) i = i + 1 url = None if options.url: url = options.url else: url = munge_server_url(config.getServerlURL()[0]) s = create_server_obj(url) sid = get_sys_id() if not sid: system_exit(1, "Could not determine systemid") try: session = s.auth.login(options.username, options.password) if options.list_values: ret = s.system.get_custom_values(session, int(sid)) elif options.delete_values: ret = s.system.delete_custom_values(session, int(sid), valuesdel) else: ret = s.system.set_custom_values(session, int(sid), values) except xmlrpclib.Fault, e: if e.faultCode == -1: system_exit(1, "Error code: %s\nInvalid login information.\n" % e.faultCode) else: system_exit(1, "Error code: %s\n%s\n" % (e.faultCode, e.faultString))
def tui_call_wrapper(screen, func, *params): try: results = func(*params) except up2dateErrors.CommunicationError: ErrorWindow(screen, HOSTED_CONNECTION_ERROR % config.getServerlURL()[0]) raise sys.exc_info()[1] except up2dateErrors.SSLCertificateVerifyFailedError: ErrorWindow(screen, e.errmsg) raise sys.exc_info()[1] except up2dateErrors.NoBaseChannelError: e = sys.exc_info()[1] FatalErrorWindow(screen, e.errmsg + '\n' + BASECHANNELERROR % (up2dateUtils.getArch(), up2dateUtils.getOSRelease(), up2dateUtils.getVersion())) except up2dateErrors.SSLCertificateFileNotFound: e = sys.exc_info()[1] ErrorWindow(screen, e.errmsg + '\n\n' + SSL_CERT_FILE_NOT_FOUND_ERRER) raise e return results
def get_server(self, refreshCallback=None, serverOverride=None, timeout=None): """ Moved from rpcServer. """ ca = self.cfg["sslCACert"] if isinstance(ca, basestring): ca = [ca] rhns_ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"] if self.cfg["enableProxy"]: proxy_host = config.getProxySetting() else: proxy_host = None if not serverOverride: server_urls = config.getServerlURL() else: server_urls = serverOverride server_list = rpcServer.ServerList(server_urls) proxy_user = None proxy_password = None if self.cfg["enableProxyAuth"]: proxy_user = self.cfg["proxyUser"] or None proxy_password = self.cfg["proxyPassword"] or None lang = None for env in 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG': if os.environ.get(env): lang = os.environ[env].split(':')[0].split('.')[0] break else: continue retry_server = rpcServer.RetryServer(server_list.server(), refreshCallback=refreshCallback, proxy=proxy_host, username=proxy_user, password=proxy_password) retry_server.addServerList(server_list) retry_server.add_header("X-Up2date-Version", up2dateUtils.version()) if lang: retry_server.setlang(lang) # require RHNS-CA-CERT file to be able to authenticate the SSL connections need_ca = [True for i in retry_server.serverList.serverList if urlparse.urlparse(i)[0] == 'https'] if need_ca: for rhns_ca_cert in rhns_ca_certs: if not os.access(rhns_ca_cert, os.R_OK): msg = "%s: %s" % ("ERROR: can not find RHNS CA file", rhns_ca_cert) log.log_me("%s" % msg) raise up2dateErrors.SSLCertificateFileNotFound(msg) # force the validation of the SSL cert retry_server.add_trusted_cert(rhns_ca_cert) clientCaps.loadLocalCaps() # send up the capabality info header_list = clientCaps.caps.headerFormat() for (headerName, value) in header_list: retry_server.add_header(headerName, value) return retry_server
def findHostByRoute(): """ returns [hostname, intf, intf6] Where hostname is you FQDN of this machine. And intf is numeric IPv4 address. And intf6 is IPv6 address. """ cfg = config.initUp2dateConfig() sl = config.getServerlURL() st = {'https': 443, 'http': 80} hostname = None intf = None intf6 = None for serverUrl in sl: server = serverUrl.split('/')[2] servertype = serverUrl.split(':')[0] port = st[servertype] for family in (AF_INET6, AF_INET): try: s = socket.socket(family) except socket.error: continue if cfg['enableProxy']: server_port = config.getProxySetting() (server, port) = server_port.split(':') port = int(port) try: s.settimeout(5) s.connect((server, port)) intf_tmp = s.getsockname()[0] if family == AF_INET: intf = intf_tmp else: intf6 = intf_tmp hostname_tmp = socket.getfqdn(intf_tmp) if hostname_tmp != intf_tmp: hostname = hostname_tmp except socket.error: s.close() continue s.close() # Override hostname with the value from /etc/hostname if os.path.isfile("/etc/hostname") and os.access("/etc/hostname", os.R_OK): hostnameinfo = open("/etc/hostname", "r").readlines() for info in hostnameinfo: if not len(info): continue hostname = info.strip() # Override hostname with the one in /etc/sysconfig/network # for bz# 457953 elif os.path.isfile("/etc/sysconfig/network") and os.access( "/etc/sysconfig/network", os.R_OK): networkinfo = open("/etc/sysconfig/network", "r").readlines() for info in networkinfo: if not len(info): continue vals = info.split('=') if len(vals) <= 1: continue if vals[0].strip() == "HOSTNAME": # /etc/sysconfig/network is of shell syntax, # so values can be quoted hostname = ''.join(vals[1:]).strip('"\' \t\n') break if hostname == None or hostname == 'localhost.localdomain': hostname = "unknown" return hostname, intf, intf6
def findHostByRoute(): """ returns [hostname, intf, intf6] Where hostname is you FQDN of this machine. And intf is numeric IPv4 address. And intf6 is IPv6 address. """ cfg = config.initUp2dateConfig() sl = config.getServerlURL() st = {'https':443, 'http':80} hostname = None intf = None intf6 = None etchostname = False sockethostname = None for serverUrl in sl: server = serverUrl.split('/')[2] servertype = serverUrl.split(':')[0] port = st[servertype] for family in (AF_INET6, AF_INET): try: s = socket.socket(family) except socket.error: continue if cfg['enableProxy']: server_port = config.getProxySetting() (server, port) = server_port.split(':') port = int(port) try: s.settimeout(5) s.connect((server, port)) intf_tmp = s.getsockname()[0] if family == AF_INET: intf = intf_tmp else: intf6 = intf_tmp hostname_tmp = socket.getfqdn(intf_tmp) if hostname_tmp != intf_tmp: hostname = hostname_tmp sockethostname = hostname_tmp except socket.error: s.close() continue s.close() # Override hostname with the value from /etc/hostname if os.path.isfile("/etc/hostname") and os.access("/etc/hostname", os.R_OK): hostnameinfo = open("/etc/hostname", "r").readlines() # Warn if /etc/hostname contains more than one entry (bsc#929979) if len(hostnameinfo) > 1: log = up2dateLog.initLog() log.log_me("/etc/hostname contains more than one entry! Using first one.") if len(hostnameinfo): info = hostnameinfo[0] else: info = "" # ".site" is now an allowed TLD. Catch local installations by checking # for pseudo TLD ".suse" and require more than the domainname for ".site" # so "local.site" still can be identified as local installation (bsc#923990) if len(info): tmpval = info.strip().split('.') if not info.strip().endswith(".suse"): if not info.strip().endswith(".site") or len(tmpval) > 2: hostname = info.strip() etchostname = True # Override hostname with the one in /etc/sysconfig/network # for bz# 457953 elif os.path.isfile("/etc/sysconfig/network") and os.access("/etc/sysconfig/network", os.R_OK): networkinfo = open("/etc/sysconfig/network", "r").readlines() for info in networkinfo: if not len(info): continue vals = info.split('=') if len(vals) <= 1: continue if vals[0].strip() == "HOSTNAME": # /etc/sysconfig/network is of shell syntax, # so values can be quoted hostname = ''.join(vals[1:]).strip('"\' \t\n') etchostname = False break # /etc/hostname doesn't contain a fully qualified hostname # try to find out the domain if etchostname and "." not in hostname: fqdn = socket.getfqdn(hostname) if "." in fqdn: domain = fqdn.split('.', 1)[1] aliasfqdn = "{0}.{1}".format(hostname, domain) try: socket.gethostbyname(aliasfqdn) hostname = aliasfqdn except socket.error: hostname = fqdn log = up2dateLog.initLog() log.log_me("Could not resolve /etc/hostname alias to {0}. Falling back to {1}".format(aliasfqdn, fqdn)) else: log = up2dateLog.initLog() log.log_me("Got an invalid FQDN {0} for /etc/hostname. Falling back to {1}".format(fqdn, sockethostname)) hostname = sockethostname if hostname == None or hostname == 'localhost.localdomain': hostname = "unknown" return hostname, intf, intf6
def findHostByRoute(): """ returns [hostname, intf, intf6] Where hostname is you FQDN of this machine. And intf is numeric IPv4 address. And intf6 is IPv6 address. """ cfg = config.initUp2dateConfig() sl = config.getServerlURL() st = {'https':443, 'http':80} hostname = None intf = None intf6 = None for serverUrl in sl: server = serverUrl.split('/')[2] servertype = serverUrl.split(':')[0] port = st[servertype] for family in (AF_INET6, AF_INET): try: s = socket.socket(family) except socket.error: continue if cfg['enableProxy']: server_port = config.getProxySetting() (server, port) = server_port.split(':') port = int(port) try: s.settimeout(5) s.connect((server, port)) intf_tmp = s.getsockname()[0] if family == AF_INET: intf = intf_tmp else: intf6 = intf_tmp hostname_tmp = socket.getfqdn(intf_tmp) if hostname_tmp != intf_tmp: hostname = hostname_tmp except socket.error: s.close() continue s.close() # Override hostname with the value from /etc/hostname if os.path.isfile("/etc/hostname") and os.access("/etc/hostname", os.R_OK): hostnameinfo = open("/etc/hostname", "r").readlines() for info in hostnameinfo: if not len(info): continue hostname = info.strip() # Override hostname with the one in /etc/sysconfig/network # for bz# 457953 elif os.path.isfile("/etc/sysconfig/network") and os.access("/etc/sysconfig/network", os.R_OK): networkinfo = open("/etc/sysconfig/network", "r").readlines() for info in networkinfo: if not len(info): continue vals = info.split('=') if len(vals) <= 1: continue strippedstring = vals[0].strip() vals[0] = strippedstring if vals[0] == "HOSTNAME": hostname = ''.join(vals[1:]).strip() break if hostname == None or hostname == 'localhost.localdomain': hostname = "unknown" return hostname, intf, intf6
def get_server(): """Spacewalk server fqdn""" return urlparse(config.getServerlURL()[0]).netloc
def main(self): args = [] show_help = None debug_level = 3 mode = None dict_name_opt = { '--server-name': None, '--password': None, '--username': None, '--config': None, } for index in range(1, len(sys.argv)): arg = sys.argv[index] param = [x for x in dict_name_opt.items() if x[1] == 0] if param: if arg.startswith('-') or arg in self.modes: # not perfect, but at least a little bit better print("Option %s requires an argument" % dict_name_opt[param[0][0]]) return 1 dict_name_opt[param[0][0]] = arg continue if arg in ('--help', '-h'): show_help = 1 continue param = [s for s in dict_name_opt.keys() if arg.startswith(s)] if param: rarg = arg[len(param[0]):] if not rarg: dict_name_opt[param[0]] = 0 if index == len(sys.argv) - 1: print("Option %s requires an argument" % param[0]) return 1 continue if rarg[0] == '=': if len(rarg) == 1: print("Option %s requires an argument" % param[0]) return 1 dict_name_opt[param[0]] = rarg[1:] continue print("Unknown option %s" % arg) return 1 if mode is None: # This should be the mode mode = arg if mode == '': # Bad self.usage(1) if mode[0] == '-': # Mode can't be an option self.usage(1) if mode not in self.modes: print("Unknown mode %s" % mode) self.usage(1) continue args.append(arg) server_name = dict_name_opt['--server-name'] password = dict_name_opt['--password'] username = dict_name_opt['--username'] config_file_override = dict_name_opt['--config'] if config_file_override and not os.path.isfile(config_file_override): rhn_log.die(1, "Config file %s does not exist.", config_file_override) rhn_log.set_debug_level(debug_level) if mode is None: # No args were specified self.usage(0) execname = os.path.basename(sys.argv[0]) # Class names cannot have dot in them, so strip the extension execname = execname.split('.', 1)[0] mode_module = mode.replace('-', '_') module_name = "%s_%s" % (self.mode_prefix, mode_module) full_module_name = "%s.%s" % (self.plugins_dir, module_name) try: module = __import__(full_module_name) except ImportError: e = sys.exc_info()[1] rhn_log.die(1, "Unable to load plugin for mode '%s': %s" % (mode, e)) module = getattr(module, module_name) if show_help: # Display the per-module help handler = module.Handler(args, None, mode=mode, exec_name=execname) handler.usage() return 0 cfg = config.initUp2dateConfig() up2date_cfg = dict(cfg.items()) if server_name: local_config.init(self.config_section, defaults=up2date_cfg, config_file_override=config_file_override, server_url="https://" + server_name) else: local_config.init(self.config_section, defaults=up2date_cfg, config_file_override=config_file_override) try: server_name = local_config.get('server_url') except InterpolationError: e = sys.exc_info()[1] if e.option == 'server_url': server_name = config.getServerlURL() up2date_cfg['proto'] = urlsplit(server_name[0])[0] if up2date_cfg['proto'] == '': up2date_cfg['proto'] = 'https' up2date_cfg['server_list'] = [ urlsplit(x)[2] for x in server_name ] else: up2date_cfg['server_list'] = [ urlsplit(x)[1] for x in server_name ] server_name = (up2date_cfg['server_list'])[0] local_config.init( self.config_section, defaults=up2date_cfg, config_file_override=config_file_override, server_name=server_name) print("Using server name %s" % server_name) # set the debug level through the config rhn_log.set_debug_level(int(local_config.get('debug_level') or 0)) rhn_log.set_logfile(local_config.get('logfile') or "/var/log/rhncfg") # Multi-level import - __import__("foo.bar") does not return the bar # module, but the foo module with bar loaded # XXX Error checking repo_class = local_config.get('repository_type') if repo_class is None: rhn_log.die( 1, "repository_type not set (missing configuration file?)") repo_module_name = "%s.%s" % (self.plugins_dir, repo_class) try: repo_module = __import__(repo_module_name) except ImportError: e = sys.exc_info()[1] rhn_log.die(1, "Unable to load repository module: %s" % e) try: repo_module = getattr(repo_module, repo_class) except AttributeError: rhn_log.die(1, "Malformed repository module") try: repo = getattr(repo_module, self.repository_class_name)() except AttributeError: rhn_log.die(1, "Missing repository class") except InterpolationError: e = sys.exc_info()[1] if e.option == 'server_url': #pkilambi: bug#179367# backtic is replaced with single quote rhn_log.die( 1, "Missing 'server_url' configuration variable; please refer to the config file" ) raise except cfg_exceptions.ConfigurationError: e = sys.exc_info()[1] rhn_log.die(e) except gaierror: e = sys.exc_info()[1] print("Socket Error: %s" % (e.args[1], )) sys.exit(1) handler = module.Handler(args, repo, mode=mode, exec_name=execname) try: try: handler.authenticate(username, password) handler.run() except cfg_exceptions.AuthenticationError: e = sys.exc_info()[1] rhn_log.die(1, "Authentication failed: %s" % e) except Exception: raise finally: repo.cleanup() return 0
def main(self): args = [] show_help = None debug_level = 3 mode = None dict_name_opt={'--server-name': None,'--password': None,'--username': None,} for index in range(1,len(sys.argv)): arg=sys.argv[index] param = [x for x in dict_name_opt.items() if x[1] == 0] if param: if arg.startswith('-') or arg in self.modes: # not perfect, but at least a little bit better print("Option %s requires an argument" % dict_name_opt[param[0][0]]) return 1 dict_name_opt[param[0][0]] = arg continue if arg in ('--help', '-h'): show_help = 1 continue param = [s for s in dict_name_opt.keys() if arg.startswith(s)] if param: rarg = arg[len(param[0]):] if not rarg: dict_name_opt[param[0]] = 0 if index == len(sys.argv) - 1: print("Option %s requires an argument" % param[0]) return 1 continue if rarg[0] == '=': if len(rarg) == 1: print("Option %s requires an argument" % param[0]) return 1 dict_name_opt[param[0]] = rarg[1:] continue print("Unknown option %s" % arg) return 1 if mode is None: # This should be the mode mode = arg if mode == '': # Bad self.usage(1) if mode[0] == '-': # Mode can't be an option self.usage(1) if mode not in self.modes: print("Unknown mode %s" % mode) self.usage(1) continue args.append(arg) server_name = dict_name_opt['--server-name'] password = dict_name_opt['--password'] username = dict_name_opt['--username'] rhn_log.set_debug_level(debug_level) if mode is None: # No args were specified self.usage(0) execname = os.path.basename(sys.argv[0]) # Class names cannot have dot in them, so strip the extension execname = execname.split('.', 1)[0] mode_module = mode.replace('-', '_') module_name = "%s_%s" % (self.mode_prefix, mode_module) full_module_name = "%s.%s" % (self.plugins_dir, module_name) try: module = __import__(full_module_name) except ImportError: e = sys.exc_info()[1] rhn_log.die(1, "Unable to load plugin for mode '%s': %s" % (mode, e)) module = getattr(module, module_name) if show_help: # Display the per-module help handler = module.Handler(args, None, mode=mode, exec_name=execname) handler.usage() return 0 cfg = config.initUp2dateConfig() up2date_cfg = dict(cfg.items()) if server_name: local_config.init(self.config_section, defaults=up2date_cfg, server_url="https://" + server_name) else: local_config.init(self.config_section, defaults=up2date_cfg) try: server_name = local_config.get('server_url') except InterpolationError: e = sys.exc_info()[1] if e.option == 'server_url': server_name = config.getServerlURL() up2date_cfg['proto'] = urlsplit(server_name[0])[0] if up2date_cfg['proto'] == '': up2date_cfg['proto'] = 'https' up2date_cfg['server_list'] = [urlsplit(x)[2] for x in server_name] else: up2date_cfg['server_list'] = [urlsplit(x)[1] for x in server_name] server_name = (up2date_cfg['server_list'])[0] local_config.init(self.config_section, defaults=up2date_cfg, server_name=server_name) print("Using server name %s" % server_name) # set the debug level through the config rhn_log.set_debug_level(int(local_config.get('debug_level') or 0)) rhn_log.set_logfile(local_config.get('logfile') or "/var/log/rhncfg") # Multi-level import - __import__("foo.bar") does not return the bar # module, but the foo module with bar loaded # XXX Error checking repo_class = local_config.get('repository_type') if repo_class is None: rhn_log.die(1, "repository_type not set (missing configuration file?)") repo_module_name = "%s.%s" % (self.plugins_dir, repo_class) try: repo_module = __import__(repo_module_name) except ImportError: e = sys.exc_info()[1] rhn_log.die(1, "Unable to load repository module: %s" % e) try: repo_module = getattr(repo_module, repo_class) except AttributeError: rhn_log.die(1, "Malformed repository module") try: repo = getattr(repo_module, self.repository_class_name)() except AttributeError: rhn_log.die(1, "Missing repository class") except InterpolationError: e = sys.exc_info()[1] if e.option == 'server_url': #pkilambi: bug#179367# backtic is replaced with single quote rhn_log.die(1, "Missing 'server_url' configuration variable; please refer to the config file") raise except cfg_exceptions.ConfigurationError: e = sys.exc_info()[1] rhn_log.die(e) except gaierror: e = sys.exc_info()[1] print("Socket Error: %s" % (e.args[1],)) sys.exit(1) handler = module.Handler(args, repo, mode=mode, exec_name=execname) try: try: handler.authenticate(username, password) handler.run() except cfg_exceptions.AuthenticationError: e = sys.exc_info()[1] rhn_log.die(1, "Authentication failed: %s" % e) except Exception: raise finally: repo.cleanup() return 0
def getServer(refreshCallback=None, serverOverride=None, timeout=None): log = up2dateLog.initLog() cfg = config.initUp2dateConfig() # Where do we keep the CA certificate for RHNS? # The servers we're talking to need to have their certs # signed by one of these CA. ca = cfg["sslCACert"] if not isinstance(ca, list): ca = [ca] rhns_ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"] if cfg["enableProxy"]: proxyHost = config.getProxySetting() else: proxyHost = None if not serverOverride: serverUrls = config.getServerlURL() else: serverUrls = serverOverride serverList = ServerList(serverUrls) proxyUser = None proxyPassword = None if cfg["enableProxyAuth"]: proxyUser = cfg["proxyUser"] or None proxyPassword = cfg["proxyPassword"] or None lang = None for env in 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG': if env in os.environ: if not os.environ[env]: # sometimes unset continue lang = os.environ[env].split(':')[0] lang = lang.split('.')[0] break s = RetryServer(serverList.server(), refreshCallback=refreshCallback, proxy=proxyHost, username=proxyUser, password=proxyPassword, timeout=timeout) s.addServerList(serverList) s.add_header("X-Up2date-Version", up2dateUtils.version()) if lang: s.setlang(lang) # require RHNS-CA-CERT file to be able to authenticate the SSL connections need_ca = [ True for i in s.serverList.serverList if urlparse.urlparse(i)[0] == 'https' ] if need_ca: for rhns_ca_cert in rhns_ca_certs: if not os.access(rhns_ca_cert, os.R_OK): msg = "%s: %s" % (_("ERROR: can not find RHNS CA file"), rhns_ca_cert) log.log_me("%s" % msg) raise up2dateErrors.SSLCertificateFileNotFound(msg) # force the validation of the SSL cert s.add_trusted_cert(rhns_ca_cert) clientCaps.loadLocalCaps() # send up the capabality info headerlist = clientCaps.caps.headerFormat() for (headerName, value) in headerlist: s.add_header(headerName, value) return s
config_file = self.options.cfg self._config = osad_config.init('osad', config_file=config_file) config_keys = [ 'debug_level', 'osa_ssl_cert', 'logfile', 'run_rhn_check', 'rhn_check_command', 'enable_failover' ] for key in config_keys: ret[key] = osad_config.get(key) try: server_url = osad_config.get('server_url') except osad_config.InterpolationError, e: server_url = config.getServerlURL()[0] else: if server_url is None: server_url = config.getServerlURL()[0] ret['server_url'] = server_url #8/23/05 wregglej 165775 added the run_rhn_check option. run_rhn_check = osad_config.get('run_rhn_check') if run_rhn_check is None: log_debug(3, "Forcing run_rhn_check") run_rhn_check = 1 ret['run_rhn_check'] = int(run_rhn_check) ret['tcp_keepalive_timeout'] = int( osad_config.get('tcp_keepalive_timeout', defval=1800)) ret['tcp_keepalive_count'] = int( osad_config.get('tcp_keepalive_count', defval=3))
def read_config(self): ret = {} # Read from the global config first config_file = self.options.cfg self._config = osad_config.init('osad', config_file=config_file) config_keys = [ 'debug_level', 'osa_ssl_cert', 'logfile', 'run_rhn_check', 'rhn_check_command', 'enable_failover' ] for key in config_keys: ret[key] = osad_config.get(key) try: server_url = osad_config.get('server_url') except osad_config.InterpolationError: e = sys.exc_info()[1] server_url = config.getServerlURL() else: if not server_url: server_url = config.getServerlURL() else: def convert_url(s): s = s.strip() if hasattr(config, 'convert_url_to_puny'): s = config.convert_url_to_puny(s) elif hasattr(config, 'convert_url_to_pune'): s = config.convert_url_to_pune(s) return s server_url = [convert_url(i) for i in server_url.split(';')] # Remove empty URLs for url in server_url: if not url: server_url.remove(url) # Real unusual case if there is no server URL both in up2date and osad config files if not server_url: die("Missing server URL in config file") ret['server_url'] = server_url #8/23/05 wregglej 165775 added the run_rhn_check option. run_rhn_check = osad_config.get('run_rhn_check') if run_rhn_check is None: log_debug(3, "Forcing run_rhn_check") run_rhn_check = 1 ret['run_rhn_check'] = int(run_rhn_check) ret['tcp_keepalive_timeout'] = int( osad_config.get('tcp_keepalive_timeout', defval=1800)) ret['tcp_keepalive_count'] = int( osad_config.get('tcp_keepalive_count', defval=3)) systemid = osad_config.get('systemid') if systemid is None: systemid = self.get_up2date_config()['systemIdPath'] ret['systemid'] = systemid enable_proxy = self._config.get_option('enableProxy') if enable_proxy is None: enable_proxy = self.get_up2date_config()['enableProxy'] if enable_proxy: ret['enable_proxy'] = 1 ret['proxy_url'] = self._config.get_option('httpProxy') if ret['proxy_url'] is None: ret['proxy_url'] = str(config.getProxySetting()) ret['enable_proxy_auth'] = 0 enable_proxy_auth = self._config.get_option('enableProxyAuth') if enable_proxy_auth is None: enable_proxy_auth = self.get_up2date_config( )['enableProxyAuth'] if enable_proxy_auth: ret['enable_proxy_auth'] = 1 proxy_user = self._config.get_option('proxyUser') if proxy_user is None: proxy_user = self.get_up2date_config()['proxyUser'] ret['proxy_user'] = proxy_user proxy_password = self._config.get_option('proxyPassword') if proxy_password is None: proxy_password = self.get_up2date_config()['proxyPassword'] ret['proxy_password'] = proxy_password if not server_url: die("Unable to retrieve server URL") # SSL cert for Jabber's TLS, it can potentially be different than the # client's osa_ssl_cert = self._config.get_option('osa_ssl_cert') # The up2date ssl cert - we get it from up2daate's config file client_ca_cert = self.get_up2date_config()['sslCACert'] if isinstance(client_ca_cert, ListType): if client_ca_cert: client_ca_cert = client_ca_cert[0] else: client_ca_cert = None if osa_ssl_cert is None: # No setting, use up2date's osa_ssl_cert = client_ca_cert if client_ca_cert is not None: ret['ssl_ca_cert'] = client_ca_cert if osa_ssl_cert is not None: ret['osa_ssl_cert'] = osa_ssl_cert return ret
def update_applet_cfg(): server_url = config.getServerlURL()[0] # get up2date's conf vals... new_ca = read_cfg_val(cfg, 'sslCACert') # TODO: applet needs to support failover # for now patch the ca if type(new_ca) == type([]): new_ca_buf = "%s" % (string.join(map(str, new_ca), ';')) else: new_ca_buf = new_ca # determine the new needed values new_url = re.sub(r"(http[s]?://.*?)/.*$", r"\1/APPLET", server_url) backup_filename = APPLET_CONF + ".bak" new_filename = APPLET_CONF + ".new" # slurp in the current conf to snag the uuid contents = open(APPLET_CONF, "r").read() up2date_uuid_cfg = _get_uuid_config() uuid = read_cfg_val(up2date_uuid_cfg, "rhnuuid") try: # 2. create new file fd = os.open(new_filename, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0644) new_file = os.fdopen(fd, 'w') new_file.seek(0) seen_ca_cert = 0 for line in string.split(contents, "\n"): if line.startswith('server_url='): new_file.write("server_url=%s\n\n" % new_url) continue if line.startswith('uuid='): if uuid: # Use the up2date uuid instead new_file.write("uuid=%s\n\n" % uuid) continue # Load the applet's uuid uuid = (string.split(line, '='))[1] new_file.write(line + '\n\n') continue if line.startswith('use_ca_cert='): seen_ca_cert = 1 new_file.write("use_ca_cert=%s\n" % new_ca_buf) continue if new_ca and not seen_ca_cert: new_file.write("use_ca_cert=%s\n" % new_ca_buf) new_file.close() # 3. rename current to backup os.rename(APPLET_CONF, backup_filename) # 4. rename new to current os.rename(new_filename, APPLET_CONF) # 5. unlink backup os.unlink(backup_filename) except Exception: # failure, restore from backup and error out os.rename(backup_filename, APPLET_CONF) raise return (new_url, uuid)
def main(): (options, args, num_args) = verify_command_line() values = {} valuesdel = [] i = 0 if not options.delete_values: while (i < num_args): values[args[i]] = args[i + 1] i = i + 2 else: while (i < num_args): valuesdel.insert(i, args[i]) i = i + 1 url = None if options.url: url = options.url else: url = munge_server_url(config.getServerlURL()[0]) s = create_server_obj(url) sid = get_sys_id() if not sid: system_exit(1, "Could not determine systemid") try: session = s.auth.login(options.username, options.password) if options.list_values: ret = s.system.get_custom_values(session, int(sid)) elif options.delete_values: ret = s.system.delete_custom_values(session, int(sid), valuesdel) else: ret = s.system.set_custom_values(session, int(sid), values) except xmlrpclib.Fault: t, e = sys.exc_info()[:2] if e.faultCode == -1: system_exit( 1, "Error code: %s\nInvalid login information.\n" % e.faultCode) else: system_exit(1, "Error code: %s\n%s\n" % (e.faultCode, e.faultString)) # handle list and set modes for output... if options.list_values: if not ret: system_exit(0, "No custom values set for this system.\n") for key in ret: print("%s\t%s" % (key, ret[key])) system_exit(0, None) else: if ret: system_exit(0, None) else: system_exit(1, "Unknown failure!\n")
ret = {} # Read from the global config first config_file = self.options.cfg self._config = osad_config.init('osad', config_file=config_file) config_keys = ['debug_level', 'osa_ssl_cert', 'logfile', 'run_rhn_check', 'rhn_check_command', 'enable_failover'] for key in config_keys: ret[key] = osad_config.get(key) try: server_url = osad_config.get('server_url') except osad_config.InterpolationError, e: server_url = config.getServerlURL()[0] else: if server_url is None: server_url = config.getServerlURL()[0] ret['server_url'] = server_url #8/23/05 wregglej 165775 added the run_rhn_check option. run_rhn_check = osad_config.get('run_rhn_check') if run_rhn_check is None: log_debug(3, "Forcing run_rhn_check") run_rhn_check = 1 ret['run_rhn_check'] = int(run_rhn_check) ret['tcp_keepalive_timeout'] = int(osad_config.get('tcp_keepalive_timeout', defval=1800)) ret['tcp_keepalive_count'] = int(osad_config.get('tcp_keepalive_count', defval=3)) systemid = osad_config.get('systemid') if systemid is None:
def read_config(self): ret = {} # Read from the global config first config_file = self.options.cfg self._config = osad_config.init('osad', config_file=config_file) config_keys = ['debug_level', 'osa_ssl_cert', 'logfile', 'run_rhn_check', 'rhn_check_command', 'enable_failover'] for key in config_keys: ret[key] = osad_config.get(key) try: server_url = osad_config.get('server_url') except osad_config.InterpolationError: e = sys.exc_info()[1] server_url = config.getServerlURL() else: if not server_url: server_url = config.getServerlURL() else: def convert_url(s): s = s.strip() if hasattr(config, 'convert_url_to_puny'): s = config.convert_url_to_puny(s) elif hasattr(config, 'convert_url_to_pune'): s = config.convert_url_to_pune(s) return s server_url = [convert_url(i) for i in server_url.split(';')] # Remove empty URLs for url in server_url: if not url: server_url.remove(url) # Real unusual case if there is no server URL both in up2date and osad config files if not server_url: die("Missing server URL in config file") ret['server_url'] = server_url #8/23/05 wregglej 165775 added the run_rhn_check option. run_rhn_check = osad_config.get('run_rhn_check') if run_rhn_check is None: log_debug(3, "Forcing run_rhn_check") run_rhn_check = 1 ret['run_rhn_check'] = int(run_rhn_check) ret['tcp_keepalive_timeout'] = int(osad_config.get('tcp_keepalive_timeout', defval=1800)) ret['tcp_keepalive_count'] = int(osad_config.get('tcp_keepalive_count', defval=3)) systemid = osad_config.get('systemid') if systemid is None: systemid = self.get_up2date_config()['systemIdPath'] ret['systemid'] = systemid enable_proxy = self._config.get_option('enableProxy') if enable_proxy is None: enable_proxy = self.get_up2date_config()['enableProxy'] if enable_proxy: ret['enable_proxy'] = 1 ret['proxy_url'] = self._config.get_option('httpProxy') if ret['proxy_url'] is None: ret['proxy_url'] = str(config.getProxySetting()) ret['enable_proxy_auth'] = 0 enable_proxy_auth = self._config.get_option('enableProxyAuth') if enable_proxy_auth is None: enable_proxy_auth = self.get_up2date_config()['enableProxyAuth'] if enable_proxy_auth: ret['enable_proxy_auth'] = 1 proxy_user = self._config.get_option('proxyUser') if proxy_user is None: proxy_user = self.get_up2date_config()['proxyUser'] ret['proxy_user'] = proxy_user proxy_password = self._config.get_option('proxyPassword') if proxy_password is None: proxy_password = self.get_up2date_config()['proxyPassword'] ret['proxy_password'] = proxy_password if not server_url: die("Unable to retrieve server URL") # SSL cert for Jabber's TLS, it can potentially be different than the # client's osa_ssl_cert = self._config.get_option('osa_ssl_cert') # The up2date ssl cert - we get it from up2daate's config file client_ca_cert = self.get_up2date_config()['sslCACert'] if isinstance(client_ca_cert, ListType): if client_ca_cert: client_ca_cert = client_ca_cert[0] else: client_ca_cert = None if osa_ssl_cert is None: # No setting, use up2date's osa_ssl_cert = client_ca_cert if client_ca_cert is not None: ret['ssl_ca_cert'] = client_ca_cert if osa_ssl_cert is not None: ret['osa_ssl_cert'] = osa_ssl_cert return ret
def getServer(refreshCallback=None, serverOverride=None, timeout=None): log = up2dateLog.initLog() cfg = config.initUp2dateConfig() # Where do we keep the CA certificate for RHNS? # The servers we're talking to need to have their certs # signed by one of these CA. ca = cfg["sslCACert"] if not isinstance(ca, list): ca = [ca] rhns_ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"] if cfg["enableProxy"]: proxyHost = config.getProxySetting() else: proxyHost = None if not serverOverride: serverUrls = config.getServerlURL() else: serverUrls = serverOverride serverList = ServerList(serverUrls) proxyUser = None proxyPassword = None if cfg["enableProxyAuth"]: proxyUser = cfg["proxyUser"] or None proxyPassword = cfg["proxyPassword"] or None lang = None for env in 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG': if env in os.environ: if not os.environ[env]: # sometimes unset continue lang = os.environ[env].split(':')[0] lang = lang.split('.')[0] break s = RetryServer(serverList.server(), refreshCallback=refreshCallback, proxy=proxyHost, username=proxyUser, password=proxyPassword, timeout=timeout) s.addServerList(serverList) s.add_header("X-Up2date-Version", up2dateUtils.version()) if lang: s.setlang(lang) # require RHNS-CA-CERT file to be able to authenticate the SSL connections need_ca = [ True for i in s.serverList.serverList if urlparse.urlparse(i)[0] == 'https'] if need_ca: for rhns_ca_cert in rhns_ca_certs: if not os.access(rhns_ca_cert, os.R_OK): msg = "%s: %s" % (_("ERROR: can not find RHNS CA file"), rhns_ca_cert) log.log_me("%s" % msg) raise up2dateErrors.SSLCertificateFileNotFound(msg) # force the validation of the SSL cert s.add_trusted_cert(rhns_ca_cert) clientCaps.loadLocalCaps() # send up the capabality info headerlist = clientCaps.caps.headerFormat() for (headerName, value) in headerlist: s.add_header(headerName, value) return s
class BaseMain: modes = [] repository_class_name = "Repository" plugins_dir = 'config_common' mode_prefix = None config_section = None def usage(self, exit_code): print "Usage: %s MODE [ --server-name name ] [ params ]" % sys.argv[0] print "Valid modes are:" for mode in self.modes: print "\t%s" % mode sys.exit(exit_code) def main(self): args = [] show_help = None debug_level = 3 mode = None dict_name_opt={'--server-name': None,'--password': None,'--username': None,} for index in range(1,len(sys.argv)): arg=sys.argv[index] param = filter(lambda x: x[1] == 0,dict_name_opt.iteritems()) if param: if arg.startswith('-') or arg in self.modes: # not perfect, but at least a little bit better print "Option %s requires an argument" % dict_name_opt[param[0][0]] return 1 dict_name_opt[param[0][0]] = arg continue if arg in ('--help', '-h'): show_help = 1 continue param = [s for s in dict_name_opt.keys() if arg.startswith(s)] if param: rarg = arg[len(param[0]):] if not rarg: dict_name_opt[param[0]] = 0 if index == len(sys.argv) - 1: print "Option %s requires an argument" % param[0] return 1 continue if rarg[0] == '=': if len(rarg) == 1: print "Option %s requires an argument" % param[0] return 1 dict_name_opt[param[0]] = rarg[1:] continue print "Unknown option %s" % arg return 1 if mode is None: # This should be the mode mode = arg if mode == '': # Bad self.usage(1) if mode[0] == '-': # Mode can't be an option self.usage(1) if mode not in self.modes: print "Unknown mode %s" % mode self.usage(1) continue args.append(arg) server_name = dict_name_opt['--server-name'] password = dict_name_opt['--password'] username = dict_name_opt['--username'] rhn_log.set_debug_level(debug_level) if mode is None: # No args were specified self.usage(0) execname = os.path.basename(sys.argv[0]) # Class names cannot have dot in them, so strip the extension execname = string.split(execname, '.', 1)[0] mode_module = string.replace(mode, '-', '_') module_name = "%s_%s" % (self.mode_prefix, mode_module) full_module_name = "%s.%s" % (self.plugins_dir, module_name) try: module = __import__(full_module_name) except ImportError, e: rhn_log.die(1, "Unable to load plugin for mode '%s': %s" % (mode, e)) module = getattr(module, module_name) if show_help: # Display the per-module help handler = module.Handler(args, None, mode=mode, exec_name=execname) handler.usage() return 0 cfg = config.initUp2dateConfig() up2date_cfg = dict(cfg.items()) if server_name: local_config.init(self.config_section, defaults=up2date_cfg, server_url="https://" + server_name) else: local_config.init(self.config_section, defaults=up2date_cfg) try: server_name = local_config.get('server_url') except InterpolationError, e: if e.option == 'server_url': server_name = config.getServerlURL() up2date_cfg['proto'] = urlsplit(server_name[0])[0] if up2date_cfg['proto'] == '': up2date_cfg['proto'] = 'https' up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[2], server_name) else: up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[1], server_name) server_name = (up2date_cfg['server_list'])[0] local_config.init(self.config_section, defaults=up2date_cfg, server_name=server_name)
def main(): (options, args, num_args) = verify_command_line() values = {} valuesdel = [] i = 0 if not options.delete_values: while (i < num_args): values[args[i]] = args[i+1] i = i + 2 else: while (i < num_args): valuesdel.insert(i, args[i]) i = i + 1 url = None if options.url: url = options.url else: url = munge_server_url(config.getServerlURL()[0]) s = create_server_obj(url) sid = get_sys_id() if not sid: system_exit(1, "Could not determine systemid") try: session = s.auth.login(options.username, options.password) if options.list_values: ret = s.system.get_custom_values(session, int(sid)) elif options.delete_values: ret = s.system.delete_custom_values(session, int(sid), valuesdel) else: ret = s.system.set_custom_values(session, int(sid), values) except xmlrpclib.Fault: t, e = sys.exc_info()[:2] if e.faultCode == -1: system_exit(1, "Error code: %s\nInvalid login information.\n" % e.faultCode) else: system_exit(1, "Error code: %s\n%s\n" % (e.faultCode, e.faultString)) # handle list and set modes for output... if options.list_values: if not ret: system_exit(0, "No custom values set for this system.\n") for key in ret: print ("%s\t%s" % (key, ret[key])) system_exit(0, None) else: if ret: system_exit(0, None); else: system_exit(1, "Unknown failure!\n")