Exemplo n.º 1
0
	def setUp(self):
	
		print "setup"
		self.server = xmlrpclib.Server("http://localhost:7081",allow_none=True);
		self.dbname = ["testdb3","2003-04"]
		self.client_id = self.server.getConnection(self.dbname)
Exemplo n.º 2
0
import xmlrpclib, time, random

# Number of dimensions for hypercube
dim = 6

# Create an object to represent our server.
server_url = 'http://127.0.0.1:20738/RPC2'
server = xmlrpclib.Server(server_url)
G = server.ubigraph

G.clear()

# While we are building the graph, make everything invisible.
G.set_vertex_style_attribute(0, "visible", "false")
G.set_edge_style_attribute(0, "visible", "false")

# Default vertex styles
G.set_vertex_style_attribute(0, "shape", "sphere")
G.set_vertex_style_attribute(0, "color", "#F4FF85")
G.set_vertex_style_attribute(0, "size", "0.25")

activeVertex = G.new_vertex_style(0)
G.set_vertex_style_attribute(activeVertex, "color", "#FF4B30")

# Convert integer to binary, code by Antti Kaihola
bstr_pos = lambda n: n > 0 and bstr_pos(n >> 1) + str(n & 1) or ''
bstr_nonneg = lambda n: n > 0 and bstr_nonneg(n >> 1).lstrip('0') + str(
    n & 1) or '0'
bstr_sgn = lambda n: n < 0 and '-' + binarystr(-n) or n and bstr_sgn(
    n >> 1).lstrip('0') + str(n & 1) or '0'
bstr = lambda n, l=16: n < 0 and binarystr(
Exemplo n.º 3
0
# Client code

import xmlrpclib

server = xmlrpclib.Server('http://localhost:8000')
print server.chop_in_half('I am a confidant guy')
print server.repeat('Repetition is the key to learning!\n', 5)
print server._string('<= underscore')
print server.python_string.join(['I', 'like it!'], " don't ")
#print server._privateFunction() # Will throw an exception

oee = server.get_OEE_data()
uptime = oee['uptime']
print oee
print uptime
Exemplo n.º 4
0
#!/usr/bin/env python

import xmlrpclib
import sys

s = xmlrpclib.Server("http://localhost/")
sess = s.session.login_with_password("root", "xenroot")['Value']

pool = s.pool.get_all(sess)['Value'][0]
restrictions = s.pool.get_restrictions(sess, pool)['Value']

base_request = {
    'user_version': '1',
    'is_a_template': False,
    'affinity': '',
    'memory_static_max': '4',
    'memory_static_min': '1',
    'memory_dynamic_max': '3',
    'memory_dynamic_min': '2',
    'VCPUs_params': {},
    'VCPUs_max': '1',
    'VCPUs_at_startup': '1',
    'name_label': 'hello',
    'name_description': 'hi',
    'memory_target': '2',
    'actions_after_shutdown': 'destroy',
    'actions_after_reboot': 'restart',
    'actions_after_crash': 'destroy',
    'PV_bootloader': '',
    'PV_kernel': '',
    'PV_ramdisk': '',
Exemplo n.º 5
0
class CobblerCLI:

    def __init__(self):
        # Load server ip and ports from local config
        self.url_cobbler_api = utils.local_get_cobbler_api_url()
        self.url_cobbler_xmlrpc = utils.local_get_cobbler_xmlrpc_url()

        # FIXME: allow specifying other endpoints, and user+pass
        self.parser = optparse.OptionParser()
        self.remote = xmlrpclib.Server(self.url_cobbler_api)
        self.shared_secret = utils.get_shared_secret()

    def start_task(self, name, options):
        options = utils.strip_none(vars(options), omit_none=True)
        fn = getattr(self.remote, "background_%s" % name)
        return fn(options, self.token)

    def get_object_type(self, args):
        """
        If this is a CLI command about an object type, e.g. "cobbler distro add", return the type, like "distro"
        """
        if len(args) < 2:
            return None
        elif args[1] in OBJECT_TYPES:
            return args[1]
        return None

    def get_object_action(self, object_type, args):
        """
        If this is a CLI command about an object type, e.g. "cobbler distro add", return the action, like "add"
        """
        if object_type is None or len(args) < 3:
            return None
        if args[2] in OBJECT_ACTIONS_MAP[object_type]:
            return args[2]
        return None

    def get_direct_action(self, object_type, args):
        """
        If this is a general command, e.g. "cobbler hardlink", return the action, like "hardlink"
        """
        if object_type is not None:
            return None
        elif len(args) < 2:
            return None
        elif args[1] == "--help":
            return None
        elif args[1] == "--version":
            return "version"
        else:
            return args[1]

    def check_setup(self):
        """
        Detect permissions and service accessibility problems and provide
        nicer error messages for them.
        """

        s = xmlrpclib.Server(self.url_cobbler_xmlrpc)
        try:
            s.ping()
        except Exception, e:
            print >> sys.stderr, "cobblerd does not appear to be running/accessible: %s" % repr(e)
            sys.exit(411)

        s = xmlrpclib.Server(self.url_cobbler_api)
        try:
            s.ping()
        except:
            print >> sys.stderr, "httpd does not appear to be running and proxying cobbler, or SELinux is in the way. Original traceback:"
            traceback.print_exc()
            sys.exit(411)

        if not os.path.exists("/var/lib/cobbler/web.ss"):
            print >> sys.stderr, "Missing login credentials file.  Has cobblerd failed to start?"
            sys.exit(411)

        if not os.access("/var/lib/cobbler/web.ss", os.R_OK):
            print >> sys.stderr, "User cannot run command line, need read access to /var/lib/cobbler/web.ss"
            sys.exit(411)
Exemplo n.º 6
0
def main():

    # Get the options
    options = parse_args()
    # read the config
    if options.cfg_file:
        config = ConfigParser.ConfigParser()
        config.read (options.cfg_file)
        if options.spw_server is None:
            options.spw_server = config.get ('Spacewalk', 'spw_server')
        if options.spw_user is None:
            options.spw_user = config.get ('Spacewalk', 'spw_user')
        if options.spw_pass is None:
            options.spw_pass = config.get ('Spacewalk', 'spw_pass')
    else:
        #ask for username and password if emtpy
        while str(options.spw_user) == 'None' or '': options.spw_user = raw_input("Spacewalk Username: "******"Spacewalk Password: "******"Channel not given, aborting"
        sys.exit(2)

    spacewalk = xmlrpclib.Server("https://%s/rpc/api" % options.spw_server, verbose=0, allow_none=True)
    spacekey = spacewalk.auth.login(options.spw_user, options.spw_pass)

    to_delete=[]
    to_delete_ids=[]
    # get all packages
    if options.wo_channel is None and options.lucene is None and options.all_channel is None:
        print "Getting all packages"
        allpkgs = spacewalk.channel.software.listAllPackages(spacekey, options.channel)
        print " - Amount: %d" % len(allpkgs)
        # get newest packages
        print "Getting newest packages"
        newpkgs = spacewalk.channel.software.listLatestPackages(spacekey, options.channel)
        print " - Amount: %d" % len(newpkgs)
        for pkg in allpkgs:
            if not cmp_dictarray(newpkgs, pkg['id']):
                print "Marked:  %s-%s-%s (id %s)" % (pkg['name'], pkg['version'], pkg['release'], pkg['id'])
                to_delete.append(pkg)
                to_delete_ids.append(pkg['id'])
        print "Removing packages from channel..."

    if options.all_channel is not None:
        print "Getting all channels"
        allchannels = spacewalk.channel.listAllChannels(spacekey)
        print " - Amount: %d" % len(allchannels)
        for chan in allchannels:
            print "Getting all packages from %s" % chan['label']
            allpkgs = spacewalk.channel.software.listAllPackages(spacekey, chan['label'])
            print " - Amount: %d" % len(allpkgs)
            # get newest packages
            print "Getting newest packages"
            newpkgs = spacewalk.channel.software.listLatestPackages(spacekey, chan['label'])
            print " - Amount: %d" % len(newpkgs)
            for pkg in allpkgs:
                if not cmp_dictarray(newpkgs, pkg['id']):
                    print "Marked:  %s-%s-%s (id %s)" % (pkg['name'], pkg['version'], pkg['release'], pkg['id'])
                    to_delete.append(pkg)
                    to_delete_ids.append(pkg['id'])
        print "Removing packages from all channels..."

    if options.wo_channel is not None:
        print "Getting all packages without channel"
        to_delete = spacewalk.channel.software.listPackagesWithoutChannel(spacekey)

    if options.lucene is not None:
        print "Getting all packages which match %s" % options.lucene
        to_delete = spacewalk.packages.search.advanced(spacekey, options.lucene)

    if options.max:
        if len(to_delete) > options.max:
            to_delete = to_delete[:options.max]
        if len(to_delete_ids) > options.max:
            to_delete_ids = to_delete_ids[:options.max]


    print "Packages to remove: %s" % len(to_delete)

    if len(to_delete) > 0:
        if options.dryrun is None:
            if options.wo_channel is None and options.all_channel is None:
                print "Removing %d packages from channel %s" % (len(to_delete_ids), options.channel)
                ret = spacewalk.channel.software.removePackages(spacekey, options.channel, to_delete_ids)
            elif options.all_channel is not None:
                print "Removing %d packages from channel %s" % (len(to_delete_ids), chan['label'])
                ret = spacewalk.channel.software.removePackages(spacekey, chan['label'], to_delete_ids)
        elif options.wo_channel is None and options.all_channel is None:
            print "Dryrun: Removing %d packages from channel %s" % (len(to_delete_ids), options.channel)
        print "Deleting packages from spacewalk (if packages could not be removed they are maybe in another channel too)"
        for pkg in to_delete:
            if options.dryrun is not None:
                print "Dryrun: - Delete package %s-%s-%s (ID: %s)" % (pkg['name'], pkg['version'], pkg['release'], pkg['id'])
            else:
                print "Deleting package %s-%s-%s (ID: %s)" % (pkg['name'], pkg['version'], pkg['release'],pkg['id'])
                try:
                    ret = spacewalk.packages.removePackage(spacekey, pkg['id'])
                except:
                    print "  - Could not delete package from Spacewalk"
                if ret != 1:
                    print " - Could not delete package %s-%s-%s (ID: %s)" % (pkg['name'], pkg['version'], pkg['release'],pkg['id'])
Exemplo n.º 7
0
    def get(self, name, imdb, season, episode):
        try:
            if not control.setting('subtitles') == 'true': raise Exception()


            langDict = {'Afrikaans': 'afr', 'Albanian': 'alb', 'Arabic': 'ara', 'Armenian': 'arm', 'Basque': 'baq', 'Bengali': 'ben', 'Bosnian': 'bos', 'Breton': 'bre', 'Bulgarian': 'bul', 'Burmese': 'bur', 'Catalan': 'cat', 'Chinese': 'chi', 'Croatian': 'hrv', 'Czech': 'cze', 'Danish': 'dan', 'Dutch': 'dut', 'English': 'eng', 'Esperanto': 'epo', 'Estonian': 'est', 'Finnish': 'fin', 'French': 'fre', 'Galician': 'glg', 'Georgian': 'geo', 'German': 'ger', 'Greek': 'ell', 'Hebrew': 'heb', 'Hindi': 'hin', 'Hungarian': 'hun', 'Icelandic': 'ice', 'Indonesian': 'ind', 'Italian': 'ita', 'Japanese': 'jpn', 'Kazakh': 'kaz', 'Khmer': 'khm', 'Korean': 'kor', 'Latvian': 'lav', 'Lithuanian': 'lit', 'Luxembourgish': 'ltz', 'Macedonian': 'mac', 'Malay': 'may', 'Malayalam': 'mal', 'Manipuri': 'mni', 'Mongolian': 'mon', 'Montenegrin': 'mne', 'Norwegian': 'nor', 'Occitan': 'oci', 'Persian': 'per', 'Polish': 'pol', 'Portuguese': 'por,pob', 'Portuguese(Brazil)': 'pob,por', 'Romanian': 'rum', 'Russian': 'rus', 'Serbian': 'scc', 'Sinhalese': 'sin', 'Slovak': 'slo', 'Slovenian': 'slv', 'Spanish': 'spa', 'Swahili': 'swa', 'Swedish': 'swe', 'Syriac': 'syr', 'Tagalog': 'tgl', 'Tamil': 'tam', 'Telugu': 'tel', 'Thai': 'tha', 'Turkish': 'tur', 'Ukrainian': 'ukr', 'Urdu': 'urd'}

            codePageDict = {'ara': 'cp1256', 'ar': 'cp1256', 'ell': 'cp1253', 'el': 'cp1253', 'heb': 'cp1255', 'he': 'cp1255', 'tur': 'cp1254', 'tr': 'cp1254', 'rus': 'cp1251', 'ru': 'cp1251'}

            quality = ['bluray', 'hdrip', 'brrip', 'bdrip', 'dvdrip', 'webrip', 'hdtv']


            langs = []
            try:
                try: langs = langDict[control.setting('subtitles.lang.1')].split(',')
                except: langs.append(langDict[control.setting('subtitles.lang.1')])
            except: pass
            try:
                try: langs = langs + langDict[control.setting('subtitles.lang.2')].split(',')
                except: langs.append(langDict[control.setting('subtitles.lang.2')])
            except: pass

            try: subLang = xbmc.Player().getSubtitles()
            except: subLang = ''
            if subLang == langs[0]: raise Exception()

            server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc', verbose=0)
            token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')['token']

            sublanguageid = ','.join(langs) ; imdbid = re.sub('[^0-9]', '', imdb)

            if not (season == None or episode == None):
                result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid, 'season': season, 'episode': episode}])['data']
                fmt = ['hdtv']
            else:
                result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid}])['data']
                try: vidPath = xbmc.Player().getPlayingFile()
                except: vidPath = ''
                fmt = re.split('\.|\(|\)|\[|\]|\s|\-', vidPath)
                fmt = [i.lower() for i in fmt]
                fmt = [i for i in fmt if i in quality]

            filter = []
            result = [i for i in result if i['SubSumCD'] == '1']

            for lang in langs:
                filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in fmt)]
                filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in quality)]
                filter += [i for i in result if i['SubLanguageID'] == lang]

            try: lang = xbmc.convertLanguage(filter[0]['SubLanguageID'], xbmc.ISO_639_1)
            except: lang = filter[0]['SubLanguageID']

            content = [filter[0]['IDSubtitleFile'],]
            content = server.DownloadSubtitles(token, content)
            content = base64.b64decode(content['data'][0]['data'])
            content = str(zlib.decompressobj(16+zlib.MAX_WBITS).decompress(content))

            subtitle = xbmc.translatePath('special://temp/')
            subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang)

            codepage = codePageDict.get(lang, '')
            if codepage and control.setting('subtitles.utf') == 'true':
                try:
                    content_encoded = codecs.decode(content, codepage)
                    content = codecs.encode(content_encoded, 'utf-8')
                except:
                    pass

            file = control.openFile(subtitle, 'w')
            file.write(str(content))
            file.close()

            xbmc.sleep(1000)
            xbmc.Player().setSubtitles(subtitle)
        except:
            pass
Exemplo n.º 8
0
 def sendrpc(self, msg):
     srv = xmlrpclib.Server(self.ciaurl)
     res = srv.hub.deliver(msg)
     if res is not True:
         raise util.Abort(
             _('%s returned an error: %s') % (self.ciaurl, res))
######################################################################

import sys
import xmlrpclib
import shlex

try:
    import json
except:
    import simplejson as json

# NOTE -- this file assumes Ansible is being accessed FROM the cobbler
# server, so it does not attempt to login with a username and password.
# this will be addressed in a future version of this script.

conn = xmlrpclib.Server("http://127.0.0.1/cobbler_api", allow_none=True)

###################################################
# executed with no parameters, return the list of
# all groups and hosts

if len(sys.argv) == 1:

    systems = conn.get_item_names('system')
    groups = {'ungrouped': []}

    for system in systems:

        data = conn.get_blended_data(None, system)

        dns_name = None
class ProvisionInterface(cmd.Cmd):
    """
        The following interface must be supported by the XMLRPC server
        running in your ATM Backend.
        ------------------------------------------------------------------------
        function:
            ready_for_hsm - check if atm is ready for hsm to be connected

        args:
            None

        returns:
            bool: True for success, False otherwise.
        ------------------------------------------------------------------------
        function:
            hsm_connected - check if hsm is connected to the atm

        args:
            None

        returns:
            bool: True for success, False otherwise.
        ------------------------------------------------------------------------
        function:
            card_connected - check if a card is connected to the atm

        args:
            None

        returns:
            bool: True for success, False otherwise.
        ------------------------------------------------------------------------
        function:
            provision_card

        args:
            param1 (xmlrpclib base64 - max length 16384 bytes):
                                            Material used to provision card
            param2 (string - required length 8, allowable characters: 0-9):
                                            Pin used to provision card

        returns:
            bool: True for success, False otherwise.
        ------------------------------------------------------------------------
        function:
            provision_atm

        args:
            param1 (xmlrpclib base64 - max length 16384 bytes):
                                            Material used to provision atm
            param2 (string[] - array max length 128, bill string length 16):
                                            Array of bills to provision atm with

        returns:
            bool: True for success, False otherwise.
        ------------------------------------------------------------------------
    """

    intro = 'Welcome to the Provision Client, type help or ? to list commands.\n'
    prompt = 'provision$ '
    atm = xmlrpclib.Server('http://' + HOST + ':' + PORT)

    def do_ready_for_hsm(self, args):
        """hello"""
        try:
            print self.atm.ready_for_hsm()
        except socket.error:
            print 'Error connecting to ATM'
        except:
            print '**** RECEIVED ERROR ****'
            print traceback.format_exc()

    def do_hsm_connected(self, args):
        """hsm_connected"""
        try:
            print self.atm.hsm_connected()
        except socket.error:
            print 'Error connecting to ATM'
        except:
            print '**** RECEIVED ERROR ****'
            print traceback.format_exc()

    def do_card_connected(self, args):
        """card_connected"""
        try:
            print self.atm.card_connected()
        except socket.error:
            print 'Error connecting to ATM'
        except:
            print '**** RECEIVED ERROR ****'
            print traceback.format_exc()

    def do_provision_card(self, args):
        'provision_card <card provision material filename> <pin>'

        try:
            filename = args.split(' ')[0]
            with open(filename) as fp:
                card_provision_material = xmlrpclib.Binary(
                    fp.read().strip(" \n\r"))
            assert len(
                card_provision_material.data) <= PROVISION_MATERIAL_MAX_SIZE
            pin = args.split(' ')[1].strip(" \n\r")
            print "PIN: " + pin
            assert len(pin) == REQUIRED_PIN_LENGTH
            assert pin.isdigit()
            print self.atm.provision_card(card_provision_material, pin)
        except socket.error:
            print 'Error connecting to ATM'
        except IndexError:
            print 'Usage: provision_card <card provision material filename> <pin>'
        except IOError:
            print traceback.format_exc()
            print(traceback.format_exc().splitlines()[-1])
        except:
            print '**** RECEIVED ERROR ****'
            print traceback.format_exc()

    def do_provision_atm(self, args):
        'provision_atm <atm provision material> <billfile name>'
        try:
            provision_material_filename = args.split(' ')[0]
            with open(provision_material_filename) as fp:
                atm_provision_material = xmlrpclib.Binary(
                    fp.read().strip(" \n\r"))
            assert len(
                atm_provision_material.data) < PROVISION_MATERIAL_MAX_SIZE

            billfile_name = args.split(' ')[1]
            with open(billfile_name) as fp:
                bill_array = fp.readlines()
            print bill_array
            assert all(
                len(bill.strip(" \n\r")) <= BILL_MAX_SIZE
                for bill in bill_array)

            print self.atm.provision_atm(atm_provision_material, bill_array)
        except socket.error:
            print 'Error connecting to ATM'
        except IndexError:
            print 'Usage: provision_atm <atm provision material> <bill file>'
        except IOError:
            print traceback.format_exc()
            print(traceback.format_exc().splitlines()[-1])
        except:
            print '**** RECEIVED ERROR ****'
            print traceback.format_exc()

    def do_exit(self, args):
        """exit"""
        return 1

    def do_quit(self, args):
        """quit"""
        return 1
 def __init__(self, devKey="put your key here"):
     self.server = xmlrpclib.Server(
         'http://put your testlink URL|IP here/lib/api/xmlrpc.php')
     self.devKey = devKey
Exemplo n.º 12
0
def do_login(self, args):
    (args, _options) = parse_arguments(args)

    # logout before logging in again
    if len(self.session):
        logging.warning('You are already logged in')
        return True

    # an argument passed to the function get precedence
    if len(args) == 2:
        server = args[1]
    else:
        # use the server we were already using
        server = self.config['server']

    # bail out if not server was given
    if not server:
        logging.warning('No server specified')
        return False

    # load the server-specific configuration
    self.load_config_section(server)

    # an argument passed to the function get precedence
    if len(args):
        username = args[0]
    elif self.config.has_key('username'):
        # use the username from before
        username = self.config['username']
    elif self.options.username:
        # use the username from before
        username = self.options.username
    else:
        username = ''

    # set the protocol
    if self.config.has_key('nossl') and self.config['nossl']:
        proto = 'http'
    else:
        proto = 'https'

    server_url = '%s://%s/rpc/api' % (proto, server)

    # this will enable spewing out all client/server traffic
    verbose_xmlrpc = False
    if self.options.debug > 1:
        verbose_xmlrpc = True

    # connect to the server
    logging.debug('Connecting to %s', server_url)
    self.client = xmlrpclib.Server(server_url, verbose=verbose_xmlrpc)

    # check the API to verify connectivity
    try:
        self.api_version = self.client.api.getVersion()
        logging.debug('Server API Version = %s', self.api_version)
    except xmlrpclib.Fault, e:
        if self.options.debug > 0:
            logging.exception(e)

        logging.error('Failed to connect to %s', server_url)
        self.client = None
        return False
Exemplo n.º 13
0
 def __init__(self, logger, address, user, password):
     StorageManager.__init__(self, logger)
     self.xen = xmlrpclib.Server(address)
Exemplo n.º 14
0
    def get_event_list_from_xmlrpc(self, timestamp):

        ## on test pour voir si on est en dynamique, si c'est le cas, on met à jour la valeur du timestamp
        if timestamp != 0:
            self.parameters[self.timestamp] = int(timestamp)

        ####on cree l'identification
        auth = {}
        if self.data_access_options["authType"] == "anonymous":
            auth["AuthMethod"] = "anonymous"

        elif self.data_access_options["authType"] == "password":
            auth["AuthMethod"] = "password"
            auth["Username"] = self.data_access_options["Username"]
            auth["AuthString"] = self.data_access_options["AuthString"]

        elif self.data_access_options["authType"] == "session":
            auth["AuthMethod"] = "session"
            auth["session"] = self.data_access_options["session"]

        elif self.data_access_options["authType"] == "gpg":
            auth["AuthMethod"] = "gpg"
            auth["name"] = self.data_access_options["name"]
            auth["signature"] = self.data_access_options["signature"]

        srv = xmlrpclib.Server(self.data_access_options["server"],
                               allow_none=1)

        ##On gère en fonction des methodes

        if self.methode == "GetSites":
            self.geo_methode = "site_id"
            try:
                if len(self.return_fields) == 0:
                    data = srv.GetSites(auth, self.parameters)
                else:
                    data = srv.GetSites(auth, self.parameters,
                                        self.return_fields)
            except:
                return self.parameters
        else:
            return 2

        ###on recupère la liste des localisation

        ##si il y a moins de 8 resultats, on recupère seulement la localisation de ceux-ci
        list = []
        try:
            sites_id = srv.GetSites(auth, {},
                                    ["site_id", "latitude", "longitude"])
        except:
            return 3
        try:
            for i in data:
                for j in sites_id:
                    if i["site_id"] == j["site_id"]:
                        try:
                            pos = [{
                                "latitude": j["latitude"],
                                "longitude": j["longitude"]
                            }]
                        except:
                            return 4
                        i["ape_position"] = pos
                        list.append(i)
        except:
            return 5
        return list
Exemplo n.º 15
0
#!/usr/bin/env python
import xmlrpclib
server = xmlrpclib.Server(
    'http://*****:*****@localhost/zidestore/so/awilliam/')
print server.zogi.getTasksById(13530, 65535)
Exemplo n.º 16
0
#!/usr/bin/env python
import xmlrpclib, pprint
server = xmlrpclib.Server('http://*****:*****@192.168.3.164/zidestore/so/root/')
#print "archived"
#pprint.pprint(server.zogi.searchForObjects('Task', "archived" ,65535))
print "todo"
pprint.pprint(server.zogi.searchForObjects('Task', "todo", 19))
#print "delegated"
#pprint.pprint(server.zogi.searchForObjects('Task', "delegated" ,65535))
Exemplo n.º 17
0
def GetServerConnection():
    return xmlrpclib.Server('http://localhost:8000')
Exemplo n.º 18
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    opts = parse_args(argv)[0]

    gram.am.gram.config.initialize(opts.config_file)

    # If the port isn't set explicitly, use defaults from config
    if not opts.v3_port:
        opts.v3_port = gram.am.gram.config.gram_am_port
    if not opts.v2_port:
        opts.v2_port = gram.am.gram.config.gram_am_v2_port
    if not opts.rpi_port:
        opts.rpi_port = gram.am.gram.config.gram_am_rpi_port

    level = logging.INFO
    if opts.debug:
        level = logging.DEBUG
    logging.basicConfig(level=level, format='%(asctime)s %(message)s')

    # Read in config file options, command line gets priority
    optspath = None
    if not opts.configfile is None:
        optspath = os.path.expanduser(opts.configfile)

    config = read_config(optspath)

    for (key, val) in config['aggregate_manager'].items():
        if hasattr(opts, key) and getattr(opts, key) is None:
            setattr(opts, key, val)
        if not hasattr(opts, key):
            setattr(opts, key, val)
    if getattr(opts, 'rootcadir') is None:
        setattr(opts, 'rootcadir', config['global']['rootcadir'])

    if opts.rootcadir is None:
        sys.exit(
            'Missing path to trusted root certificate directory (-r argument)')

    certfile = getAbsPath(opts.certfile)
    keyfile = getAbsPath(opts.keyfile)
    if not os.path.exists(certfile):
        sys.exit("Aggregate certfile %s doesn't exist" % certfile)

    if not os.path.exists(keyfile):
        sys.exit("Aggregate keyfile %s doesn't exist" % keyfile)

# Removed because OpenStack is not required for pi usage
#  # Check if quantum is running, if not, then take a nap
#  command_str = '%s net-list' % gram.am.gram.config.network_type
#  command = command_str.split()
#  ready = 0
#  while(not ready):
#      try :
#          subprocess.check_output(command)
#          ready = 1
#          logging.getLogger('gram-am').info(' Ready to start GRAM')
#      except :
#          logging.getLogger('gram-am').error('Error executing command %s' % command)
#          time.sleep(15)

    gram.am.gram.config.snapshot_dir = opts.snapshot_dir
    gram.am.gram.config.recover_from_snapshot = opts.recover_from_snapshot
    gram.am.gram.config.recover_from_most_recent_snapshot = \
        opts.recover_from_most_recent_snapshot
    gram.am.gram.config.snapshot_maintain_limit = opts.snapshot_maintain_limit

    # Instantiate an argument guard that will reject or modify
    # arguments and options provided to calls
    argument_guard = None
    if hasattr(opts, 'argument_guard'):
        argument_guard = getInstanceFromClassname(opts.argument_guard)

# Instantiate authorizer from 'authorizer' config argument
# By default, use the SFA authorizer
    if hasattr(opts, 'authorizer'):
        authorizer_classname = opts.authorizer
    else:
        authorizer_classname = "gcf.geni.auth.sfa_authorizer.SFA_Authorizer"
    authorizer = getInstanceFromClassname(authorizer_classname, opts.rootcadir,
                                          opts, argument_guard)

    # Use XMLRPC authorizer if opt.remote_authorizer is set
    if hasattr(opts, 'remote_authorizer'):
        import xmlrpclib
        authorizer = xmlrpclib.Server(opts.remote_authorizer)

    # Instantiate resource manager from 'authorizer_resource_manager'
    # config argument. Default = None
    resource_manager = None
    if hasattr(opts, 'authorizer_resource_manager'):
        resource_manager = \
            getInstanceFromClassname(opts.authorizer_resource_manager)

    # rootcadir is  dir of multiple certificates
    delegate = gcf.geni.ReferenceAggregateManager(getAbsPath(opts.rootcadir))

    # here rootcadir is supposed to be a single file with multiple
    # certs possibly concatenated together
    comboCertsFile = gcf.geni.CredentialVerifier.getCAsFileFromDir(
        getAbsPath(opts.rootcadir))

    server_url = "https://%s:%d/" % (opts.host, int(opts.v3_port))
    GRAM = gram.am.am3.GramReferenceAggregateManager(
        getAbsPath(opts.rootcadir), config['global']['base_name'], certfile,
        server_url)

    if opts.api_version == 1:
        msg = "Version 1 of AM API unsopported in GRAM"
        sys.exit(msg)
    #elif opts.api_version == 2:
    ams_v2 = gram.am.gram_am2.GramAggregateManagerServer(
        (opts.host, int(opts.v2_port)),
        keyfile=keyfile,
        certfile=certfile,
        trust_roots_dir=getAbsPath(opts.rootcadir),
        ca_certs=comboCertsFile,
        base_name=config['global']['base_name'],
        authorizer=authorizer,
        resource_manager=resource_manager,
        GRAM=GRAM)
    #elif opts.api_version == 3:
    ams_v3 = gram.am.am3.GramAggregateManagerServer(
        (opts.host, int(opts.v3_port)),
        keyfile=keyfile,
        certfile=certfile,
        trust_roots_dir=getAbsPath(opts.rootcadir),
        ca_certs=comboCertsFile,
        base_name=config['global']['base_name'],
        authorizer=authorizer,
        resource_manager=resource_manager,
        GRAM=GRAM)

    ams_rpi_v3 = gram.am.rpiv3.GramAggregateManagerServer(
        (opts.host, int(opts.rpi_port)),
        keyfile=keyfile,
        certfile=certfile,
        trust_roots_dir=getAbsPath(opts.rootcadir),
        ca_certs=comboCertsFile,
        base_name=config['global']['base_name'],
        authorizer=authorizer,
        resource_manager=resource_manager,
        GRAM=GRAM)
    #else:
    #    msg = "Unknown API version: %d. Valid choices are \"1\", \"2\", or \"3\""
    #    sys.exit(msg % (opts.api_version))

    logging.getLogger('gcf-am').info('GENI AM 3 Listening on port %s...' %
                                     (opts.v3_port))
    logging.getLogger('gcf-am').info('GENI AM 2 Listening on port %s...' %
                                     (opts.v2_port))
    logging.getLogger('gcf-am').info('GENI AM PI Listening on port %s...' %
                                     (opts.rpi_port))

    thread = threading.Thread(target=ams_v2.serve_forever, args=())
    thread.start()

    thread = threading.Thread(target=ams_rpi_v3.serve_forever, args=())
    thread.start()

    ams_v3.serve_forever()
Exemplo n.º 19
0
    urlprefix = urlprefix % globals()

    # The script wants a reference to head followed by the list of
    # commit ID to report about.
    if len(arguments) == 0:
        refname = do("git symbolic-ref HEAD 2>/dev/null")
        merges = [do("git rev-parse HEAD")]
    else:
        refname = arguments[0]
        merges = arguments[1:]

    if notify:
        if xmlrpc:
            import xmlrpclib
            server = xmlrpclib.Server('http://cia.navi.cx/RPC2');
        else:
            import smtplib
            server = smtplib.SMTP('localhost')

    for merged in merges:
        message = report(refname, merged, xmlrpc)
        if not notify:
            print message
        elif xmlrpc:
            server.hub.deliver(message)
        else:
            server.sendmail(fromaddr, [toaddr], message)

    if notify:
        if not xmlrpc:
Exemplo n.º 20
0
def get_client(url):
    context = None
    client = xmlrpclib.Server(url, verbose=0, context=context)
    return client
 def reconnect(self):
     """re-establishes the connection"""
     self.client = xmlrpclib.Server("https://%s/rpc/api" % self.host)
     self.key = self.client.auth.login(self.username, self.__password)
     pass
Exemplo n.º 22
0
# Read the config file and convert to list of dictionaries
cparser = ConfigParser.RawConfigParser()
propsFile = cparser.read(options.propFileName)
dprops = dict(cparser.items('properties'))
param = [ dprops ]

print "Passing parameters: "
for x in dprops:
    print x +" = " + dprops[x]

# Create an object to represent our server.
server_url = options.server;
credentials = []

if server_url.startswith('https://'):
    if options.cert == None or options.privateKey == None:
        print "For using secure (https) transport, you must specify the path to your certificate and private key"
        parser.print_help()
        exit(-1)
    # create secure transport with client cert
    transport = SafeTransportWithCert(options.cert, options.privateKey)
    server = xmlrpclib.Server(server_url, transport=transport)
else:
    server = xmlrpclib.Server(server_url)

# Call the server and get our result.
print "Issuing modify " + options.modifySubcommand + " subcommand for reservation ... \n"
result = server.orca.modifySliver(options.sliceID, options.reservation, credentials, options.modifySubcommand, param)
print result
Exemplo n.º 23
0
 def __init__(self, url):
     """`url` to server"""
     self.url = url
     self.srvr = xmlrpclib.Server(url)
     self.system = self.srvr.system
 def __init__(self, url):
     self.rpc = xmlrpclib.Server(url)
     self.aes = Security("HARSHANOOKA")
Exemplo n.º 25
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
# import ssl
import xmlrpclib

from pprint import pprint

# use the .inspecrc file in this directory
MANAGER_URL = os.environ['MANAGER_URL']
MANAGER_LOGIN = os.environ['MANAGER_LOGIN']
MANAGER_PASSWORD = os.environ['MANAGER_PASSWORD']

client = xmlrpclib.Server(MANAGER_URL, verbose=0)
# for ssl
# context=ssl._create_unverified_context()
# client = xmlrpclib.Server(MANAGER_URL, verbose=0, context=context)

key = client.auth.login(MANAGER_LOGIN, MANAGER_PASSWORD)
userlist = client.user.list_users(key)
pprint(userlist)

sys_list = client.system.listActiveSystems(key)
pprint(sys_list)

detailsfor = [sys['id'] for sys in sys_list]
sys_list = client.system.listActiveSystemsDetails(key, detailsfor)
pprint(sys_list)
Exemplo n.º 26
0
def create_wordpress_via_api(notes, mp3_file, ogg_file, mp3_url, ogg_url,
                             audio_metadata, show_id, forum_link_text,
                             post_link_text, discourse_link, header_img_data,
                             requested_categories, youtube_link):
    # First, get audio duration and file size
    global DRY_RUN
    if DRY_RUN:
        print "Using fake data for WordPress post"
        duration_sec = 3601
        duration_min = duration_sec / 60
        duration_m = int(duration_min)
        duration_s = int((duration_min - duration_m) * 60)
        duration = "%s:%02d" % (duration_m, duration_s)
        ogg_size = 50000000
        mp3_size = 60000000
    else:
        aud = MP3(mp3_file)
        duration_sec = aud.info.length
        duration_min = duration_sec / 60
        duration_m = int(duration_min)
        duration_s = int((duration_min - duration_m) * 60)
        duration = "%s:%02d" % (duration_m, duration_s)
        ogg_size = os.path.getsize(ogg_file)
        mp3_size = os.path.getsize(mp3_file)

    # Now, assemble all our data
    post_contents = {
        "post_type":
        "post",
        "post_title":
        "%s: %s" % (show_id, audio_metadata["bv_override_title"]),
        "post_author":
        WP_AUTHOR_ID,
        "post_content":
        notes.replace(
            "[forum_post_link]",
            u'<a class="community-button" href="%s">%s</a>' %
            (discourse_link, forum_link_text)).replace(
                '[display_podcast]', youtube_link + '\n[display_podcast]'),
        "post_status":
        "draft",
        "comment_status":
        "closed",
        "post_name":
        show_id
    }
    if LIVE:
        post_contents["post_status"] = "publish"
    podcast_files = [{
        "title": "BV %s mp3" % show_id,
        "URI": mp3_url,
        "size": mp3_size,
        "duration": duration,
        "type": "audio_mp3"
    }, {
        "title": "BV %s ogg" % show_id,
        "URI": ogg_url,
        "size": ogg_size,
        "duration": duration,
        "type": "audio_ogg"
    }]

    generic_post_data = {
        'dimensionW': 0,
        'atom': 'on',
        'previewImage':
        'http://badvoltage.org/wp-content/plugins/podpress/images/vpreview_center.png',
        'rss': 'on',
        'dimensionH': 0
    }

    podcast_file_data = []
    for p in podcast_files:
        d = {}
        d.update(generic_post_data)
        d.update(p)
        # set Include In: RSS on for mp3s, off for everything else
        if p['type'] != 'audio_mp3': del d['rss']
        podcast_file_data.append(d)

    s = xmlrpclib.Server("http://badvoltage.org/xmlrpc.php")
    print "Fetching the taxonomy list to put this post in 'Shows'..."
    categories_as_term_list = [
        x for x in s.wp.getTerms(WP_BLOG_ID, WP_AUTHOR_USER, WP_AUTHOR_PASS,
                                 'category')
        if x["name"] in requested_categories
    ]
    post_contents["terms"] = {
        "category": [x["term_id"] for x in categories_as_term_list]
    }

    if not LIVE:
        print "*** This is not running on the live server, so skipping the WP post"
        print "The WP post data would have been"
        print post_contents
        return

    sio = StringIO.StringIO()
    header_img_data.save(sio, format="JPEG")
    img_data = {
        "name": "img_%s.jpg" % (show_id, ),
        "type": "image/jpeg",
        "bits": xmlrpclib.Binary(sio.getvalue()),
        "overwrite": True
    }

    print "Uploading image to WordPress..."
    image_upload = s.wp.uploadFile(WP_BLOG_ID, WP_AUTHOR_USER, WP_AUTHOR_PASS,
                                   img_data)
    print "Creating a post on badvoltage.org..."
    post_contents["post_thumbnail"] = image_upload["id"]
    postid = s.wp.newPost(WP_BLOG_ID, WP_AUTHOR_USER, WP_AUTHOR_PASS,
                          post_contents)
    print "...and adding podcast media to it..."
    s.podPress.setPostData(postid, podcast_file_data)
    print "...done."
Exemplo n.º 27
0
def get_client(config):
    return xmlrpclib.Server('http://arg_unused',
                            transport=UnixStreamTransport(config['unix']))
Exemplo n.º 28
0
        # Initialize the main analyzer class.
        analyzer = Analyzer()

        # Run it and wait for the response.
        success = analyzer.run()

    # This is not likely to happen.
    except KeyboardInterrupt:
        error = "Keyboard Interrupt"

    # If the analysis process encountered a critical error, it will raise a
    # CuckooError exception, which will force the termination of the analysis.
    # Notify the agent of the failure. Also catch unexpected exceptions.
    except Exception as e:
        # Store the error.
        error_exc = traceback.format_exc()
        error = str(e)

        # Just to be paranoid.
        if len(log.handlers):
            log.exception(error_exc)
        else:
            sys.stderr.write("{0}\n".format(error_exc))

    # Once the analysis is completed or terminated for any reason, we report
    # back to the agent, notifying that it can report back to the host.
    finally:
        # Establish connection with the agent XMLRPC server.
        server = xmlrpclib.Server("http://127.0.0.1:8000")
        server.complete(success, error, PATHS["root"])
Exemplo n.º 29
0
    def get(self, key):
        if key[-4:] == "meta" or key[-10:] == "list_nodes":
            print "entering meta get"
            number = self.meta_server
            port = 'http://127.0.0.1:' + str(number)
            key = self.path + "&&" + key
            rpc = xmlrpclib.Server(port)
            res = rpc.get(Binary(key))
            if "value" in res:
                return pickle.loads(res["value"].data)
            else:
                return None
        else:

            print "entering into get function"
            key = self.path + "&&" + key
            Qr = self.Qr
            read_servers = self.data_servers
            i = 0
            c = []
            for number in read_servers:
                port = 'http://127.0.0.1:' + str(number)
                rpc = xmlrpclib.Server(port)
                readdatastatus = False
                getdatacount = 0
                print "going to while loop"
                while (readdatastatus is False and getdatacount < 5):
                    try:
                        rcv = rpc.get(Binary(key))
                        readdatastatus = True

                    except:
                        getdatacount = getdatacount + 1
                        print "get datacount is",
                        continue

                if "value" in rcv:
                    c.append(rcv["value"].data)
                    print c[i]
                    i = i + 1

                else:
                    print "no value in the server", number

            unique_list = []
            list_map = {}
            for i in c:
                if i not in unique_list:
                    unique_list.append(i)
            print "Unique list of reads ", unique_list
            for i in unique_list:
                counts = 0
                for j in c:
                    if i == j:
                        counts = counts + 1

                print "No of occurence of value", i, "is", counts
            list_map[i] = counts
            count_list = list_map.values()
            highest = max(count_list)
            if highest > int(Qr):
                for data, count in list_map.items():
                    if count == highest:
                        correct_value = data
                        print "correct value is : ", pickle.loads(
                            correct_value)
                    break
                for number in data_servers:
                    port = 'http://127.0.0.1:' + str(number)
                    rpc = xmlrpclib.Server(port)
                    k = 0
                    readdatastatus = False
                    getdatacount2 = 0
                    while (readdatastatus is False and getdatacount2 < 5):
                        try:
                            rcv = rpc.get(Binary(key))
                            readdatastatus = True
                            if "value" in rcv:
                                c.append(rcv["value"].data)
                                print c[k]
                                k = k + 1

                            else:
                                print "no value in the server", number
                        except:
                            getdatacount2 = getdatacount2 + 1
                            continue
                    if correct_value != c[k]:
                        status = False
                        counter = 0
                        while (status is False and counter < 5):
                            try:
                                status = rpc.put(
                                    Binary(key),
                                    Binary(pickle.dumps(correct_value)), 6000)
                            except:

                                counter = counter - 1
                                continue

                return pickle.loads(correct_value)
            else:
                print "servers crashed beyond repair"
Exemplo n.º 30
0
    def execute(self,
                query,
                column_names=None,
                date_fields=None,
                binary_fields=None,
                requesttagname=None,
                debug=False):
        """
        - execute (query, column_names = None, date_fields = None,
                   binary_fields = None,
                   requesttagname = None, debug = False)
        - Executes the query given as input
        - If Debug is True, the query and the column_names are printed
        """
        TRIES = 10
        log.debug('about to execute: %s', query)
        log.debug('column_names: %s', str(column_names))

        server = xmlrpclib.Server(self.urlEiServer)

        counter = 0
        finished = False

        while not finished:
            try:
                if server.Ping.isAlive('', '') > 0:
                    raise EiPingError('Ei server did not Ping.isAlive <= 0')
                finished = True
            except:
                counter += 1
                if counter > TRIES:
                    raise EiPingError('Could not ping to Ei server')
                else:
                    pass

        if not (server.Config.containsKey('', '', self.tagname)):
            server.Config.put('', '', self.tagname, self.urlJdbcServer)
        if server.Config.get('', '', self.tagname) != self.urlJdbcServer:
            server.Config.put('', '', self.tagname, self.urlJdbcServer)
        try:
            resultList = server.Query.execute('', '', query, [self.tagname])
        except ValueError:
            # Sometimes the you get an error like 'ValueError: invalid literal
            # for float(): NaN' For example, this error can occur if it wants
            # to get the mean, min, max or sum and there is is no data for
            # these results and it returns a strange square-symbol, which can
            # not be sent with xmlrpc as a float. Therefore, we catch the
            # error.
            return -2  # Error code.
        #now convert this list to a dictionary, using column_names (if present)
        try:
            rowLen = len(resultList[0])
        except:
            #todo: goede foutmelding oid
            return []
        #there are no columnNames: just take numbers
        if column_names == None:
            #make ['0', '1', ...] as columnNames
            column_names = map(lambda x: str(x), range(rowLen))
        result = []
        for row in resultList:
            newRow = {}
            for i in range(rowLen):
                if (row[i]) != (row[i]):
                    rowValue = None
                elif (date_fields is not None
                      and date_fields.count(column_names[i]) > 0):
                    # parse iso8601 date, maar niet helemaal omdat er
                    # minnetjes tussen moeten...   TODO: English
                    rowStr = str(row[i])
                    if len(rowStr) != 17:
                        # I saw dates like: 292278994-08-17 08:12:55.192
                        rowValue = None
                        log.error('Weird date found: %s', rowStr)
                    else:
                        rowEdited = (rowStr[:4] + '-' + rowStr[4:6] + '-' +
                                     rowStr[6:])
                        rowValue = iso8601.parse_date(rowEdited)
                elif (binary_fields is not None
                      and binary_fields.count(column_names[i]) > 0):
                    rowValue = row[i].data
                elif row[i] == -999:
                    rowValue = None
                else:
                    rowValue = row[i]
                newRow[column_names[i]] = rowValue
            result.append(newRow)
        return result