• python之hashlib、configparser、logging模块


    hashlib模块

    Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。

    什么是摘要算法呢?摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。

    摘要算法就是通过摘要函数f()对任意长度的数据data计算出固定长度的摘要digest,目的是为了发现原始数据是否被人篡改过。

    摘要算法之所以能指出数据是否被篡改过,就是因为摘要函数是一个单向函数,计算f(data)很容易,但通过digest反推data却非常困难。而且,对原始数据做一个bit的修改,都会导致计算出的摘要完全不同。

    我们以常见的摘要算法MD5为例,计算出一个字符串的MD5值:

    import hashlib
    str="这是一串需要加密的字符"
    md5=hashlib.md5()
    md5.update(str.encode())
    print(md5.hexdigest())#输出  760fcfd067fbe67f40a4758f8a07d62c

    如果数据量很大,可以考虑进行多次update,最后计算结果跟一次update全部值是一样的

    如:

    import hashlib
    str="这是一串需要加密的字符"
    md5=hashlib.md5()
    md5.update(str.encode())
    print(md5.hexdigest())#输出   760fcfd067fbe67f40a4758f8a07d62c
    md5=hashlib.md5()
    md5.update("这是一串".encode())
    md5.update("需要加密的字符".encode())
    print(md5.hexdigest())#输出   760fcfd067fbe67f40a4758f8a07d62c

    同样,我们也可以由此对一个文件进行加密

    import hashlib
    md5=hashlib.md5()
    with open('file','rb') as f:#打开一个名为file的文件
        for i in f:
            md5.update(i)#对文件逐行进行加密
    print(md5.hexdigest())#输出
        

    MD5是最常见的摘要算法,速度很快,生成结果是固定的128 bit字节,通常用一个32位的16进制字符串表示。另一种常见的摘要算法是SHA1,调用SHA1和调用MD5完全类似:

    import hashlib
    str="昨夜你曾经说,愿夜幕永不开启"
    sha1=hashlib.sha1()
    sha1.update(str.encode())
    print(sha1.hexdigest())#输出   c7b66b7c1b39674a85f7c7ae9c8a1a54a2fdef47
    sha1=hashlib.sha1()
    sha1.update("昨夜你曾经说,".encode())
    sha1.update("愿夜幕永不开启".encode())
    print(sha1.hexdigest())#输出   c7b66b7c1b39674a85f7c7ae9c8a1a54a2fdef47

    SHA1的结果是160 bit字节,通常用一个40位的16进制字符串表示。比SHA1更安全的算法是SHA128,SHA256和SHA512,不过越安全的算法越慢,而且摘要长度更长。

    import hashlib
    str="昨夜你曾经说,愿夜幕永不开启"
    sha1=hashlib.sha256()
    sha1.update(str.encode())
    print(sha1.hexdigest())#输出   01193adaee0dc6cb58ee6b9f02e67d0ed9d8c6152f85766fd7323e26d9330bf2
    sha1=hashlib.sha256()
    sha1.update("昨夜你曾经说,".encode())
    sha1.update("愿夜幕永不开启".encode())
    print(sha1.hexdigest())#输出   01193adaee0dc6cb58ee6b9f02e67d0ed9d8c6152f85766fd7323e26d9330bf2

    “加盐”加密

    加盐加密是一种对系统登录口令的加密方式,它实现的方式是将每一个口令同一个叫做”盐“(salt)的n位随机数相关联。无论何时只要口令改变,随机数就改变。随机数以未加密的方式存放在口令文件中,这样每个人都可以读。不再只保存加密过的口令,而是先将口令和随机数连接起来然后一同加密,加密后的结果放在口令文件中。

    hashlib模块中进行加盐加密,如下:

    import hashlib
    str="昨夜你曾经说,愿夜幕永不开启"
    md5=hashlib.md5('salt'.encode())#这是加的盐
    md5.update(str.encode())
    print(md5.hexdigest())#输出   1d651299f0dbfe3dc7a3e5e12b719874
    md5=hashlib.md5()#此处未加盐
    md5.update("昨夜你曾经说,".encode())
    md5.update("愿夜幕永不开启".encode())
    print(md5.hexdigest())#输出   379049e0da6515a6051c2909d0d1f2ee

    我们同样可以把盐(salt)换成我们设计好的字符串,从而使加密更加安全

    configparser模块

    该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

    如,我们经常看到以下这种格式的文件

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
      
    [bitbucket.org]
    User = hg
      
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no

    我们同样可以用python生成这样一个文件

    import configparser
    
    config = configparser.ConfigParser()
    
    config["DEFAULT"] = {'ServerAliveInterval': '45',
                          'Compression': 'yes',
                         'CompressionLevel': '9',
                         'ForwardX11':'yes'
                         }
    
    config['bitbucket.org'] = {'User':'hg'}
    
    config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
    
    with open('example.ini', 'w') as configfile:
    
       config.write(configfile)

    查找

    import configparser
    
    config = configparser.ConfigParser()
    
    #---------------------------查找文件内容,基于字典的形式
    
    print(config.sections())        #  []
    
    config.read('example.ini')
    
    print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']
    
    print('bytebong.com' in config) # False
    print('bitbucket.org' in config) # True
    
    
    print(config['bitbucket.org']["user"])  # hg
    
    print(config['DEFAULT']['Compression']) #yes
    
    print(config['topsecret.server.com']['ForwardX11'])  #no
    
    
    print(config['bitbucket.org'])          #<Section: bitbucket.org>
    
    for key in config['bitbucket.org']:     # 注意,有default会默认default的键
        print(key)
    
    print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
    
    print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
    
    print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value

    增删改

    import configparser
    
    config = configparser.ConfigParser()
    
    config.read('example.ini')
    
    config.add_section('yuan')
    
    
    
    config.remove_section('bitbucket.org')
    config.remove_option('topsecret.server.com',"forwardx11")
    
    
    config.set('topsecret.server.com','k1','11111')
    config.set('yuan','k2','22222')
    
    config.write(open('new2.ini', "w"))

     logging模块

    python同样提供logging日志记录模块,以下是logging模块配置参数

    logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:
    
    filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
    filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
    format:指定handler使用的日志显示格式。
    datefmt:指定日期时间格式。
    level:设置rootlogger(后边会讲解具体概念)的日志级别
    stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
    
    format参数中可能用到的格式化串:
    %(name)s Logger的名字
    %(levelno)s 数字形式的日志级别
    %(levelname)s 文本形式的日志级别
    %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
    %(filename)s 调用日志输出函数的模块的文件名
    %(module)s 调用日志输出函数的模块名
    %(funcName)s 调用日志输出函数的函数名
    %(lineno)d 调用日志输出函数的语句所在的代码行
    %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
    %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
    %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
    %(thread)d 线程ID。可能没有
    %(threadName)s 线程名。可能没有
    %(process)d 进程ID。可能没有
    %(message)s用户输出的消息

    logging简单测试

    import logging  
    logging.debug('debug message')  
    logging.info('info message')  
    logging.warning('warning message')  
    logging.error('error message')  
    logging.critical('critical message'

    默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。

    logging自定义格式输出

    import logging
    
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename='test.log',
                        filemode='w')
    
    logging.debug('debug message')
    logging.info('info message')
    logging.warning('warning message')
    logging.error('error message')
    logging.critical('critical message')

    生成test.log文件,内容如下

    logging对象配置

    import logging
    
    logger = logging.getLogger()
    # 创建一个handler,用于写入日志文件
    fh = logging.FileHandler('test.log',encoding='utf-8') 
    
    # 再创建一个handler,用于输出到控制台 
    ch = logging.StreamHandler() 
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setLevel(logging.DEBUG)
    
    fh.setFormatter(formatter) 
    ch.setFormatter(formatter) 
    logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 
    logger.addHandler(ch) 
    
    logger.debug('logger debug message') 
    logger.info('logger info message') 
    logger.warning('logger warning message') 
    logger.error('logger error message') 
    logger.critical('logger critical message')

    logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。另外,可以通过:logger.setLevel(logging.Debug)设置级别,当然,也可以通过

    fh.setLevel(logging.Debug)单对文件流设置某个级别。

    其他常用模块

    其他常用模块:http://www.cnblogs.com/qflyue/p/8259772.html

  • 相关阅读:
    uva10341
    android_定义多个Activity及跳转
    阿里巴巴2014年校园招聘(秋季招聘)在线笔试--測试研发project师
    关于程序猿的几个阶段!
    【Spring】Spring学习笔记-01-入门级实例
    感知器算法(二分类问题)
    Ubuntu14.04下安装ZendStudio10.6.1+SVN出现Failed to load JavaHL Library
    EF架构~关系表插入应该写在事务里,但不应该是分布式事务
    EF架构~在global.asax里写了一个异常跳转,不错!
    EF架构~为导航属性赋值时ToList()的替换方案
  • 原文地址:https://www.cnblogs.com/qflyue/p/8342581.html
Copyright © 2020-2023  润新知