----------------------------------------------------------------------------------------------------------
#! /usr/bin/python
#FileName: RegDeviceSimu.py
import urllib
import httplib
import base64
import json
import ConfigParser
import sys
endpoint_path = '/opt/endpoint/modules/notification_rest_service/'
if not endpoint_path in sys.path:
sys.path.append(endpoint_path)
mdmi_path = '/opt/mdmi/modules'
if not mdmi_path in sys.path:
sys.path.append(mdmi_path)
from encryption import encrypt
from hosteddb.hosted_device import HostedDevice
app_reg_url = "/endpoint/v1/device/register"
app_reg_wrongurl = "/endpoint/v1/device/registe"
app_unreg_url = "/endpoint/v1/device/unregister"
app_unreg_wrongurl = "/endpoint/v1/device/unregiste"
class RegistrationSimu(object):
def execute(self, username, account_id, device_id, host, data, headers, url):
auth = self.encrypt_info(username, account_id, device_id, host)
headers['Host'] = host
headers['X-Ws-Auth'] = auth
headers['X-Ws-Ver'] = "1.0.0"
headers['X-WS-Mobile-Ver'] = "1.0.0"
print headers
conn = None
response = None
try:
conn = httplib.HTTPConnection("localhost", "80")
conn.request("POST", url, json.dumps(data), headers)
response = conn.getresponse()
#return response.read().strip()
return response.status
except Exception, e:
print "Exception: %s" % str(e)
print "Error Code: %s:" % response.status
def encrypt_info(self, username, account_id, device_id, host):
str = "Username:%s;AccountID:%d;DeviceID:%s;DeviceType:iPad;DeviceClass:1" % (username, account_id, device_id)
return encrypt(str, host, 0, "1.0.0")
def getdeviceinfo(self, udid):
hosted_device = HostedDevice(udid)
response = hosted_device.do_get()
deviceinfo = json.loads(response.content)
#print deviceinfo
udid = deviceinfo[0]["attributes"]["UDID"][0]
apptoken = deviceinfo[0]["attributes"]["appToken"][0]
print "Device UDID : %s - app token : %s" %(udid, apptoken)
def reg_device(email, accountid, udid, host, apptoken, headers, url):
print "start testing......"
obj = RegistrationSimu()
result = obj.execute(email, accountid, udid, host, apptoken, headers, url)
print result
if result == 200:
obj.getdeviceinfo(udid=udid)
print "Register app to Hosted Cloud server testing ended......"
else:
print "Register app to Hosted Cloud server testing failed......"
print "*" * 60
return result
if __name__ == '__main__':
#print "start testing......"
#obj = RegistrationSimu()
#print obj.execute("enderic1@websense.com", 87, "A9E7F809887AAF1865EF531EB9B35AA326FEE958", "localhost", {"token": "f48efe2c9120bf8588cfaa120832478790325b7c43138a8367da16ad0b1150c1"}, {"Content-Type":"application/json"})
#print obj.execute("xwang@websense.com", 87, "04D8CFD680D639302810460DAC8E3599152C5973", "localhost", {"token": "d7c49bb6fab13bd338928dcfddd300a9e3ce27ca718eb07df0812f311afab2ed"}, {"Content-Type":"application/json"})
#print "testing ended......"
#print obj.execute("xwang1@websense.com", 88, "9EE375C38B610E57DEF622F107FD0B94", "localhost", {"token": "APA91bGKie7RpFTL6eG-3CVQb335ZnyFN2MChP9M_LlML_zu6wH8gV1MlhVkwXjQy1MpbWvuzybPwvxXmTC2FJuabSaEn_EbftRst3cfS992m4weSFEA66ddsSHTwh0f6pVO0R96Xi4-iBueS199Qt1jw-9Z6aHpUSdDp_0ySrucA9uosbBV8k8"}, {"Content-Type":"application/json"})
#print "testing ended......"
reg_device("xwang1@websense.com", 88, "04D8CFD680D639302810460DAC8E3599152C5973", "localhost", {"token": "d7c49bb6fab13bd338928dcfddd300a9e3ce27ca718eb07df0812f311afab2ed"}, {"Content-Type":"application/json"}, app_reg_url)
#reg_device("xwang1@websense.com", 88, "04D8CFD680D639302810460DAC8E3599152C5973", "localhost", {"token": "d7c49bb6fab13bd338928dcfddd300a9e3ce27ca718eb07df0812f311afab2ed"}, {"Content-Type":"application/json"}, app_reg_wrongurl)
#reg_device("xwang1@websense.com", 88, "9EE375C38B610E57DEF622F107FD0B94", "localhost", {"token": "APA91bGKie7RpFTL6eG-3CVQb335ZnyFN2MChP9M_LlML_zu6wH8gV1MlhVkwXjQy1MpbWvuzybPwvxXmTC2FJuabSaEn_EbftRst3cfS992m4weSFEA66ddsSHTwh0f6pVO0R96Xi4-iBueS199Qt1jw-9Z6aHpUSdDp_0ySrucA9uosbBV8k8"}, {"Content-Type":"application/json"}, app_reg_url)
----------------------------------------------------------------------------------------------------------
#! /usr/bin/python
#FileName: NotificationSimu.py
import urllib
import httplib
import base64
import json
import ConfigParser
import sys
import time
import multiprocessing
endpoint_path = '/opt/endpoint/modules/notification_rest_service/'
if not endpoint_path in sys.path:
sys.path.append(endpoint_path)
mdmi_path = '/opt/mdmi/modules'
if not mdmi_path in sys.path:
sys.path.append(mdmi_path)
from encryption import encrypt
class NotificationSimu(object):
def execute(self, dn, password, data, headers):
headers['Authorization'] = "Basic " + base64.b64encode(dn + ":" + password)
conn = None
response = None
try:
conn = httplib.HTTPSConnection("localhost", "443")
conn.request("POST", "/endpoint/v1/notification/add", json.dumps(data), headers)
response = conn.getresponse()
return response.status
#return response.read().strip()
except Exception, e:
print "Exception: %s" % str(e)
print "Error Code: %s:" % response.status
def execute_url_incorrect(self, dn, password, data, headers):
headers['Authorization'] = "Basic " + base64.b64encode(dn + ":" + password)
conn = None
response = None
try:
conn = httplib.HTTPSConnection("localhost", "443")
conn.request("POST", "/endpoi", json.dumps(data), headers)
response = conn.getresponse()
return response.status
#return response.read().strip()
except Exception, e:
print "Exception: %s" % str(e)
print "Error Code: %s:" % response.status
def send_msg_ios():
#data = {"device_udid": "04D8CFD680D639302810460DAC8E3599152C5973", "app_id": "1234", "account_id": "88", "category": "Entertainment", "type": 0, "timestamp": "1395908409"}
data = {"device_udid": "04D8CFD680D639302810460DAC8E3599152C5973", "app_id": "1234", "account_id": "88", "category": "Entertainment", "type": 0, "timestamp": "1395908409"}
#data1 = {"messages": 12345}
blocktime = time.time()
data["timestamp"] = str(int(blocktime))
obj = NotificationSimu()
print "start testing......"
print obj.execute("cn=enrollment-service (admin),account=1,dc=blackspider,dc=com", "7Nz+BXcOXW3ZTXgZptPmRg", data, {"Content-Type":"application/json"})
print "testing ended......"
def send_msg_ard():
data = {"device_udid": "9EE375C38B610E57DEF622F107FD0B94", "app_id": "5678", "account_id": "88", "category": "News", "type": 0, "timestamp": "1395908409"}
blocktime = time.time()
data["timestamp"] = str(int(blocktime))
obj = NotificationSimu()
print "start testing......"
print obj.execute("cn=enrollment-service (admin),account=1,dc=blackspider,dc=com", "7Nz+BXcOXW3ZTXgZptPmRg", data, {"Content-Type":"application/json"})
print "testing ended......"
def send_multi_msgs_ios(con_num=10, loop_num=10):
pool = multiprocessing.Pool(processes=con_num)
results = []
i = 0
for i in xrange(loop_num):
results.append(pool.apply_async(send_msg_ios, ()))
pool.close()
pool.join()
print '======================================================'
print 'res size: %d' %len(results)
for res in results:
print res.get()
print "Send ios REST request Sub-process(es) done."
def send_multi_msgs_ard(con_num=10, loop_num=10):
pool = multiprocessing.Pool(processes=con_num)
results = []
i = 0
for i in xrange(loop_num):
results.append(pool.apply_async(send_msg_ard, ()))
pool.close()
pool.join()
print '======================================================'
print 'res size: %d' %len(results)
for res in results:
print res.get()
print "Send android REST request Sub-process(es) done."
if __name__ == '__main__':
send_multi_msgs_ios(loop_num=1)
-----------------------------------------------------------------
from common_task import CommonTask
from update_tqp_config import UpdateTQPConfig
from Endpoint_RegSimu_REST import *
from Endpoint_NotifSimu_REST import *
sys.path.append("/opt/mdmi/modules")
from hosteddb.hosted_taskqueue import HostedTaskQueue
NAMESPACES = ["mobile", "email"]
EMAIL_CFG_NAME = ["EmailTasks"]
ENDPOINT_CFG_NAME = ["task_block_message"]
ENDPOINT_TQS = ["blockmessage"]
updatetqconfig = UpdateTQPConfig('/etc/sysconfig/tqp/plugins.json')
task = CommonTask()
taskqueue = HostedTaskQueue()
data = {"description" : "", "max_leases" : "30", "max_age" : "0"}
device_cnt = 0
print "Register app to hosted cloud server ..."
result = reg_device("xwang1@websense.com", 88, "04D8CFD680D639302810460DAC8E3599152C5973", "localhost", {"token": "d7c49bb6fab13bd338928dcfddd300a9e3ce27ca718eb07df0812f311afab2ed"}, {"Content-Type":"application/json"}, app_reg_url)
if (result == 200):
device_cnt += 1
result = reg_device("xwang1@websense.com", 88, "9EE375C38B610E57DEF622F107FD0B94", "localhost", {"token": "APA91bGKie7RpFTL6eG-3CVQb335ZnyFN2MChP9M_LlML_zu6wH8gV1MlhVkwXjQy1MpbWvuzybPwvxXmTC2FJuabSaEn_EbftRst3cfS992m4weSFEA66ddsSHTwh0f6pVO0R96Xi4-iBueS199Qt1jw-9Z6aHpUSdDp_0ySrucA9uosbBV8k8"},
{"Content-Type":"application/json"}, app_reg_url)
if (result == 200):
device_cnt += 1
print "Total %d devices are registered to hosted cloud server successfully !" % device_cnt
print "Enable block message TQP..."
updatetqconfig.set_tqp_switch(tqpList=ENDPOINT_CFG_NAME, flag=1)
updatetqconfig.stop_service("/etc/init.d/task-processor")
updatetqconfig.start_service("/etc/init.d/task-processor")
#print "Clean block message task queue..."
#task.do_clearTaskQueue(account=1, tqname=ENDPOINT_TQS[0], namespace=NAMESPACES[0], desc=data)
#updatetqconfig.restart_service("/etc/init.d/task-processor")
while True:
#print "Stop block message TQP..."
#updatetqconfig.set_tqp_switch(tqpList=ENDPOINT_CFG_NAME, flag=0)
#updatetqconfig.restart_service("/etc/init.d/task-processor")
print "Send out endpoint messages requests to REST service..."
send_multi_msgs_ios(loop_num=1)
send_multi_msgs_ard(loop_num=1)
#tags = None
#del task
#task = CommonTask()
#for acc in [88]:
# tk = task.do_getTask(account=acc, tqname=ENDPOINT_TQS[0], namespace=NAMESPACES[0])
# if tk:
# print tk
# event = task.do_getEventFromTask(task=tk)
# print event
#print "Start block message TQP..."
#updatetqconfig.set_tqp_switch(tqpList=ENDPOINT_CFG_NAME, flag=1)
#updatetqconfig.restart_service("/etc/init.d/task-processor")
#print "-"*60
time.sleep(5)
本博客详细介绍了如何使用Python脚本来注册设备到云端服务器,并通过REST服务进行消息通知。包括设备注册流程、消息发送及多进程并发请求。
1万+

被折叠的 条评论
为什么被折叠?



