Ejemplo n.º 1
0
    def report_asset(self):
        # 实例化obj
        obj = info_collection.InfoCollection()
        # 客户端执行obj实例下的collect函数进行数据收集
        asset_data = obj.collect()
        # 查看客户端本地的asset_id文件是否有id写入,这里的sn其实没什么用暂时
        asset_id = self.load_asset_id(asset_data["sn"])
        # 先确定本地客户端是否有asset_id号
        if asset_id:
            # 如果本地有asset_id号,那就往asset_data里添加一条key为asset_id,value为asset_id的数据,并且指定执行提交数据的url
            asset_data["asset_id"] = asset_id
            post_url = "asset_report"
        else:  #first time report to server
            '''report to another url,this will put the asset into approval waiting zone, when the asset is approved ,this request returns
            asset's ID'''
            # 如果本地没有asset_id号,那就往asset_data里添加一条key为asset_id,value为None的数据,并且指定执行提交数据的url
            asset_data["asset_id"] = None
            post_url = "asset_report_with_no_id"

        data = {"asset_data": json.dumps(asset_data)}
        # 执行__submit_data私有函数方法,三个参数分别是提交到的url,数据,以及提交的方法
        response = self.__submit_data(post_url, data, method="post")
        if "asset_id" in response:
            self.__update_asset_id(response["asset_id"])

        self.log_record(response)
Ejemplo n.º 2
0
 def collect_data():
     """
     收集资产信息
     """
     obj = info_collection.InfoCollection()
     asset_data = obj.collect()
     pprint(asset_data)
Ejemplo n.º 3
0
    def report_data():
        """
        获取本机IP地址,然后发送至服务器
        :return:
        """
        # 获取IP
        info = info_collection.InfoCollection()
        ip = info.get_ip()
        url = "http://%s:%s%s?serverType=%s" % (settings.Params['server'],
                                                settings.Params['port'],
                                                settings.Params['url'], ip)
        print('正在将数据发送至: [%s]  ......' % url)

        try:
            response = urllib.request.urlopen(
                url=url, data=None, timeout=settings.Params['request_timeout'])
            message = str(response.read(), 'utf-8')
            j = json.loads(message)
            retstatus = j['resultMsg']['status']
            print('返回结果: %s ' % retstatus)
        except Exception as e:
            message = '发送失败'
            print("发送失败,%s" % e)
        with open(settings.PATH, 'ab') as f:
            string = '发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n' % (
                time.strftime('%Y-%m-%d %H:%M:%S'), url, retstatus)
            f.write(string.encode())
            print("日志记录成功!")
Ejemplo n.º 4
0
 def report_data():
     """收集硬件信息,然后发送到服务器"""
     # 收集信息
     info = info_collection.InfoCollection()
     asset_data = info.collect()
     # 将数据打包到一个字典内,并转换为json格式
     data = {"asset_data": json.dumps(asset_data)}
     # 根据settings中的配置,构造url
     url = "http://%s:%s%s" % (settings.Params['server'], settings.Params['port'],
                               settings.Params['url'])
     print("正在将数据发送至: [%s] ..." % url)
     try:
         # 使用python内置的urllib.request库,发送post请求
         # 需要先将数据进行封装,并转换为bytes类型
         data_encode = urllib.parse.urlencode(data).encode()
         response = urllib.request.urlopen(url=url, data=data_encode,
                                           timeout=settings.Params['request_timeout'])
         print("\033[31;1m发送完毕!\033[0m ")
         message = response.read().decode()
         print("返回结果: %s" % message)
     except Exception as e:
         message = "发送失败" + "  错误原因:  {}".format(e)
         print("返回结果:%s" % message)
     # 记录发送日志
     with open(settings.PATH, 'ab') as f:  # 以byte的方式写入,防止出现编码错误
         log = "发送时间: %s \t服务器地址: %s \t返回结果: %s \n" % (time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
         f.write(log.encode())
         print("日志记录成功!")
Ejemplo n.º 5
0
 def report_data():
     """
     收集硬件信息,然后发送到服务器。
     :return: 
     """
     #收集信息
     info = info_collection.InfoCollection()
     asset_data = info.collect()
     #讲数据打包到一个字典中,并转化为json格式
     data = {"asset_data": json.dumps(asset_data)}
     #根据setting中的配置,构造url
     url = "http://%s:%s%s" % (setting.Params['server'],
                               setting.Params['port'],
                               setting.Params['url'])
     print('正在将数据发送至:[%s] ......' % url)
     try:
         #使用python内置的urllib。request库,发送post请求
         #需要先将数据进行封装,并转化为btes字节
         data_encode = urllib.parse.urlencode(data).encode()
         response = urllib.request.urlopen(
             url=url,
             data=data_encode,
             timeout=setting.Params['request_timeout'])
         print("\033[31;1m发送完毕!\033[0m")
         message = response.read().decode()
         print("返回结果:%s" % message)
     except Exception as e:
         message = '发送失败了' + '  原因是:{}'.format(e)
         print("\033[31;1m发送失败,错误原因:%s \033[0m" % e)
     with open(setting.PATH, 'ab') as f:  #以byte的方式写入,防止出现编码错误
         log = '发送时间:%s\t 服务器地址:%s \t 返回结果:%s \n' % (
             time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
         f.write(log.encode())
         print("日志记录成功!")
Ejemplo n.º 6
0
    def report_data():
        """
        收集硬件信息,然后发送到服务器。
        :return:
        """
        # 收集信息
        info = info_collection.InfoCollection()
        asset_data = info.collect()
        # 将数据打包到一个字典内,并转换为json格式
        data = json.dumps({"asset_data": asset_data})
        # 根据settings中的配置,构造url
        url = "http://%s:%s%s" % (settings.Params['server'],
                                  settings.Params['port'],
                                  settings.Params['url'])
        print('正在将数据发送至: [%s]  ......' % url)
        try:
            headers = {'content-type': 'application/json'}
            response = requests.post(url=url, data=data, headers=headers)
            message = response.text
        except Exception as e:
            message = "发送失败" + f"  错误原因:{e}"
            print(f"发送失败,错误原因:{e}")

        # 记录发送日志
        with open(settings.PATH, 'ab') as f:
            log = f"发送时间:{time.strftime('%Y-%m-%d %H:%M:%S')} \t 服务器地址:{url} \t 返回结果:{message} \n"
            f.write(log.encode())
            print("日志记录成功!")
Ejemplo n.º 7
0
 def report_data():
     '''收集硬件信息,发送服务器'''
     info = info_collection.InfoCollection()
     asset_data = info.collect()
     data = {'asset_data': json.dumps(asset_data)}
     url = "http://{}:{}{}".format(settings.Params['server'],
                                   settings.Params['port'],
                                   settings.Params['url'])
     print('数据往{},发送'.format(url))
     try:
         #使用python内置urllib.request库,发送post请求
         #需要将数据进行封装,并转换成Bytes类型
         data_encode = urllib.parse.urlencode(data).encode()
         response = urllib.request.urlopen(
             url=url,
             data=data_encode,
             timeout=settings.Params['request_timeout'])
         message = response.read().decode()
         print('服务器返回结果: %s' % message)
     except Exception as e:
         message = "发送失败,错误原因:{}".format(e)
         print(message)
     with open(settings.PATH, 'ab') as f:
         log = "发送时间:{},URL地址{},\n返回结果{}\n".format(
             time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
         f.write(log.encode())
         print('日志记录成功')
Ejemplo n.º 8
0
    def report_asset(self):
        '''
        搜集数据并汇报
        '''

        # 实例化一个搜集信息实例
        obj = info_collection.InfoCollection()
        # 通过collect()搜集信息
        asset_data = obj.collect()
        # 获取资产id
        asset_id = self.load_asset_id(asset_data["sn"])
        if asset_id:  # 如果获取到资产id,资产数据中添加上资产id,并设置上传url
            asset_data["asset_id"] = asset_id
            post_url = "asset_report"

        else:
            '''
            会汇报到另外一个url,将这条资产信息添加到待批准区,批准后会返回资产id
            '''

            asset_data["asset_id"] = None
            post_url = "asset_report_with_no_id"

        # 将搜集的资产数据序列化下,传给__submit__data
        data = {"asset_data": json.dumps(asset_data)}
        # 不同的url,和资产数据传给__submit__data处理得到服务器返回的信息
        response = self.__submit_data(post_url, data, method="post")
        if "asset_id" in response:
            self.__update_asset_id(response["asset_id"])
        # 写入日志
        self.log_record(response)
Ejemplo n.º 9
0
 def report_data():
     """收集硬件信息,然后发送到服务器!"""
     info = info_collection.InfoCollection()
     asset_data = info.collect()
     # 将数据打包到一个字典内,并转换为json格式
     data = {"asset_data": json.dumps(asset_data)}
     # 根据settings中的配置,构造url
     url = "http://%s:%s%s" % (settings.Params["server"], settings.Params["port"], settings.Params["url"])
     print("正在将数据发送到:[%s] ......" % url)
     try:
         # 使用Python内置的urllib.request库,发送post请求
         # 需要先将数据进行封装,转换成bytes类型
         data_encode = urllib.parse.urlencode(data).encode()
         response = urllib.request.urlopen(url=url, data=data_encode, timeout=settings.Params["request_timeout"])
         print("\033[31;1m发送完毕!\033[0m")
         message = response.read().decode()
         print("返回结果:%s" % message)
     except Exception as e:
         message = "发送失败:" + "错误原因:{}".format(e)
         print("\033[31;1m发送失败,错误原因:%s\033[0m" % e)
     # 记录发送日志
     with open(settings.PATH, "ab") as f:        # 以byte方式写入,防止出现编码错误
         log = "发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n" % (time.strftime("%Y-%m-%d %H:%M:%S"), url, message)
         f.write(log.encode())
         print("记录日志成功!")
Ejemplo n.º 10
0
	def report_data():
		"""
		收集硬件信息,然后发送到服务器。
		:return:
		"""
		#收集信息
		info = info_collection.InfoCollection()
		asset_data = info.collect()
		#将数据打包到一个字典内,并转换为json格式
		data = {"asset_data": json.dumps(asset_data)}
		# 根据settings中的配置,构造url
		url = "http://{}:{}{}".format(settings.Params["server"],settings.Params['port'],settings.Params['url'])
		print('正在将数据发送至:[{}] ......'.format(url))
		try:
			#使用Python内置的urllib.request库,发送post请求。
			#需要先将数据进行封装,并转换成bytes类型
			data_encode = urllib.parse.urlencode(data).encode()
			response = urllib.request.urlopen(url=url,data=data_encode,timeout=settings.Params['request_timeout'])
			print("\033[31;1m发送完毕!\033[0m")
			message = response.read().decode()
			print("返回结果:{}".format(message))
		except Exception as e:
			message = '发送失败' + '错误原因:{}\033[0m'.format(e)
		#记录发送日志
		with open(settings.PATH,'ab') as f:#以byte的方式写入,防止出现编码错误
			log = '发送时间:{} \t 服务器地址:{} \t 返回结果:{} \n'.format(time.strftime('%Y-%m-%d %H:%M:%S'),url,message)
			f.write(log.encode())
			print("日志记录成功!")
Ejemplo n.º 11
0
 def report_asset(self):
     '''
     如果本地已经记录了asset_id,直接请求/asset/report/,如果服务器未找到匹配的记录就返回错误,找到了就更新
     如果本地没有asset_id,就请求/asset/report/asset_with_no_asset_id/,结果可能是提交新资产待审核或者返回丢失的asset_id,或者提示数据不合法
     '''
     obj = info_collection.InfoCollection()
     asset_data = obj.collect()
     asset_id = self.load_asset_id()
     if asset_id:  #本地已经记录了资产id,说明资产信息已经有记录
         asset_data['asset_id'] = asset_id
         post_url = 'asset_report'
     else:  #说明是第一次提交资产信息,或者asset_id丢失了
         #必须要加上这个字段,才能在服务端通过数据合法验证
         asset_data['asset_id'] = None
         post_url = 'asset_report_with_no_id'
     data = {'asset_data': json.dumps(asset_data)}
     response = self.__submit_data(post_url, data, method='post')
     # 返回的json字节串需要解码后才能反序列化
     response = response.decode('utf-8')
     response = json.loads(response)
     # asset_id丢失,返回的对象里会包含asset_id,存储到本地文件
     if 'asset_id' in response:
         self.__update_asset_id(response['asset_id'])
     # 提交结果记录日志
     self.log_record(response)
Ejemplo n.º 12
0
 def report_data():
     """
     收集硬件信息,然后发送到服务器。
     :return:
     """
     # 收集信息
     info = info_collection.InfoCollection()
     asset_data = info.collect()
     # 将数据打包到一个字典内,并转换为json格式
     data = {"asset_data": json.dumps(asset_data)}
     # 根据settings中的配置,构造url
     url = "http://%s:%s%s" % (settings.Params['server'], settings.Params['port'], settings.Params['url'])
     print('正在将数据发送至: [%s]  ......' % url)
     try:
         # 使用Python内置的urllib.request库,发送post请求。
         # 需要先将数据进行封装,并转换成bytes类型
         data_encode = urllib.parse.urlencode(data).encode()
         response = urllib.request.urlopen(url=url, data=data_encode, timeout=settings.Params['request_timeout'])
         print("\033[31;1m发送完毕!\033[0m ")
         message = response.read().decode()
         print("返回结果:%s" % message)
     except Exception as e:
         message = "发送失败"
         print("\033[31;1m发送失败,%s\033[0m" % e)
     # 记录发送日志
     with open(settings.PATH, 'ab') as f:
         string = '发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n' % (time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
         f.write(string.encode())
         print("日志记录成功!")
Ejemplo n.º 13
0
 def report_data():
     info = info_collection.InfoCollection()
     asset_data = info.collect()
     data = {'asset_data': json.dumps(asset_data)}
     url = "http://%s:%s%s" % (setting.Params['server'],
                               setting.Params['port'],
                               setting.Params['url'])
     print('正将数据发送至:[%s]……' % url)
     try:
         data_encode = urllib.parse.urlencode(data).encode()
         response = urllib.request.urlopen(
             url=url,
             data=data_encode,
             timeout=setting.Params['request_timeout'])
         print("\033[31;1m发送完毕!\033[0m ")
         message = response.read().decode()
         print("返回结果:%s" % message)
     except Exception as e:
         message = '发送失败' + " 错误原因:{}".format(e)
         print("\033[31;1m发送失败,错误原因: %s\033[0m" % e)
     with open(setting.PATH, 'ab') as f:
         log = '发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n' % (
             time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
         f.write(log.encode())
         print('日志记录成功!')
Ejemplo n.º 14
0
    def report_data():
        """
        收集硬件信息,然后发送到服务器
        :return:
        """
        info = info_collection.InfoCollection()
        asset_data = info.collect()

        data = {"asset_data": json.dumps(asset_data)}

        url = "http://%s:%s%s" % (settings.Params['server'],
                                  settings.Params['port'],
                                  settings.Params['url'])

        try:
            data_encode = urllib.parse.urlencode(data).encode()
            logger.info('Send asset %s to %s' % (data, url))
            response = urllib.request.urlopen(
                url=url,
                data=data_encode,
                timeout=settings.Params['request_timeout'])
            msg = response.read().decode()

            logger.info('Response %s from %s' % (msg, url))
        except Exception as e:
            logger.warning('发送失败,错误原因:%s' % e)
Ejemplo n.º 15
0
    def report_data():
        """
        收集硬件信息,然后发送到服务器。
        :return:
        """

        info = info_collection.InfoCollection()
        asset_data = info.collect()

        data = {'asset_data': json.dumps(asset_data)}
        url = "http://%s:%s%s" % (settings.Params['server'], settings.Params['port'], settings.Params['url'])
        print('正在将数据发送至: [%s]  ......' % url)
        try:

            r = requests.post(url=url, data=data, timeout=settings.Params['request_timeout'])
            print("\033[31;1m发送完毕!\033[0m ")
            print(r.text)




        except Exception as e:
            message = '发送失败' + "   错误原因:  {}".format(e)
            print("\033[31;1m发送失败,错误原因: %s\033[0m" % e)
        # 记录发送日志
        with open(settings.PATH, 'ab') as f:  # 以byte的方式写入,防止出现编码错误
            log = '发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n' % (time.strftime('%Y-%m-%d %H:%M:%S'), url, r.text)
            f.write(log.encode())
            print("日志记录成功!")
Ejemplo n.º 16
0
    def report_data():
        '''
		收集硬件信息 发送至服务器
		:return:
		'''

        # 收集信息
        info = info_collection.InfoCollection()
        asset_data = info.collect()
        # 将数据打包到字典 转为json
        data = {"asset_data": json.dumps(asset_data)}
        # 根据settings 配置 构造URL
        url = "http://%s:%s%s" % (settings.Params['server'],
                                  settings.Params['port'],
                                  settings.Params['url'])
        print('正在将数据发送至:%s .....' % url)

        try:
            data_encode = urllib.parse.urlencode(data).encode()
            response = urllib.request.urlopen(
                url=url,
                data=data_encode,
                timeout=settings.Params['request_timeout'])
            print("\033[31;1m发送完毕! \033[0m ")
            message = response.read().decode()
            print("返回结果: %s" % message)
        except Exception as e:
            message = "发送失败"
            print("\033[31;1m发送失败,%s\033[0m" % e)
        with open(settings.PATH, 'ab') as f:
            string = '发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n' % (
                time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
Ejemplo n.º 17
0
    def report_data():
        info = info_collection.InfoCollection()
        asset_data = info.collect()

        data = {'asset_data': json.dumps(asset_data)}
        url = 'http://%s:%s%s' % (settings.Params['server'],
                                  settings.Params['port'],
                                  settings.Params['url'])
        print('正在将数据发送至:【%s】。。。。' % url)

        try:
            data_encode = urllib.parse.urlencode(data).encode()

            response = urllib.request.urlopen(
                url=url,
                data=data_encode,
                timeout=settings.Params['request_timeout'])
            print('\033[31;1m发送完毕!\033[0m ')
            message = response.read().decode()
            print('返回结果:%s' % message)

        except Exception as e:
            message = '发送失败'
            print('\033[31;1m发送失败,%s\033[0m' % e)

        with open(settings.PATH, 'ab') as f:
            string = '发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n' % (
                time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
            f.write(string.encode())
            print('日志记录成功!')
Ejemplo n.º 18
0
    def report_asset(self):
        '''
        1. 通过collect方法获取硬件信息
            通过判断是否有asset_id将客户端硬件信息发送到不同的URL上
        :return:
        '''
        obj = info_collection.InfoCollection()
        asset_data = obj.collect()
        asset_id = self.load_asset_id()
        if asset_id:  #reported to server before
            asset_data["asset_id"] = asset_id
            post_url = "asset_report"

        else:  #first time report to server
            '''report to another url,this will put the asset into approval waiting zone, when the asset is approved ,this request returns
            asset's ID'''

            asset_data["asset_id"] = None
            post_url = "asset_report_with_no_id"

        data = {
            "asset_data": json.dumps(asset_data)
        }  #动过post方式将数据提交给服务端,key=asset_data
        response = self.__submit_data(post_url, data, method="post")
        if "asset_id" in response:
            self.__update_asset_id(response["asset_id"])

        self.log_record(response)
Ejemplo n.º 19
0
 def report_data():
     """收集硬件信息,然后发送到服务器。"""
     info = info_collection.InfoCollection()
     asset_data = info.collect()  # 收集信息
     # 将数据打包到一个字典内,并转换为json格式
     data = {'asset_data': json.dumps(asset_data)}
     # 根据settings中的配置,构造url
     url = "http://%s:%s%s" % (settings.Params['server'],
                               settings.Params['port'],
                               settings.Params['url'])
     print('----正在发送数据到:[%s]----' % url)
     try:
         # 使用Python内置的urllib.request库,发送post请求。
         # 需要先将数据进行封装,并转换成bytes类型
         data_encode = urllib.parse.urlencode(data).encode()
         response = urllib.request.urlopen(
             url=url,
             data=data_encode,
             timeout=settings.Params['request_timeout'])
         print('\033[31;1m发送完毕!033[0m ')
         message = response.read().decode()
         print('返回结果: %s' % message)
     except Exception as e:
         message = '发送失败' + '失败原因:{}'.format(e)
         print('\033[31;1m 发送失败,失败原因:%s 033[0m ' % message)
     # 记录发送日志
     with open(settings.PATH, 'ab') as f:
         log = '发送时间:%s,\t服务器地址:%s \t 返回结果:%s\n' % \
         (time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
         f.write(log.encode())
         print('日志记录成功!')
Ejemplo n.º 20
0
 def report_asset(self):
     '''
     该方法用于连接指定url汇报资产信息,并获取对应url的返回结果
     客户端连接到服务器后,服务器会返回一个资产id到客户端,客户端拿到资产id后,
     会存到一个指定的文件里面. 下次客户端再次联系服务器端时,就会带着这个资产id,
     这样服务器端就知道客户端是台老机器. 这样服务器端就根据这个id拿数据库里面的数据
     进行比对,如果有不一样的就更新一下资产信息.
     如果客户端没有资产id发过去,那么证明客户端是第一次连接服务器,服务器端就认为这是一台新加入的机器.
     当我们批准这台机器加入后,服务器端会返回一个id给客户端,这样下次客户端再连接时就有资产id了
     '''
     obj = info_collection.InfoCollection()
     # asset_data包含了cpu/内存/主机类型/网卡等各种信息的字典
     asset_data = obj.collect()
     # 如何确定这台机器是新机器呢?就是看你有没有传资产id在服务端,如果有,则不是新机器,如果没有则是第一次连接
     asset_id = self.load_asset_id(asset_data['sn'])
     if asset_id:  # 如果有id,证明之前汇报过
         asset_data['asset_id'] = asset_id
         post_url = 'asset_report'
     else:  # 第一次连接server,如果没有资产id,则向另一个url汇报
         asset_data['asset_id'] = None
         post_url = 'asset_report_with_no_id'
     print('post_url', post_url)
     data = {'asset_data': json.dumps(asset_data)}
     # 将数据以post的方法提交到submit_data函数,该函数会请求指定的url,将客户端的数据提交上去,并获取返回的结果
     response = self.__submit_data(post_url, data, method='post')
     print('response:', response)
     if 'asset_id' in response:
         self.__update_asset_id(response['asset_id'])
     self.log_record(response)
Ejemplo n.º 21
0
 def report_data():
     info = info_collection.InfoCollection()
     asset_data = info.collect()
     #把数据打包为一个字典里面
     data = {"asset_data": json.dumps(asset_data)}
     #根据settings里面的配置构造url
     url = "http://%s:%s%s" % (settings.Params['server'],
                               settings.Params['port'],
                               settings.Params['url'])
     print("正在发送数据到:[%s}" % url)
     try:
         #使用python内置的urllib.request库,发送post请求,需要先将数据进行封装,并转换成bytes
         data_encode = urllib.parse.urlencode(data).encode()
         response = urllib.request.urlopen(
             url=url,
             data=data_encode,
             timeout=settings.Params['request_timeout'])
         print("\033[31;1m发送完毕!\033[0m ")
         message = response.read().decode()
         print("返回结果:%s" % message)
     except Exception as e:
         message = "发送失败"
         print("\033[31;1m发送失败,%s\033[0m" % e)
         # 记录发送日志
     with open(settings.PATH, 'ab') as f:
         string = '发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n' % (
             time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
         f.write(string.encode())
         print("日志记录成功!")
Ejemplo n.º 22
0
    def report_data():
        """
        收集硬件信息,然后发送到服务器。
        :return:
        """

        info = info_collection.InfoCollection()
        asset_data = info.collect()

        data = {'asset_data': json.dumps(asset_data)}
        url = "http://%s:%s%s" % (settings.Params['server'], settings.Params['port'], settings.Params['url'])
        print('正在将数据发送至: [%s]  ......' % url)
        try:
            # 使用Python内置的urllib.request库,发送post请求。
            # 需要先将数据进行封装,并转换成bytes类型
            data_encode = urllib.parse.urlencode(data).encode()
            response = urllib.request.urlopen(url=url, data=data_encode, timeout=settings.Params['request_timeout'])
            print("\033[31;1m发送完毕!\033[0m ")
            message = response.read().decode()
            print("返回结果:%s" % message)
        except Exception as e:
            message = '发送失败' + "   错误原因:  {}".format(e)
            print("\033[31;1m发送失败,错误原因: %s\033[0m" % e)
        # 记录发送日志
        with open(settings.PATH, 'ab') as f:  # 以byte的方式写入,防止出现编码错误
            log = '发送时间:%s \t 服务器地址:%s \t 返回结果:%s \n' % (time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
            f.write(log.encode())
            print("日志记录成功!")
Ejemplo n.º 23
0
    def report_data():
        """收集硬件信息并且上报"""
        info = info_collection.InfoCollection()
        asset_data = info.collect()
        print(asset_data)

        data = {"asset_data": json.dumps(asset_data)}
        url = "http://%s:%s%s" % (settings.Params['server'],
                                  settings.Params['port'],
                                  settings.Params['url'])
        print("正在上传数据到【%s】......." % url)
        try:
            data_encode = urllib.parse.urlencode(data).encode()
            response = urllib.request.urlopen(
                url=url,
                data=data_encode,
                timeout=settings.Params['request_timeout'])
            print("发送完毕")
            message = response.read().decode()
            print("返回结果:%s" % message)
        except Exception as e:
            message = "发送失败" + "失败原因 :{}".format(e)
            print("发送失败原因:%s" % e)
        with open(settings.PATH, 'ab') as f:
            log = "发送时间:%s\t服务器地址:%s\t 返回结果 :%s\n" % (
                time.strftime('%Y-%m-%d %H:%M:%S'), url, message)
            f.write(log.encode())
            print("日志记录成功")
Ejemplo n.º 24
0
 def collect_data():
     """
     收集硬件信息
     :return:
     """
     info = info_collection.InfoCollection()
     asset_data = info.collect()
     print(asset_data)
Ejemplo n.º 25
0
 def collect_data(self):
     """
     obj: 实例化Infocollection类
     asset_data: 收集硬件信息
     :return:返回硬件信息字典
     """ ""
     obj = info_collection.InfoCollection()
     asset_data = obj.collect()
Ejemplo n.º 26
0
    def collect_data():
        '''
		收集硬件信息 用于测试

		:return:
		'''
        info = info_collection.InfoCollection()
        asset_data = info.collect()
        print(asset_data)
Ejemplo n.º 27
0
    def collect_data():
        """
        Collect Device Info, used for testing
        :return:
        """

        info = info_collection.InfoCollection()
        asset_data = info.collect()
        print(asset_data)
Ejemplo n.º 28
0
 def get_asset_id(self):
     asset_id = self.load_asset_id()
     if asset_id:
         print("asset_id = ", asset_id)
     else:
         data_obj = info_collection.InfoCollection()
         asset_data = data_obj.collection()
         sn = asset_data["sn"]
         print("======not save asset_id=======")
         print "sn is ", sn
Ejemplo n.º 29
0
    def report_asset(self):
        obj = info_collection.InfoCollection()
        # 获取收集的信息
        asset_data = obj.collect()
        # 取到post  url
        post_url = "asset_report"
        data = {"asset_data": json.dumps(asset_data)}
        response = self.__submit_data(post_url, data, method="post")

        self.log_record(response)
Ejemplo n.º 30
0
    def report_data():
        """
        收集硬件信息,然后发送到服务器。
        :return:
        """
        # 收集信息
        info = info_collection.InfoCollection()
        asset_data = info.collect()
        # 将数据打包到一个字典内,并转换为 json 格式
        data = {"asset_data": json.dumps(asset_data)}
        # 根据 settings 中的配置,构造URL
        url = "http://%s:%s%s" % (settings.Params['server'],
                                  settings.Params['port'],
                                  settings.Params['url'])
        print('正在将数据发送至:[%s] ......' % url)
        """
        Python2 中 urllib 的 urlencode 在 Python3 中分别拆分到 urllib.parse;
        urllib2 的 urlopen 拆分到 urllib.request
        因此,需要判断当前 Python 版本,并导入对应的库
        """
        if sys.version_info >= (3, 0):
            import urllib.request as request
            import urllib.parse as parse
        else:
            import urllib2 as request
            import urllib as parse

        try:
            # 使用 Python 内置的 urllib.request库,发送 post 请求。
            # 需要先将数据进行封装,并转换成bytes 类型(这里urlencode处理的数据用作 POST操作,必须编码为bytes,否则将导致TypeError)

            data_encode = parse.urlencode(data).encode()
            response = request.urlopen(
                url=url,
                data=data_encode,
                timeout=settings.Params['request_timeout'])

            print("\033[31;1m发送完毕!\033[0m")
            message = response.read().decode() if sys.version_info >= (
                3, 0) else response.read(
                )  # if isinstance(response.read(), bytes) else response.read()
            print("返回结果:%s" % message)
        except Exception as e:
            message = "发送失败" + "  错误原因:{}".format(e)
            print("\033[31;1m发送失败,错误原因:%s\033[0m" % e)

        # 记录发送日志
        with open(settings.PATH, 'ab') as f:
            log = "发送时间:%s \t 服务器地址: %s \t 返回结果:%s \n" % (
                time.strftime("%Y-%m-%d %H:%M:%S"), url, message)
            log = log.encode() if sys.version_info >= (3, 0) else log
            f.write(log)
            print("日志记录成功")