Example #1
0
 def setUp(self):
   global proc
   if proc is None:
     proc = subprocess.Popen([sys.executable, 
       os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test.py'),
       'serve'])
     time.sleep(1)
   self.host = 'http://127.0.0.1:8999/json/'
   self.proxy10 = ServiceProxy(self.host, version='1.0')
   self.proxy20 = ServiceProxy(self.host, version='2.0')
Example #2
0
 def bitcoin_balance(self, username=None):
     s = ServiceProxy(settings.BITCOIN_SERVER_URL)
     balance = s.getbalance(username or self.username)['result']
     
     # force set score == balance
     if username is None:
         self.score = balance
         self.save(update_fields=['score'])
     
     return balance
Example #3
0
def zabbixapi(request):
    method = request.POST.get('method')
    hostids = request.POST.get('hostids')
    groupid = request.POST.get('groupid')
    data = {}
    data['method'] = 'zabbix.' + method
    data['params'] = {"hostids": hostids, "groupid": groupid}
    if data['method'] == "zabbix.link_tem":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        link_tem = s.zabbix.link_tem(data)
        return HttpResponse(json.dumps(link_tem))
    elif data['method'] == "zabbix.add":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        create_zbx_host = s.zabbix.add(data)
        return HttpResponse(json.dumps(create_zbx_host))
Example #4
0
def addItem(request):
    if request.method == 'GET':
        return JSONResponse("GET")

    if request.method == 'POST':
        data = JSONParser().parse(request)
        flg_key = data.has_key('key')
        if not flg_key:
            return JSONResponse('key is empty!')

        access_key = data['key']
        if cmp(access_key, "test"):
            return JSONResponse("access key error.")

        flg_domain = data.has_key('domain')
        if not flg_domain:
            result = {"error": "-1", "errmsg": "domain is empty"}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")

        from jsonrpc.proxy import ServiceProxy
        s = ServiceProxy('http://localhost:5000/json/')
        import awvs
        ins = awvs.AWVS()
        ins.auth({"email": "name", "password": "******"})
        ins.addTask(['lua.ren\n', 'candylab.net\n'])

        result = {"error": "0", "errmsg": "none"}
        return HttpResponse(json.dumps(result, ensure_ascii=False),
                            content_type="application/json,charset=utf-8")
Example #5
0
    def pull(request, organization_name, department_name):
        organization = Organization.objects.get(name=organization_name)
        department = Department.objects.get(name=department_name,
                                            organization=organization)
        url = 'http://' + department.domain + '/json/'
        s = ServiceProxy(url)

        remote_list = s.teleforma.get_course_list(organization_name,
                                                  department.name)
        for course_dict in remote_list['result']:
            course = Course.objects.filter(code=course_dict['code'])
            if not course:
                course = Course()
            else:
                course = course[0]
            course.from_dict(course_dict)

        remote_list = s.teleforma.get_course_type_list()
        if remote_list['result']:
            for course_type_dict in remote_list['result']:
                course_type = CourseType.objects.filter(
                    name=course_type_dict['name'])
                if not course_type:
                    course_type = CourseType()
                else:
                    course_type = course_type[0]
                course_type.from_dict(course_type_dict)
Example #6
0
    def test_tag_list(self):
        s = ServiceProxy(self.URL)

        result = s.collector.getTagList()
        tags = result['result']
        self.assertTrue(len(tags) > 0)
        self.assertEqual(result['error'], None)
        self.assertEqual(tags[0]['tag'], 'SIM_RANDINT')
Example #7
0
def addhome_params():
    client = ServiceProxy(REMOTE_JSON)

    while 1:
        router_id = raw_input("\nEnter Router ID: ")
        if router_id=='':
            print 'Empty address. Input again.'
            continue

        result = client.ucap.check_hid_existence(router_id)
        if result['result'][1]=='t':
            print 'This Router ID already exists. Input again.'
            continue
        else:
            break

    while 1:
        address = raw_input("\nEnter Home Address: ")
        if address=='':
            print 'Empty address. Input again.'
            continue
        else:
            break

    while 1:
        details = raw_input("\nEnter Description: ")
        if details=='':
            print 'Empty description. This is good for identifcation. Input again.'
            continue
        else:
            break

    notify = 'f'
    notifyperc = '80'
    notified = 'f'
    photofilepath = ''

    # Review information
    print "\n\nPlease review and verify inputs. No turning back after this!"
    print "\n* Router ID: %s\n* Home Address: %s\n* Description: %s\n"%(router_id,address,details)

    while 1:
        yes_enter = raw_input("\nIs everything correct? (y/n): ")
        if yes_enter=='y' or yes_enter=='yes':
            break
        elif yes_enter=='n' or yes_enter=='no':
            print "Starting over...."
            return -2
        else:
            continue
    try:
        res = client.ucap.addHouse(router_id, address, details, photofilepath)
        print res
        print 'Home Added.'
        return 0
    except:
        print 'JSONRPC Failed. Abort'
        return -1
Example #8
0
    def add_credit(self, value, free=False):
        retval = None
        if settings.JSONRPC_URL and not free:
            items = [{
                "description": config.invoice_desc,
                "count": float(value),
                "unit": "kr.",
                "price": 1 / float(config.credit_currency.split(",")
                                   [0]),  #TODO:change it to multicurrency
                "tax": config.tax,
            }]

            proxy = ServiceProxy(settings.JSONRPC_URL)
            #TODO:what to do with exception?
            retval = proxy.add_invoice(settings.JSONRPC_USERNAME,
                                       settings.JSONRPC_PASSWORD,
                                       self.address_id, items)

        bonus = 1.0

        if value >= 1000:
            bonus = config.credit_1000_bonus
        elif value >= 750:
            bonus = config.credit_750_bonus
        elif value >= 500:
            bonus = config.credit_500_bonus
        elif value >= 250:
            bonus = config.credit_250_bonus

        credit = Credit(user=self.user,
                        value=value * bonus,
                        bonus=value * (bonus - 1.0),
                        invoice=free)
        credit.save()

        message = Message.objects.filter(purpose="add_credit")
        if message:
            message[0].send(
                config.email, {
                    "user": self.user.username,
                    "credit": value,
                    "bonus": value * (bonus - 1.0)
                })

        return retval
Example #9
0
 def test_positional_args(self):
   proxy = ServiceProxy(self.host)
   self.assert_(proxy.jsonrpc.test('Hello')[u'result'] == 'Hello')
   try:
     proxy.jsonrpc.test(string='Hello')
   except Exception, e:
     self.assert_(e.args[0] == 'Unsupport arg type for JSON-RPC 1.0 '
                               '(the default version for this client, '
                               'pass version="2.0" to use keyword arguments)')
Example #10
0
 def stop(self):
     print('Got stop call')
     self.continue_serving = False
     try:
         proxy = ServiceProxy('http://127.0.0.1:8999/json/', version=2.0)
         proxy.jsonrpc.test(string='Hello')['result']
     except: # doesnt matter if this fails
         pass
     self.t.join(2.0)
     return self
Example #11
0
    def pull(request, host=None):
        if host:
            url = 'http://' + host + '/json/'
        else:
            url = 'http://' + settings.TELECASTER_MASTER_SERVER + '/json/'
        s = ServiceProxy(url)

        remote_list = s.teleforma.get_class_group_list()
        for class_group_dict in remote_list['result']:
            class_group, c = WebClassGroup.objects.get_or_create(
                name=class_group_dict['name'])
Example #12
0
 def push(request, organization_name, department_name):
     organization = organization.objects.get(name=organization_name)
     department = Department.objects.get(name=department_name,
                                         organization=organization)
     url = 'http://' + department.domain + '/json/'
     s = ServiceProxy(url)
     remote_list = s.teleforma.get_conference_list()['result']
     remote_ids = [conf['id'] for conf in remote_list]
     for conference in Conference.objects.all():
         if not conference.public_id in remote_ids and conference.date_end:
             s.teleforma.create_conference(conference.to_json_dict())
Example #13
0
 def test_positional_args(self):
     proxy = ServiceProxy(self.host)
     self.assertTrue(proxy.jsonrpc.test('Hello')['result'] == 'Hello')
     try:
         proxy.jsonrpc.test(string='Hello')
     except Exception as e:
         self.assertTrue(e.args[0] == 'Unsupported arg type for JSON-RPC 1.0 '
                                   '(the default version for this client, '
                                   'pass version="2.0" to use keyword arguments)')
     else:
         self.assertTrue(False, 'Proxy didnt warn about version mismatch')
Example #14
0
def zabbix_template(request):
    method = request.POST.get('method')
    hostid = request.POST.get('hostid')
    templateid = request.POST.get('templateid')
    data = {}
    data['method'] = 'zabbix_template.' + method
    data['params'] = {"hostids": hostid, "templateid": templateid}
    if data['method'] == "zabbix_template.unlink_tem":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        unlink_tem = s.zabbix_template.unlink_tem(data)
        return HttpResponse(json.dumps(unlink_tem))
Example #15
0
class cbeamThread(threading.Thread):
    def __init__(self, cbeamurl):
        threading.Thread.__init__(self)
        self.cbeam = ServiceProxy(cbeamurl)
        self.cbeamdata = {}

    def run(self):
        while True:
            try:
                tmp = self.cbeam.who()['result']
                events = self.cbeam.events()['result']
                tmp['events'] = events
                self.cbeamdata = tmp
            except:
                pass
            sleep(10)
            print "c-beam data updated."

    def getcbeamdata(self):
        print self.cbeamdata
        return self.cbeamdata
Example #16
0
 def pull(request):
     departments = Department.objects.all()
     for department in departments:
         url = 'http://' + department.domain + '/json/'
         s = ServiceProxy(url)
         remote_list = s.teleforma.get_conference_list()
         for conf_dict in remote_list['result']:
             conference = Conference.objects.filter(
                 public_id=conf_dict['id'])
             if not conference:
                 conference = Conference()
                 conference.from_json_dict(conf_dict)
Example #17
0
class cbeamThread ( threading.Thread ):

    def __init__(self, cbeamurl):
        threading.Thread.__init__(self) 
        self.cbeam = ServiceProxy(cbeamurl)
        self.cbeamdata = {}

    def run (self):
        while True:
            try:
                tmp = self.cbeam.who()['result']
                events = self.cbeam.events()['result']
                tmp['events'] = events
                self.cbeamdata = tmp
            except:
                pass
            sleep(10)
            print "c-beam data updated."

    def getcbeamdata(self):
        print self.cbeamdata
        return self.cbeamdata
Example #18
0
    def add_credit(self, value, free=False):
        retval = None
        if settings.JSONRPC_URL and not free:
            items = [{
                "description": config.invoice_desc,
                "count": float(value),
                "unit": "kr.",
                "price": 1 / float(config.credit_currency.split(",")[0]), #TODO:change it to multicurrency
                "tax": config.tax,
                }]

            proxy = ServiceProxy(settings.JSONRPC_URL)
            #TODO:what to do with exception?
            retval = proxy.add_invoice(
                settings.JSONRPC_USERNAME,
                settings.JSONRPC_PASSWORD,
                self.address_id,
                items
            )

        bonus = 1.0

        if value >= 1000:
            bonus = config.credit_1000_bonus
        elif value >= 750:
            bonus = config.credit_750_bonus
        elif value >= 500:
            bonus = config.credit_500_bonus
        elif value >= 250:
            bonus = config.credit_250_bonus

        credit = Credit(user=self.user, value=value * bonus, bonus=value * (bonus - 1.0), invoice=free)
        credit.save()

        message = Message.objects.filter(purpose="add_credit")
        if message:
            message[0].send(config.email, {"user": self.user.username, "credit": value, "bonus": value * (bonus - 1.0)})

        return retval
Example #19
0
def listapi(request):
    method = request.GET.get('method')
    if method == "zbhost_allhost":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        data = s.zbhost_allhost.getlist()
        return HttpResponse(json.dumps(data),
                            content_type='application/json; charset=utf-8')
    elif method == "zabbix_gettem":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        tem = s.zabbix_gettem.getlist()
        return HttpResponse(json.dumps(tem),
                            content_type='application/json; charset=utf-8')
    elif method == "zabbix_tem":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        host_tem = s.zabbix_tem.getlist()
        return HttpResponse(json.dumps(host_tem),
                            content_type='application/json; charset=utf-8')
    elif method == "zbhost":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        zbhost = s.zbhost.getlist()
        return HttpResponse(json.dumps(zbhost),
                            content_type='application/json; charset=utf-8')
    elif method == "zabbix":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        zabbixhost = s.zabbix.getlist()
        return HttpResponse(json.dumps(zabbixhost),
                            content_type='application/json; charset=utf-8')
    else:
        data = {
            u'result':
            u'{"code": 1, "result": [{"host": "meidai-monitor", "hostid": "10291"}]}',
            u'jsonrpc': u'1.0',
            u'id': u'48e8787a-ad68-11e7-be94-000c29a6a1c8',
            u'error': None
        }
        data1 = json.dumps(data)
        return HttpResponse(json.dumps(data))
Example #20
0
def listapi(request):
    method = request.GET.get('method')
    # zbhost_allhost_getlist = method + ".getlist"
    # s = ServiceProxy('http://192.168.2.159:8400/json/')
    # data = s.zbhost_allhost.getlist()
    # print data
    print method
    if method == "zbhost_allhost":
        s = ServiceProxy('http://192.168.2.159:8000/json/')
        data = s.zbhost_allhost.getlist()
        print json.dumps(data)
        print type(json.dumps(data))
        # print ServiceProxy('http://192.168.2.159:8400/json/').zbhost_allhost.getlist()
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
    elif method == "zabbix_gettem":
        s = ServiceProxy('http://192.168.2.159:8000/json/')
        tem = s.zabbix_gettem.getlist()
        return HttpResponse(json.dumps(tem), content_type='application/json; charset=utf-8')
    elif method == "zabbix_tem":
        s = ServiceProxy('http://192.168.2.159:8000/json/')
        host_tem = s.zabbix_tem.getlist()
        return HttpResponse(json.dumps(host_tem), content_type='application/json; charset=utf-8')
    elif method == "zbhost":
        s = ServiceProxy('http://192.168.2.159:8000/json/')
        zbhost = s.zbhost.getlist()
        return HttpResponse(json.dumps(zbhost), content_type='application/json; charset=utf-8')
    elif method == "zabbix":
        s = ServiceProxy('http://192.168.2.159:8000/json/')
        zabbixhost = s.zabbix.getlist()
        return HttpResponse(json.dumps(zabbixhost), content_type='application/json; charset=utf-8')
    else:
        data = {
            u'result': u'{"code": 1, "result": [{"host": "Zabbix server", "hostid": "10084"}, {"host": "192.168.2.159", "hostid": "10107"}]}',
            u'jsonrpc': u'1.0', u'id': u'48e8787a-ad68-11e7-be94-000c29a6a1c8', u'error': None}
        data1 = json.dumps(data)
        type(data1)
        return HttpResponse(json.dumps(data))
Example #21
0
def getapi(request):
    method = request.GET.get('method')
    print method
    data = {}
    data['method'] =  method + '.get'
    data['params'] = {
        "m_table":request.GET.get('m_table',None),
        'field': request.GET.get('field', None),
        's_table': request.GET.get('s_table', None),
        'where': {'id': int(request.GET.get('id'))}
    }
    if method == "graph":
        s = ServiceProxy('http://192.168.2.159:8000/json/')
        zbx_graph = s.graph.get(data)
        return HttpResponse(json.dumps(zbx_graph))
Example #22
0
def getapi(request):
    method = request.GET.get('method')
    data = {}
    data['method'] = method + '.get'
    data['params'] = {
        "m_table": request.GET.get('m_table', None),
        'field': request.GET.get('field', None),
        's_table': request.GET.get('s_table', None),
        'where': {
            'host': request.GET.get('ip')
        }
    }
    if method == "graph":
        s = ServiceProxy('http://127.0.0.1:8000/zabbix/json/')
        zbx_graph = s.graph.get(data)
        return HttpResponse(json.dumps(zbx_graph))
Example #23
0
def deluser_params():
    client = ServiceProxy(REMOTE_JSON)
    router_id = ''

    while 1:
        router_id = raw_input("\nEnter Router ID: ")
        result = client.ucap.check_hid_existence(router_id)
        if result['result'][1] == 'f':
            print 'Wrong Router ID. Input again.'
            continue
        else:
            break

    while 1:
        user_id = raw_input("\nEnter User ID (as email address): ")
        if not re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$",
                        user_id):
            print 'Invalid email address. Input again.'
            continue

        result = client.ucap.check_uid_existence(router_id, user_id)
        if result['result'][1] == 'f':
            print 'Wrong User ID. Input again.'
            continue
        else:
            break

    # Review information
    print "\n\nPlease review and verify inputs. No turning back after this!"
    print "\n* Router ID: %s\n* User ID: %s\n" % (router_id, user_id)

    while 1:
        yes_enter = raw_input("\nIs everything correct? (y/n): ")
        if yes_enter == 'y' or yes_enter == 'yes':
            break
        elif yes_enter == 'n' or yes_enter == 'no':
            print "Starting over...."
            return -2
        else:
            continue
    try:
        result = client.ucap.delUser(router_id, user_id)
        print 'User deleted.'
        return 0
    except:
        print 'JSONRPC Failed. Abort'
        return -1
Example #24
0
 def stop(request, public_id):
     conference = Conference.objects.get(public_id=public_id)
     conference.date_end = datetime.datetime.now()
     conference.save()
     for stream in conference.livestream.all():
         stream.delete()
     for station in conference.station.all():
         station.started = False
         station.save()
         station.stop()
     if 'telecaster' in settings.INSTALLED_APPS:
         try:
             url = 'http://' + settings.TELECASTER_MASTER_SERVER + '/json/'
             s = ServiceProxy(url)
             s.teleforma.stop_conference(conference.public_id)
         except:
             pass
Example #25
0
    def handle(self, *args, **options):
        try:
            if options['index']:
                print 'hello world, %s' % options['index']
            if options['file']:
                print 'input file, %s' % options['file']

            from jsonrpc.proxy import ServiceProxy
            s = ServiceProxy('http://localhost:5000/json/')
            s.myapp.sayHello('Sam')

            self.stdout.write(
                self.style.SUCCESS(u'命令%s执行成功, 参数为%s' %
                                   (__file__, options['index'])))
        except Exception, ex:
            traceback.print_exc()
            self.stdout.write(self.style.ERROR(u'命令执行出错'))
    def fetch_chart_data(self, slot_key, slot_idx, chart_name):
        """
        * Check status
        action: "fetch"
        adom: string
        chart-name: string
        slot_key: int
        slot_idx: int

        Example:

        rtm_command({"action" : "fetch", "adom" : "root",
        "chart-name" : "Top-Users-By-Bandwidth" ,"slot_key": 2029630888,
        "slot_idx": 0 })

        =>
        {u'result': {u'perc': 100, u'status': u'finished',
        u'sql_code': 0, u'fields': [u'User', u'IP', u'Traffic Out', u'Traffic
        In', u'Bandwidth'], u'data': [[u'micheal', u'51.0.0.1', u'5000',
        u'50000', u'55000'], [u'shark', u'102.0.0.1', u'19900', u'10000',
        u'29900'], [u'shark', u'101.0.0.1', u'10330', u'10020', u'20350'],
        [u'userB', u'101.2.3.1', u'10000', u'10000', u'20000'], [u'ming',
        u'92.0.0.1', u'9001', u'9000', u'18001'], [u'ming', u'91.0.0.1',
        u'9000', u'9000', u'18000'], [u'ming', u'91.2.3.1', u'9000', u'9000',
        u'18000'], [u'jessie', u'82.0.0.1', u'8000', u'8011', u'16011'],
        [u'jessie', u'81.0.0.1', u'8000', u'8000', u'16000'], [u'jessie',
        u'81.2.3.1', u'8000', u'8000', u'16000']], u'chart-name':
        u'Top-Users-By-Bandwidth'}}
        """
        params = {
            'action': 'fetch',
            'adom': 'root',
            'chart-name': chart_name,
            'slot_key': slot_key,
            'slot_idx': slot_idx
        }

        s = ServiceProxy('http://' + self.faz_ip + '/fazproxy/')
        ret = s.fazmerge.rtm_command(params)

        return ret
Example #27
0
    def pull(request, host=None):
        if host:
            url = 'http://' + host + '/json/'
        else:
            url = 'http://' + settings.TELECASTER_MASTER_SERVER + '/json/'
        s = ServiceProxy(url)

        remote_list = s.teleforma.get_professor_list()
        for professor_dict in remote_list['result']:
            user, c = User.objects.get_or_create(
                username=professor_dict['username'])
            user.first_name = professor_dict['first_name']
            user.last_name = professor_dict['last_name']
            user.email = professor_dict['email']
            user.save()

            professor, c = Professor.objects.get_or_create(user=user)
            for course_code in professor_dict['courses']:
                course = Course.objects.filter(code=course_code)
                if course:
                    if not course[0] in professor.courses.all():
                        professor.courses.add(course[0])
            professor.save()
Example #28
0
def reg(request):
    if request.method == 'POST':
        form1 = formReg(request.POST)
        form2 = formReg2(request.POST)
        if form1.is_valid() and form2.is_valid():
            # machine
            m_web = get_object_or_404(Machine, name=config.default_web_machine)
            m_mail = get_object_or_404(Machine, name=config.default_mail_machine)
            m_mysql = get_object_or_404(Machine, name=config.default_mysql_machine)
            m_pgsql = get_object_or_404(Machine, name=config.default_pgsql_machine)

            address_id = 0
            if settings.JSONRPC_URL:
                proxy = ServiceProxy(settings.JSONRPC_URL)
                data = proxy.add_address(
                    settings.JSONRPC_USERNAME, settings.JSONRPC_PASSWORD,
                    form1.cleaned_data["company"],
                    form1.cleaned_data["first_name"],
                    form1.cleaned_data["last_name"],
                    form1.cleaned_data["street"],
                    form1.cleaned_data["city"],
                    form1.cleaned_data["city_num"],
                    form1.cleaned_data["phone"],
                    form1.cleaned_data["email"],
                    form1.cleaned_data["ic"],
                    form1.cleaned_data["dic"]
                )
                print data
                address_id = int(data["result"])

            # user
            u = user.objects.create_user(form2.cleaned_data["username"],
                                         form1.cleaned_data["email"],
                                         form2.cleaned_data["password1"])
            u.is_active = False
            u.save()

            # parms
            p = Parms()
            p.home = join("/home", form2.cleaned_data["username"])
            p.note = ""
            p.uid = 0
            p.gid = 0
            p.discount = 0
            p.web_machine = m_web
            p.mail_machine = m_mail
            p.mysql_machine = m_mysql
            p.pgsql_machine = m_pgsql
            p.user = u
            p.address_id = int(address_id)
            p.save()

            message = Message.objects.filter(purpose="reg")
            if message:
                message[0].send(form1.cleaned_data["email"])

            message = _("New user has been registered.")
            send_mail(_('New registration'),
                      message,
                      settings.EMAIL_FROM,
                [address for (name, address) in settings.ADMINS],
                      fail_silently=True)
            #fail_silently - nechci 500 kvuli neodeslanemu mailu

            return HttpResponseRedirect(
                reverse("wsgiadmin.useradmin.views.regok"))
    else:
        form1 = formReg()
        form2 = formReg2()

    form_helper = FormHelper()
    form_helper.form_tag = False

    return render_to_response('reg.html',
        {
            "form1": form1,
            "form2": form2,
            "form_helper": form_helper,
            "title": _("Registration"),
            "action": reverse("wsgiadmin.useradmin.views.reg"),
            "config": config,
            "menu_active": "registration",
        },
        context_instance=RequestContext(request)
    )
Example #29
0
 def push(self, conference):
     url = 'http://' + settings.TELECASTER_MASTER_SERVER + '/json/'
     s = ServiceProxy(url)
     s.teleforma.create_conference(conference.to_json_dict())
Example #30
0
 def bitcoin_pay(self, amount=0.0, frm=None, to=None):
     s = ServiceProxy(settings.BITCOIN_SERVER_URL)
     to_address = self.bitcoin_address(to)
     if isinstance(amount, decimal.Decimal):
         amount = float(amount)
     return s.sendfrom(frm or self.username, to_address, amount)['result']
Example #31
0
import sys
import random
import time

def randint():
	return random.randint(2**29, 2**30)

from jsonrpc.proxy import ServiceProxy

sp = ServiceProxy('jsonrpc://10.0.0.94:10030')
starttime = time.time()
ctime = time.time()
c = 0
print int(ctime*1000), c

while ctime - starttime < 60.0:
	a = randint()
	b = randint()
	res = sp.add(a,b)
	ctime = time.time()

	if res != a+b:
		print 'error, res!= a+b', res, a+b

	c += 1
	if c % 1000 == 0:
		print int(ctime*1000), c
	
ctime = time.time()
print int(ctime*1000), c
Example #32
0
def reg(request):
    if request.method == 'POST':
        form1 = formReg(request.POST)
        form2 = formReg2(request.POST)
        if form1.is_valid() and form2.is_valid():
            # machine
            m_web = get_object_or_404(Machine, name=config.default_web_machine)
            m_mail = get_object_or_404(Machine,
                                       name=config.default_mail_machine)
            m_mysql = get_object_or_404(Machine,
                                        name=config.default_mysql_machine)
            m_pgsql = get_object_or_404(Machine,
                                        name=config.default_pgsql_machine)

            address_id = 0
            if settings.JSONRPC_URL:
                proxy = ServiceProxy(settings.JSONRPC_URL)
                data = proxy.add_address(
                    settings.JSONRPC_USERNAME, settings.JSONRPC_PASSWORD,
                    form1.cleaned_data["company"],
                    form1.cleaned_data["first_name"],
                    form1.cleaned_data["last_name"],
                    form1.cleaned_data["street"], form1.cleaned_data["city"],
                    form1.cleaned_data["city_num"],
                    form1.cleaned_data["phone"], form1.cleaned_data["email"],
                    form1.cleaned_data["ic"], form1.cleaned_data["dic"])
                print data
                address_id = int(data["result"])

            # user
            u = user.objects.create_user(form2.cleaned_data["username"],
                                         form1.cleaned_data["email"],
                                         form2.cleaned_data["password1"])
            u.is_active = False
            u.save()

            # parms
            p = Parms()
            p.home = join("/home", form2.cleaned_data["username"])
            p.note = ""
            p.uid = 0
            p.gid = 0
            p.discount = 0
            p.web_machine = m_web
            p.mail_machine = m_mail
            p.mysql_machine = m_mysql
            p.pgsql_machine = m_pgsql
            p.user = u
            p.address_id = int(address_id)
            p.save()

            message = Message.objects.filter(purpose="reg")
            if message:
                message[0].send(form1.cleaned_data["email"])

            message = _("New user has been registered.")
            send_mail(_('New registration'),
                      message,
                      settings.EMAIL_FROM,
                      [address for (name, address) in settings.ADMINS],
                      fail_silently=True)
            #fail_silently - nechci 500 kvuli neodeslanemu mailu

            return HttpResponseRedirect(
                reverse("wsgiadmin.useradmin.views.regok"))
    else:
        form1 = formReg()
        form2 = formReg2()

    form_helper = FormHelper()
    form_helper.form_tag = False

    return render_to_response(
        'reg.html', {
            "form1": form1,
            "form2": form2,
            "form_helper": form_helper,
            "title": _("Registration"),
            "action": reverse("wsgiadmin.useradmin.views.reg"),
            "config": config,
            "menu_active": "registration",
        },
        context_instance=RequestContext(request))
Example #33
0
 def bitcoin_withdraw(self, addr):
     s = ServiceProxy(settings.BITCOIN_SERVER_URL)
     return s.sendfrom(self.username, addr, self.bitcoin_balance())
Example #34
0
import sys
import requests
from jsonrpc.proxy import ServiceProxy

filename=sys.argv[1]

baseurl='http://www.adversarylab.org/'

rpc=ServiceProxy(baseurl+'/api/pcap')
code=rpc.uploadCode()

requests.post(code, files={'pcapFile': open(filename,'rb')})
Example #35
0
from jsonrpc.proxy import ServiceProxy

s = ServiceProxy('http://localhost:8000/jsonrpc/')

#!/usr/bin/env python
# coding: utf-8

import pyjsonrpc


class RequestHandler(pyjsonrpc.HttpRequestHandler):
    @pyjsonrpc.rpcmethod
    def add(self, a, b):
        result = s.add(a, b)['result']
        return result + 1


# Threading HTTP-Server
http_server = pyjsonrpc.ThreadingHttpServer(server_address=('192.168.102.81',
                                                            8080),
                                            RequestHandlerClass=RequestHandler)
print "Starting HTTP server ..."
print "URL: http://localhost:8080"
http_server.serve_forever()
Example #36
0
 def test_keyword_args(self):        
   proxy = ServiceProxy(self.host, version='2.0')
   self.assert_(proxy.jsonrpc.test(string='Hello')[u'result'] == 'Hello')
   self.assert_(proxy.jsonrpc.test('Hello')[u'result'] == 'Hello')
Example #37
0
from jsonrpc.proxy import ServiceProxy
s = ServiceProxy('http://localhost:8000/api/rpc/')
print s.authenticate()
Example #38
0
#! /usr/bin/env python3

import sys
import base64
from jsonrpc.proxy import ServiceProxy

if __name__ == "__main__":
    if len( sys.argv ) != 2:
        print( "Usage: {} filename".format( sys.argv[0] ) )
        sys.exit(1)
    filename = sys.argv[1]
    service = ServiceProxy( 'http://127.0.0.1:5000/api/' )
    with open( filename, 'rb' ) as input_file:
        content = input_file.read()
        b64_content = base64.b64encode( content ).decode('utf8')
        print( b64_content )

        #response = service.api.upload_file( b64_content, filename )
        #print( "Response: {}".format( response ) )
        response = service.api.download_file( filename )
        print( "Response: {}".format( response ) )
        #content = base64.b64decode( b64_content ).decode('utf8')
        #print( content )
Example #39
0
 def __init__(self, cbeamurl):
     threading.Thread.__init__(self) 
     self.cbeam = ServiceProxy(cbeamurl)
     self.cbeamdata = {}
Example #40
0
 def bitcoin_address(self, username=None):
     s = ServiceProxy(settings.BITCOIN_SERVER_URL)
     lst = s.getaddressesbyaccount(username or self.username)['result']
     if lst: return lst[0]
     return s.getnewaddress(self.username)['result']