python基础(二十九)—常用模块补充
hashlib
摘要算法
python的hashlib提供了常见的摘要算法,如MD5,SHA1等
两端使用算法一致,那么你对同一个字符串的多次摘要不会有变化
import hashlib md5_obj = hashlib.md5 # md5算法的对象 md5_obj.update(b'alex3714') #必须是base类型 # 使用md5摘要算法对'alex3714'进行摘要 ret = md5_obj.hexdigesr() print(ret) # 无论摘要多少次结果都一样 import hashlib sha1_obj = hashlib.sha1 sha1_obj.update(b'alex3714') #必须是base类型 ret = sha1_obj.hexdigesr() print(ret) # 无论摘要多少次结果都一样
MD5是最常见的摘要算法,速度很快,生成结果是固定的128 bit字节,通常用一个32位的16进制字符串表示。另一种常见的摘要算法是SHA1,调用SHA1和调用MD5完全类似.
SHA1的结果是160 bit字节,通常用一个40位的16进制字符串表示。比SHA1更安全的算法是SHA256和SHA512,不过越安全的算法越慢,而且摘要长度更长。
摘要算法的应用
通过撞库可以破解用户设置的密码
加盐
import hashlib # 进行加盐操作,可以增加密码安全。 md5_boj = hashlib.md5('盐'.encode('utf-8')) md5_boj.update(b'alex3714') ret = md5_boj.hexdigest() print(ret)
动态加盐
import hashlib uaername = 'alex' md5_boj = hashlib.md5(uaername .encode('utf-8')+'盐'.encode('utf-8'))
md5_boj.update(b'alex3714')
ret = md5_boj.hexdigest() print(ret)
configparser模块
常见文档格式
[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是一个操作配置文件的对象 config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } config['bitbucket.org'] = {'User':'hg'} config['topsecret.server.com'] = {'HostPort':'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模块

浙公网安备 33010602011771号