2014-10-01 23 views
0

我有以下的功能,即从UDP插槽读取,并追加到一个字符串data解压需要长度43的字符串参数 - Python的

DATA_SIZE = 2048 
def handle_read(self): 
     """ 
     This handles the incoming ntp response 
     """ 
     try: 
      data = "" 
      while 1: 
       current_data, _ = self.recvfrom(self.DATA_SIZE) 
       self.log.info("msg: %s" % current_data) 
       (header, length, typeID, param1, param2, 
       param3, param4, name_string, checksum, footer, 
       ) = struct.unpack("!2B I 4H 24s I B", current_data) 
       print (header, length, typeID, param1, param2, 
       param3, param4, name_string, checksum, footer, 
       ) 
       if not current_data: 
        break 
       data += current_data 
      self.log.info(data) 
      # parse with the pysnmp into a summary 
     except Exception, e: 
      self.log.exception("The following exception happened: %s" % e) 
     finally: 
      self.handle_close() 

当我执行的代码我得到:

File "hello.py", line 67, in handle_read 
    ) = struct.unpack("!2B I 4H 24s I B", current_data) 
error: unpack requires a string argument of length 43 

我试着调整字符串参数的大小,但有相同的错误。该功能的基本功能是从self.recvfrom()中读取并追加到data。有人可以帮忙吗? 的self.recvfrom()的结构是在一对像:

0xpublic?kC0^0+>Linux manager 3.4.30 #1 SMP Wed Sep 3 11:31:42 UTC 2014 x86_64+C?R? 
('1.2.3.4', 161) 

这是SNMP消息我发现了从服务器返回,并且我与之通信的服务器的IP。这个想法是将SNMP MIB附加到该字符串中。

+0

数据的大小必须与您的格式说明符相匹配。它没有。我不确定我们在这里能够帮到什么。 – NPE 2014-10-01 16:45:53

+0

您可以扩展如何'self.recvfrom(self.DATA_SIZE)'的结构预计看起来像,以及如何你希望'struct.unpact'修改它之前追加到数据? – 2014-10-01 16:49:45

+0

@ user3197452我会发布样本... – cybertextron 2014-10-01 16:53:11

回答

0

您的代码正在读取长达2048个字节的数据报,然后解码前43个字节以记录smtp信息。问题是数据报可能多于或少于43个字节。我认为你可以通过使用unpack_from解码消息的第一部分并简单地拒绝那些太小的消息来解决你的问题。预编译结构会节省一些时间,所以我也是这样做的。

class Whatever(object): 

    DATA_SIZE = 2048 
    snmp_header = struct.Struct("!2B I 4H 24s I B") 

    def handle_read(self): 
      """ 
      This handles the incoming snmp response 
      """ 
      try: 
       data = "" 
       while 1: 
        current_data, _ = self.recvfrom(self.DATA_SIZE) 
        self.log.info("msg: %s" % current_data) 
        if len(current_data) >= self.snmp_header.size: 
         (header, length, typeID, param1, param2, 
         param3, param4, name_string, checksum, footer, 
         ) = self.snmp_header.unpack_from("!2B I 4H 24s I B", current_data) 
         print (header, length, typeID, param1, param2, 
         param3, param4, name_string, checksum, footer, 
         ) 
        else: 
         print("received datagram too small") 
        if not current_data: 
         break 
        data += current_data 
       self.log.info(data) 
       # parse with the pysnmp into a summary 
      except Exception, e: 
       self.log.exception("The following exception happened: %s" % e) 
      finally: 
       self.handle_close() 
相关问题