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常用語法使用簡介

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