Beispiel #1
0
    def __getXmlrpcServer():
        """ get an xmlrpc server object

            WARNING: if CFG.USE_SSL is off, we are sending info
                     in the clear.
        """
        log_debug(3)

        # build the URL
        url = CFG.RHN_PARENT or ''
        url = parseUrl(url)[1].split(':')[0]
        if CFG.USE_SSL:
            url = 'https://' + url + '/XMLRPC'
        else:
            url = 'http://' + url + '/XMLRPC'
        log_debug(3, 'server url: %s' % url)

        if CFG.HTTP_PROXY:
            serverObj = rpclib.Server(url,
                                      proxy=CFG.HTTP_PROXY,
                                      username=CFG.HTTP_PROXY_USERNAME,
                                      password=CFG.HTTP_PROXY_PASSWORD)
        else:
            serverObj = rpclib.Server(url)
        if CFG.USE_SSL and CFG.CA_CHAIN:
            if not os.access(CFG.CA_CHAIN, os.R_OK):
                log_error('ERROR: missing or cannot access (for ca_chain): %s' % CFG.CA_CHAIN)
                raise rhnFault(1000,
                               _("Spacewalk Proxy error (file access issues). "
                                 "Please contact your system administrator. "
                                 "Please refer to Spacewalk Proxy logs."))
            serverObj.add_trusted_cert(CFG.CA_CHAIN)
        serverObj.add_header('X-RHN-Client-Version', 2)
        return serverObj
Beispiel #2
0
    def connect_to_rhn(self, credentials):
        hostname = self.rhncfg['serverURL'].split('/')[2]
        server_url = 'https://%s/rpc/api' % (hostname)
        try:
            if self.rhncfg['enableProxy']:
                proxy = "%s:%s" % (self.proxy_host, self.proxy_port)
                log.info("Using proxy %s for RHN API methods" % (proxy))
                if self.rhncfg['enableProxyAuth']:
                    proxy = "@".join(
                        ["%s:%s" % (self.proxy_user, self.proxy_pass), proxy])
            else:
                proxy = None

            sc = rpclib.Server(server_url, proxy=proxy)

            ca = self.rhncfg["sslCACert"]
            sc.add_trusted_cert(ca)

            sk = sc.auth.login(credentials.username, credentials.password)
            return (sc, sk)
        except Exception:
            log.error(traceback.format_exc())
            system_exit(
                1,
                _("Unable to authenticate to RHN Classic.  See /var/log/rhsm/rhsm.log for more details."
                  ))
Beispiel #3
0
    def connect_to_rhn(self, credentials):
        hostname = self.rhncfg['serverURL'].split('/')[2]
        server_url = 'https://%s/rpc/api' % (hostname)

        try:
            if self.rhncfg['enableProxy']:
                proxy = "%s:%s" % (self.proxy_host, self.proxy_port)
                log.info("Using proxy %s for legacy API methods" % (proxy))
                if self.rhncfg['enableProxyAuth']:
                    proxy = "@".join(
                        ["%s:%s" % (self.proxy_user, self.proxy_pass), proxy])
            else:
                proxy = None

            rpc_session = rpclib.Server(server_url, proxy=proxy)

            ca = self.rhncfg["sslCACert"]
            rpc_session.add_trusted_cert(ca)

            if credentials.username and credentials.password:
                session_key = rpc_session.auth.login(credentials.username,
                                                     credentials.password)
            else:
                session_key = None

            return (rpc_session, session_key)
        except Exception as e:
            log.exception(e)
            system_exit(
                1,
                _("Unable to authenticate to legacy server.  ") + SEE_LOG_FILE)
Beispiel #4
0
    def getSourcePackagePath(self, pkgFilename):
        """ OVERLOADS getSourcePackagePath in common/rhnRepository.
            snag src.rpm and nosrc.rpm from local repo, after ensuring
            we are authorized to fetch it.
        """

        log_debug(3, pkgFilename)
        if pkgFilename[-8:] != '.src.rpm' and pkgFilename[-10:] != '.nosrc.rpm':
            raise rhnFault(
                17,
                _("Invalid SRPM package requested: %s") % pkgFilename)

        # Connect to the server to get an authorization for downloading this
        # package
        server = rpclib.Server(self.rhnParentXMLRPC,
                               proxy=self.httpProxy,
                               username=self.httpProxyUsername,
                               password=self.httpProxyPassword)
        if self.caChain:
            server.add_trusted_cert(self.caChain)

        try:
            retval = server.proxy.package_source_in_channel(
                pkgFilename, self.channelName, self.clientInfo)
        except xmlrpclib.Fault, e:
            raise rhnFault(1000,
                           _("Error retrieving source package: %s") %
                           str(e)), None, sys.exc_info()[2]
Beispiel #5
0
def getXmlrpcServer(server,
                    handler,
                    proxy,
                    proxyUser,
                    proxyPass,
                    sslCertPath,
                    sslYN=1):
    """ Return an XML-RPC Server connection object; no ssl if sslCertPath==None.
        May return rpclib.xmlrpclib.Fault, rpclib.xmlrpclib.ProtocolError,
        or socket.error.
    """

    _uri = server + handler
    uri = 'https://' + _uri
    if not sslYN or not sslCertPath:
        uri = 'http://' + _uri

    s = rpclib.Server(uri,
                      refreshCallback=None,
                      proxy=proxy,
                      username=proxyUser,
                      password=proxyPass,
                      timeout=CFG.timeout)
    if sslYN and sslCertPath:
        if not os.access(sslCertPath, os.R_OK):
            sys.stderr.write("SSL CA Cert inaccessible: '%s'\n" % sslCertPath)
            sys.exit(1)
        s.add_trusted_cert(sslCertPath)

    return s
def main():
    if len(sys.argv) == 1:
        server_name = 'xmlrpc.rhn.webdev.redhat.com'
    else:
        server_name = sys.argv[1]

    if len(sys.argv) <= 2:
        db_name = 'rhnuser/rhnuser@webdev'
    else:
        db_name = sys.argv[2]

    try:
        rhnSQL.initDB(db_name)
    except ConfigParserError:
        # database is not available when running in rpmbuild time
        print "Test skipped"
        return 0

    uri = "http://%s/XMLRPC" % (server_name, )
    s = rpclib.Server(uri)

    username = password = "******" % time.time()
    email = "*****@*****.**" % username

    s.registration.reserve_user(username, password)
    s.registration.new_user(username, password, email)

    data = {
        'os_release': '9',
        'architecture': 'athlon-redhat-linux',
        'profile_name': 'Test profile for %s' % username,
        'username': username,
        'password': password,
    }
    systemid = s.registration.new_system(data)

    str_caps = [
        'this.is.bogus1(0)=0',
        'this.is.bogus2(1)=1',
        'this.is.bogus3(2)=2',
    ]
    for cap in str_caps:
        s.add_header('X-RHN-Client-Capability', cap)

    # Add some packages
    packages = [
        ['a', '1', '1', ''],
        ['b', '2', '2', ''],
        ['c', '3', '3', ''],
    ]
    s.registration.update_packages(systemid, packages)

    sobj = rhnServer.get(systemid)
    server_id = sobj.getid()
    print "Registered server", server_id

    return 0
Beispiel #7
0
def getServer(options, handler):
    """ get an rpclib.Server object. NOTE: proxy is an HTTP proxy """

    serverUrl = 'https://' + options.server + handler

    s = None
    if options.http_proxy:
        s = rpclib.Server(serverUrl,
                          proxy=options.http_proxy,
                          username=options.http_proxy_username,
                          password=options.http_proxy_password)
    else:
        s = rpclib.Server(serverUrl)

    if options.ca_cert:
        s.add_trusted_cert(options.ca_cert)

    return s
Beispiel #8
0
    def getSourcePackagePath(self, pkgFilename):
        """ OVERLOADS getSourcePackagePath in common/rhnRepository.
            snag src.rpm and nosrc.rpm from local repo, after ensuring
            we are authorized to fetch it.
        """

        log_debug(3, pkgFilename)
        if pkgFilename[-8:] != '.src.rpm' and pkgFilename[-10:] != '.nosrc.rpm':
            raise rhnFault(
                17,
                _("Invalid SRPM package requested: %s") % pkgFilename)

        # Connect to the server to get an authorization for downloading this
        # package
        server = rpclib.Server(self.rhnParentXMLRPC,
                               proxy=self.httpProxy,
                               username=self.httpProxyUsername,
                               password=self.httpProxyPassword)
        if self.caChain:
            server.add_trusted_cert(self.caChain)

        try:
            retval = server.proxy.package_source_in_channel(
                pkgFilename, self.channelName, self.clientInfo)
        except xmlrpclib.Fault as e:
            raise_with_tb(
                rhnFault(1000,
                         _("Error retrieving source package: %s") % str(e)),
                sys.exc_info()[2])

        if not retval:
            raise rhnFault(
                17,
                _("Invalid SRPM package requested: %s") % pkgFilename)

        if pkgFilename[-8:] != '.src.rpm':
            # We already know the filename ends in .src.rpm
            nvrea = list(parseRPMName(pkgFilename[:-8]))
            nvrea.append("src")
        else:
            # We already know the filename ends in .nosrc.rpm
            # otherwise we did not pass first if in this func
            nvrea = list(parseRPMName(pkgFilename[:-10]))
            nvrea.append("nosrc")

        filePaths = computePackagePaths(nvrea, source=1, prepend=PREFIX)
        for filePath in filePaths:
            filePath = "%s/%s" % (CFG.PKG_DIR, filePath)
            log_debug(4, "File path", filePath)
            if os.access(filePath, os.R_OK):
                return filePath
        log_debug(4, "Source package not found locally: %s" % pkgFilename)
        raise NotLocalError(filePaths[0], pkgFilename)
Beispiel #9
0
def _create_server_obj(server_url):

    enable_proxy = read_cfg_val(cfg, 'enableProxy')
    enable_proxy_auth = read_cfg_val(cfg, 'enableProxyAuth')
    proxy_host = None
    proxy_user = None
    proxy_password = None

    if enable_proxy:
        proxy_host = self._local_config.get('httpProxy')

        if enable_proxy_auth:
            proxy_user = read_cfg_val(cfg, 'proxyUser')
            proxy_password = read_cfg_val(cfg, 'proxyPassword')

    ca = read_cfg_val(cfg, 'sslCACert')

    if type(ca) == type(""):
        ca = [ca]

    ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"]

    lang = None
    for env in 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG':
        if os.environ.has_key(env):
            if not os.environ[env]:
                # sometimes unset
                continue
            lang = string.split(os.environ[env], ':')[0]
            lang = string.split(lang, '.')[0]
            break


    server = rpclib.Server(server_url,
                           proxy=proxy_host,
                           username=proxy_user,
                           password=proxy_password)

    #server.set_transport_flags(encoding="gzip", transfer="binary")

    if lang:
        server.setlang(lang)

    for ca_cert in ca_certs:
        if not os.access(ca_cert, os.R_OK):
            raise Exception("could not find cert %s" % ca_cert)

        server.add_trusted_cert(ca_cert)

    return server
def create_server_obj(server_url):

    cfg = config.initUp2dateConfig()

    enable_proxy = cfg['enableProxy']
    proxy_host = None
    proxy_user = None
    proxy_password = None

    if enable_proxy:
        proxy_host = config.getProxySetting()

        if cfg['enableProxyAuth']:
            proxy_user = cfg['proxyUser']
            proxy_password = cfg['proxyPassword']

    ca = cfg['sslCACert']

    if isinstance(ca, basestring):
        ca = [ca]

    ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"]

    lang = None
    for env in 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG':
        if env in os.environ:
            lang = os.environ[env].split(':')[0]
            lang = lang.split('.')[0]
            break
        else:
            continue


    server = rpclib.Server(server_url,
                           proxy=proxy_host,
                           username=proxy_user,
                           password=proxy_password)

    if lang:
        server.setlang(lang)

    if server_url.startswith("https"):
        for ca_cert in ca_certs:
            if not os.access(ca_cert, os.R_OK):
                raise "could not find cert %s" % ca_cert

            server.add_trusted_cert(ca_cert)

    return server
Beispiel #11
0
 def __get_osad_config(self):
     serverrpc = rpclib.Server(uri=self.get_server_url())
     ret = None
     while ret is None:
         self.logger.info("registering as push client with %s..." %
                          self.get_server_url())
         try:
             ret = serverrpc.registration.register_osad(
                 self.get_systemid(),
                 {'client-timestamp': int(time.time())})
         except Exception as e:
             self.ogger.error(e)
             self.logger.info("waiting %d seconds..." %
                              self.get_osad_registry_interval())
             time.sleep(self.get_osad_registry_interval())
     return ret
Beispiel #12
0
    def _lookupKickstart(self, fileName, rhnParentXMLRPC, httpProxy,
                         httpProxyUsername, httpProxyPassword, caChain):
        fileDir = self._getPkgListDir()
        filePath = "%s/%s-1" % (fileDir, fileName)
        mapping = None
        if os.access(filePath, os.R_OK):
            try:
                # Slurp the file
                try:
                    with open(filePath, "r") as f:
                        mapping = cPickle.loads(f.read())
                except (UnicodeDecodeError, TypeError):
                    with open(filePath, "rb") as f:
                        mapping = cPickle.loads(f.read())
            except (IOError, cPickle.UnpicklingError):  # corrupt cached file
                mapping = None  # ignore it, we'll get and write it again

        now = int(time.time())
        if not mapping or mapping['expires'] < now:
            # Can't use the normal GETServer handler because there is no client
            # to auth. Instead this is something the Proxy has to be able to
            # do, so read the serverid and send that up.
            server = rpclib.Server(rhnParentXMLRPC,
                                   proxy=httpProxy,
                                   username=httpProxyUsername,
                                   password=httpProxyPassword)
            if caChain:
                server.add_trusted_cert(caChain)
            try:
                response = self._getMapping(server)
                mapping = {
                    'channel': str(response['label']),
                    'version': str(response['last_modified']),
                    'expires': int(time.time()) + 3600
                }  # 1 hour from now
            except Exception:
                # something went wrong. Punt, we just won't serve this request
                # locally
                raise NotLocalError

            # Cache the thing
            cache(cPickle.dumps(mapping, 1), fileDir, fileName, "1")

        return mapping
Beispiel #13
0
 def _listPackages(self):
     """ Generates a list of objects by calling the function"""
     # Can't use the normal GETServer handler because there is no client
     # to auth. Instead this is something the Proxy has to be able to do,
     # so read the serverid and send that up.
     server = rpclib.Server(self.rhnParentXMLRPC, proxy=self.httpProxy,
                            username=self.httpProxyUsername, password=self.httpProxyPassword)
     if self.caChain:
         server.add_trusted_cert(self.caChain)
     # Versionless package listing from Server. This saves us from erroring
     # unnecessarily if the channel has changed since the kickstart mapping.
     # No problem, newer channel listings will work fine with kickstarts
     # unless they have removed the kernel or something, in which case it's
     # not supposed to work.
     # Worst case scenario is that we cache listing using an older version
     # than it actually is, and the next time we serve a file from the
     # regular Repository it'll get replace with the same info but newer
     # version in filename.
     return server.proxy.listAllPackagesKickstart(self.channelName,
                                                  self.systemId)
def get_uln_erratas(channel, proxy, suffix, arch, year):
    s = rpclib.Server(uri="https://linux-update.oracle.com/XMLRPC",
                      proxy="http://%s" % proxy)
    errataList = s.errata.getErrataByChannel(channel)
    sorted_errata = {}
    for errata in errataList:
        if re.search("-%s-" % year, errata["id"]) is not None:
            suffix_id = "%s%s" % (errata["id"], suffix)
            if not suffix_id in sorted_errata:
                sorted_errata[suffix_id] = {}
                sorted_errata[suffix_id]["packages"] = [
                    "%s-%s-%s.%s" % (errata["name"], errata["version"],
                                     errata["release"], arch)
                ]
                sorted_errata[suffix_id]["type"] = errata["type"]
                sorted_errata[suffix_id]["summary"] = errata["summary"]
                sorted_errata[suffix_id]["description"] = errata["description"]
            else:
                sorted_errata[suffix_id]["packages"].append(
                    "%s-%s-%s.%s" % (errata["name"], errata["version"],
                                     errata["release"], arch))
    return sorted_errata
Beispiel #15
0
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

from rhn import rpclib

#systemid_file = '/home/devel/misa/playpen/systemid-devel'
systemid_file = '/home/devel/misa/cvs/rhn/test/backend/checks/systemid-farm06'
server = "coyote.devel.redhat.com"
#server = "rhnxml.back-webdev.redhat.com"

s = rpclib.Server("http://%s/CONFIG-MANAGEMENT" % server)

files = [
    {
        'path': '/etc/motd',
        'file_contents':
        'This system will not work today\nCause I like it so\n',
        'delim_start': '{|',
        'delim_end': '|}',
        'file_stat': {
            'size': 1234,
            'mode': 0755,
            'user': '******',
            'group': 'misa',
        },
    },
def run_test(server_url, ca_cert):
    s = rpclib.Server(server_url)
    s.add_trusted_cert(ca_cert)

    status = s.applet.poll_status()
Beispiel #17
0
    def fix_connection(self, c):
        "After setting up the connection, do whatever else is necessary"

        # Setup XMLRPC server
        xmlrpc_params = self.build_rpclib_params(self._config_options)

        # Looking for a server we connected to jabberd on
        server_urls = self._config_options['server_url']
        for url in server_urls:
            if self._connected_jabber_server in url:
                xmlrpc_params['uri'] = url
                break

        server = rpclib.Server(**xmlrpc_params)
        self._xmlrpc_server = server

        client_ssl_cert = self._config_options['ssl_ca_cert']
        osa_ssl_cert = self._config_options['osa_ssl_cert'] or client_ssl_cert
        if osa_ssl_cert:
            server.add_trusted_cert(osa_ssl_cert)

        server.registration.welcome_message()

        server_capabilities = get_server_capability(server)
        if 'registration.register_osad' not in server_capabilities:
            raise Exception("Server does not support OSAD registration")

        self._systemid_file = self._config_options['systemid']
        self._systemid = open(self._systemid_file).read()

        current_timestamp = int(time.time())
        ret = server.registration.register_osad(
            self._systemid, {'client-timestamp': current_timestamp})

        #Bugzilla: 142067
        #If the server doesn't have push support. 'ret' won't have anything in it.
        if len(ret.keys()) < 1:
            raise jabber_lib.JabberConnectionError

        js = ret.get('jabber-server')
        if js not in self._jabber_servers:
            self._jabber_servers.append(js)

        server_timestamp = ret.get('server-timestamp')
        # Compute the time drift between the client and the server
        self._time_drift = server_timestamp - current_timestamp
        log_debug(2, "Time drift", self._time_drift)

        self._dispatchers = ret.get('dispatchers')
        self._client_name = ret.get('client-name')
        self._shared_key = ret.get('shared-key')
        log_debug(2, "Client name", self._client_name)
        log_debug(2, "Shared key", self._shared_key)

        c.set_config_options(self._config_options)
        c.client_id = self._client_name
        c.shared_key = self._shared_key
        c.time_drift = self._time_drift
        c._sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        c._sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE,
                           self._tcp_keepalive_timeout)
        c._sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT,
                           self._tcp_keepalive_count)

        # Update the jabber ID
        systemid = open(self._systemid_file).read()
        args = {
            'jabber-id': str(c.jid),
        }
        ret = self._xmlrpc_server.registration.register_osad_jid(
            systemid, args)

        c.set_dispatchers(self._dispatchers)

        c.subscribe_to_presence(self._dispatchers)
        # Signal presence to the jabber server
        c.send_presence()
        return c
Beispiel #18
0
 def _connect(self):
     if self._server is None:
         self._server = rpclib.Server(self._server_url)
     return self._server
Beispiel #19
0
#
# Copyright (c) 2008 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
from rhn import rpclib

s = rpclib.Server("http://coyote.devel.redhat.com/REDHAT-XMLRPC")

print s.actions.system_capabilities(1003485542)
Beispiel #20
0
import sys

sys.path.append('..')
from rhn import rpclib

SERVER = "xmlrpc.rhn.redhat.com"
HANDLER = "/XMLRPC"
PROXY = "proxy.example.com:8080"
system_id_file = '/etc/sysconfig/rhn/systemid'

if len(sys.argv) < 3:
    print "Non efficient cmd-line arguments! Provide at least server & proxy!"
    sys.exit(1)

try:
    SERVER = sys.argv[1]
    PROXY = sys.argv[2]
    system_id_file = sys.argv[3]
except:
    pass

SERVER_URL = "https://" + SERVER + HANDLER

systemid = open(system_id_file).read()

s = rpclib.Server(SERVER_URL, proxy=PROXY)

dict = s.up2date.login(systemid)

print "Test PASSES"
Beispiel #21
0
def getServer(uri, proxy=None, username=None, password=None, ca_chain=None):
    s = rpclib.Server(uri, proxy=proxy, username=username, password=password)
    if ca_chain:
        s.add_trusted_cert(ca_chain)
    return s
Beispiel #22
0
def getServer(refreshCallback=None):
    log = rhnLog.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 type(ca) == type(""):
    	ca = [ca]

    rhns_ca_certs = ca or ["%s/usr/share/rhn/RHNS-CA-CERT" % config.PREFIX]
    if cfg["enableProxy"]:
        proxyHost = rhnUtils.getProxySetting()
    else:
        proxyHost = None

    if hasSSL():
        serverUrl = cfg["serverURL"]
    else:
        serverUrl = cfg["noSSLServerURL"]

    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 os.environ.has_key(env):
            if not os.environ[env]:
                # sometimes unset
                continue
            lang = string.split(os.environ[env], ':')[0]
            lang = string.split(lang, '.')[0]
            break


    s = rpclib.Server(serverUrl, refreshCallback=refreshCallback,
                      proxy=proxyHost,
                      username=proxyUser,
                      password=proxyPassword)
    s.add_header("X-Up2date-Version", rhnUtils.version())

    if lang:
        s.setlang(lang)

    # require RHNS-CA-CERT file to be able to authenticate the SSL connections
    for rhns_ca_cert in rhns_ca_certs:
        if not os.access(rhns_ca_cert, os.R_OK):
            log.log_me("ERROR: can not find RHNS CA file: %s" % rhns_ca_cert)
            sys.exit(-1)

        # 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
Beispiel #23
0
#
# Copyright (c) 2008--2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
from rhn import rpclib

#server = "xmlrpc.rhn.redhat.com"
server = "coyote.devel.redhat.com"

s = rpclib.Server("http://%s/APPLET" % server)

# print s.applet.poll_status()
print((s.applet.poll_packages('2.1AS', 'i386')))
print((s.applet.poll_packages('8.0', 'i386')))
Beispiel #24
0
    def __init__(self, setup_network=1):
        Repository.__init__(self)
        # all this so needs to be in a seperate rhnConfig library,
        # shared by up2date, rhncfg*, etc.
        #
        # But, I digress.

        self.__server_url = self._local_config.get('server_url')

        # 6/29/05 wregglej 152388
        # server_list contains the list of servers to failover to.
        self.__server_list = self._local_config.get('server_list')

        # 6/29/05 wregglej 152388
        # Grab server_handler, which is different for rhncfg-client and rhncfg-manager
        # and is needed when failover occurs. During a failover, when the server object is
        # being set up to use a new satellite, the server_handler is added to the address so
        # the tool communicates with the correct xmlrpc handler.
        handler = self._local_config.get('server_handler')
        cap_handler = re.sub('[^/]+$', 'XMLRPC', handler)

        if not self.__server_url:
            raise cfg_exceptions.ConfigurationError(
                "Missing entry 'server_url' in the config files\n" \
                "Try running as root, or configure server_url as described in the configuration file"
                )

        log_debug(3, "server url", self.__server_url)
        self.__proxy_user = None
        self.__proxy_password = None
        self.__proxy_host = None

        self.__enable_proxy = self._local_config.get('enableProxy')
        self.__enable_proxy_auth = self._local_config.get('enableProxyAuth')

        if self.__enable_proxy:
            self.__proxy_host = self._local_config.get('httpProxy')

            if self.__enable_proxy_auth:
                self.__proxy_user = self._local_config.get('proxyUser')
                self.__proxy_password = self._local_config.get('proxyPassword')

        ca = self._local_config.get('sslCACert')
        if isinstance(ca, basestring):
            ca = [ca]

        ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"]

        # not sure if we need this or not...
        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

        if setup_network:
            # Fetch server capabilities - we need the /XMLRPC handler
            #t = list(utils.parse_url(self.__server_url))
            #t[2] = '/XMLRPC'
            #x_server_url = utils.unparse_url(t)

            # 6/29/05 wregglej 152388
            # Fetching the server capabilities involves using the /XMLRPC handler. It's
            # the only place that I know of that does that. The server_url and server_list
            # both need to have /XMLRPC on the ends, which is what _patch_uris() does by default.
            x_server_url = self._patch_uris(self.__server_url, cap_handler)
            if self.__server_list != None:
                x_server_list = self._patch_uris(self.__server_list,
                                                 cap_handler)
            else:
                x_server_list = None

            x_server = rpclib.Server(x_server_url,
                                     proxy=self.__proxy_host,
                                     username=self.__proxy_user,
                                     password=self.__proxy_password,
                                     server_list=x_server_list,
                                     rpc_handler="/XMLRPC")

            # Make a call to a function that can export the server's capabilities
            # without setting any state on the server side
            try:
                x_server.registration.welcome_message()
            except xmlrpclib.Fault:
                e = sys.exc_info()[1]
                sys.stderr.write("XML-RPC error while talking to %s:\n %s\n" %
                                 (self.__server_url, e))
                sys.exit(2)

            self._server_capabilities = get_server_capability(x_server)
            del x_server

        # 6/29/05 wregglej 152388
        # From here on out all communication should take place through the xmlrpc handler
        # that's appropriate for the tool being used. For rhncfg-client that's /CONFIG-MANAGEMENT.
        # For rhncfg-manager that's /CONFIG-MANAGEMENT-TOOL. No, I don't know the reasoning behind that.
        # First we need to patch the uris in server_list, to use the correct handler.
        self.__server_url = self._patch_uris(self.__server_url, handler)
        if self.__server_list != None:
            self.__server_list = self._patch_uris(self.__server_list, handler)
        else:
            self.__server_list = None

        self.server = rpclib.Server(self.__server_url,
                                    proxy=self.__proxy_host,
                                    username=self.__proxy_user,
                                    password=self.__proxy_password,
                                    server_list=self.__server_list,
                                    rpc_handler=handler)

        self._set_capabilities()
        self.server.set_transport_flags(transfer=Output.TRANSFER_BINARY,
                                        encoding=Output.ENCODE_GZIP)

        if lang:
            self.server.setlang(lang)

        for ca_cert in ca_certs:
            if not os.access(ca_cert, os.R_OK):
                raise cfg_exceptions.ConfigurationError(
                    "Can not find CA file: %s" % ca_cert)

            log_debug(3, "ca cert", ca_cert)
            # force the validation of the SSL cert
            self.server.add_trusted_cert(ca_cert)
#

import sys
sys.path.append('..')
from rhn import rpclib

if len(sys.argv) > 1:
    system_id_file = sys.argv[1]
else:
    system_id_file = '/etc/sysconfig/rhn/systemid'

systemid = open(system_id_file).read()
#server_url = "http://coyote.devel.redhat.com/XMLRPC"
server_url = "http://xmlrpc.rhn.webdev.redhat.com/XMLRPC"

s = rpclib.Server(server_url)
cookie = s.up2date.login(systemid)

gs = rpclib.GETServer(server_url, headers=cookie)
gs.set_transport_flags(allow_partial_content=1)

channel_name, channel_version = cookie['X-RHN-Auth-Channels'][0][:2]

package_list = gs.listPackages(channel_name, channel_version)

for p in package_list:
    if p[0] == 'python':
        break
pn, pv, pr, pe, pa = p[:5]
package_name = "%s-%s-%s.%s.rpm" % (pn, pv, pr, pa)