python项目总结

最近在写python的工具, 总结一下.

  1. type(变量名字) # 可以打印变量类型,以方便处理

  2. len(var)#可获取类型长度

  3. binascii.a2b_hex(string) # 将十六进制数字字符串转换为二进制数据。该函数也称为unhexlify(string)

  4. binascii.b2a_hex(string)
    python 字符串与16进制互转

  5. python 打印对象的所有属性值的方法.

    def prn_obj(obj): 
      print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()]) 
    

    以上是打印某个对象的所有属性值的方法

  6. python 获取对象信息

  7. pdb 调试
    [python调试方法] (https://www.cnblogs.com/skyus/p/7210234.html)

  8. plain_text.rstrip('\0') #删除字符串末尾0字符

  9. 编译protocol Buffers
    Now that you have a .proto, the next thing you need to do is generate the classes you’ll need to read and write AddressBook (and hence Person and PhoneNumber) messages. To do this, you need to run the protocol buffer compiler protoc on your .proto:
    If you haven’t installed the compiler, download the package and follow the instructions in the README.
    Now run the compiler, specifying the source directory (where your application’s source code lives – the current directory is used if you don’t provide a value), the destination directory (where you want the generated code to go; often the same as $SRC_DIR), and the path to your .proto. In this case, you…:
    protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/addressbook.proto
    Because you want Python classes, you use the --python_out option – similar options are provided for other supported languages.
    This generates addressbook_pb2.py in your specified destination directory.

  10. hashlib.sha256(data) # 计算data的哈希值

    >>> import hashlib
    >>> a = hashlib.sha256('aaaa')
    >>> a.update('bbbb')  #将新的数据和旧的数据一起计算哈希值
    >>> a.digest()
    '\xe5\xc1\xed\xb5\x0f\xf8\xb4\xfc\xc3\xea\xd3\xa8E\xff\xbe\x1a\xd5\x1c\x9d\xae]D3Z\\3;W\xac\x8d\xf0b'
    >>> b = hashlib.sha256('aaaabbbb') #相同数据对比update的计算哈希值是相同的
    >>> b.digest()
    '\xe5\xc1\xed\xb5\x0f\xf8\xb4\xfc\xc3\xea\xd3\xa8E\xff\xbe\x1a\xd5\x1c\x9d\xae]D3Z\\3;W\xac\x8d\xf0b'
    >>> b.hexdigest()  # 获取十六进制字符串
    'e5c1edb50ff8b4fcc3ead3a845ffbe1ad51c9dae5d44335a5c333b57ac8df062'
    

    python hashlib模块

  11. logging 日志级别,网上例子很多

  12. python struct模块
    解决字节序问题,字节对齐,

    self.version = struct.unpack('>Q', payload_file.read(8))[0]
    self.manifest_len = struct.unpack('>Q', payload_file.read(8))[0] 
    self.metadata_signature_len = struct.unpack('>I', payload_file.read(4))[0]
    

    Python之struct简介
    浅析Python中的struct模块

  13. 用到’openssl’ 这个比较复杂

     def _CheckSha256Signature(sig_data, cert_file_name, actual_hash, sig_name):
        if len(sig_data) != 256:
          logger.info('%s: signature size (%d) not as expected (256).' % sig_name, len(sig_data))
        signed_data, err = RunCommand(['openssl', 'rsautl', '-verify', '-certin', '-inkey', cert_file_name ], send_data=sig_data)
    
        if len(signed_data) != len(SIG_ASN1_HEADER) + 32:
          logger.info('%s: unexpected signed data length (%d).', sig_name, len(signed_data))
    
        if not signed_data.startswith(SIG_ASN1_HEADER):
          logger.info('%s: not containing standard ASN.1 prefix.', sig_name)
    
        signed_hash = signed_data[len(SIG_ASN1_HEADER):]
        if signed_hash != actual_hash:
          logger.info('%s: signed hash (%s) different from actual (%s).', sig_name, signed_hash.encode('base64').strip(), 
    

    直接输入
    openssl x509 -in ca.crt -pubkey
    的确会看到两个公钥输出,
    如果将它转换成der格式文件的公钥文件,则没有任何多余输出
    openssl x509 -in ca.crt -inform PEM -out ca.der -outform DER

    提取公钥
    openssl x509 -in out/otacert -pubkey -noout > pubkey.pem
    /使用公钥进行验证/
    $ openssl rsautl -verify -in sign1.txt -inkey pub.pem -pubin -out replain1.txt
    /使用私钥进行签名/
    $ openssl rsautl -sign -in plain.txt -inkey pri.pem -out sign1.txt
    公钥加密
    openssl rsautl -encrypt -inkey publickey.pem -pubin -in key.bin -out key.bin.en
    将kpcs8 转换到.pem 私钥
    openssl pkcs8 -inform DER -nocrypt -in testkey.pk8 -out testkey.pem
    直接使用证书进行验签,实际也是使用公钥
    openssl rsautl -verify -certin -inkey out/otacert -in old_data -out replain.txt
    使用 openssl 生成证书(含openssl详解)
    https://blog.csdn.net/gengxiaoming7/article/details/78505107

  14. AES128 对称加密
    AES加密算法的详细介绍与实现

  15. subprocess模块

    def RunCommand(command, send_data = None):
      logger.info('Running command, please wait....')
      logger.debug('command: %s', command)
      child = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      try:
        result, err = child.communicate(input = send_data)#利用管道输入数据. 和返回数据
      finally:
        exit_code = child.wait()
      if exit_code:
        raise RuntimeError('Subprocess %r failed with code %r.' %
                           (command, exit_code))
      return result, exit_code
    
  16. import argparse 模块

    import argparse
    parser=argparse.ArgumentParser()
    parser.add_argument("echo",help="echo the string")
    args=parser.parse_args()
    print args.echo
    

    Python命令行解析argparse常用语法使用简介

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章