python常用模块(3)
hashlib模块
hashlib提供了常见的摘要算法,如md5和sha1等等。
那么什么是摘要算法呢?摘要算法又称为哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。
注意:摘要算法不是一个解密算法。(摘要算法,检测一个字符串是否发生了变化)
应涂:1.做文件校验
2.登录密码
密码不能解密,但可以撞库,用‘加盐’的方法就可以解决撞库的问题。所有以后设置密码的时候要设置的复杂一点。
import hashlib
2 # md5_obj = hashlib.md5() 未加盐
3 md5_obj = hashlib.md5('nezha'.encode('utf-8')) #加盐后(就让你的密码更牢固了)
4 md5_obj.update('123456'.encode('utf-8'))
5 print(md5_obj.hexdigest())
6 md5_obj.update('hello'.encode('utf-8'))
7 print(md5_obj.hexdigest())
8 # -----------
9 user = 'haiyan'
10 password = '123456'
11 md5_obj= hashlib.md5(user.encode('utf-8')) #加盐(哪怕被人的密码和你的密码一样,
12 # 那你加盐以后就只有你的用户名对应的是你的密码了)
13 md5_obj.update(password.encode('utf-8'))
14 print(md5_obj.hexdigest())
import hashlib
2 md5_obj = hashlib.md5()
3 import os
4 filesize = os.path.getsize('filename') #文件大小
5 f = open('filename','rb')
6 while filesize>0:
7 if filesize > 1024:
8 content = f.read(1024)
9 filesize -= 1024
10 else:
11 content = f.read(filesize)
12 filesize -= filesize
13 md5_obj.update(content)
14 # for line in f:
15 # md5_obj.update(line.encode('utf-8'))
16 md5_obj.hexdigest()
configparser模块
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
1.创建文件
import configparser
2 config = configparser.ConfigParser()
3 config["DEFAULT"] = {'ServerAliveInterval': '45',
4 'Compression': 'yes',
5 'CompressionLevel': '9',
6 'ForwardX11':'yes'
7 }
8 config['bitbuck et.org'] = {'User':'hg'}
9 config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
10 with open('example.ini', 'w') as configfile:
11 config.write(configfile) 2.查找文件
import configparser
2 config = configparser.ConfigParser()
3 # print(config.sections())
4 config.read('example.ini')
5 print(config.sections()) #读出来的是文件里面的组,
6 # 而且里面的[DEFAULT]组没有显示出来
7 print('bytebong.com' in config) # False
8 print('bitbucket.org' in config) # True
9 print(config['bitbucket.org']["user"]) # hg
10 print(config['DEFAULT']['Compression']) #yes
11 print(config['topsecret.server.com']['ForwardX11']) #no
12 print(config['bitbucket.org']) #<Section: bitbucket.org>
13 for key in config['bitbucket.org']: # 注意,有default会默认default的键
14 print(key)
15 print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键
16 print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对
17 print(config.get('bitbucket.org','compression')) # yes get方法Section下的key对应的value
3.增删改操作
import configparser
2 config = configparser.ConfigParser()
3 config.read('example.ini')
4 config.add_section('yuan')
5 # config.remove_section('bitbucket.org') #删除组
6 # config.remove_option('topsecret.server.com',"forwardx11") #删除组里面的项
7 config.set('topsecret.server.com','k1','11111')
8 config.set('yuan','k2','22222')
9 config.write(open('new2.ini', "w"))
logging模块
函数式简单配置
默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。

1 只显示大于等于warning基本的日志,这说明默认的日志级别设置为warning
2 (日志级别等级critical>error>warning>info>debug)
3 import logging
4 logging.debug('debug message')
5 logging.info('info message')
6 logging.warning('warning message') #warning 警告(从警告开始才执行)
7 logging.error('error message') #error 错误
8 logging.critical('critical message') #比错误更严重的级别

配置参数
logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:
2
3 filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
4 filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
5 format:指定handler使用的日志显示格式。
6 datefmt:指定日期时间格式。
7 level:设置rootlogger(后边会讲解具体概念)的日志级别
8 stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
9
10 format参数中可能用到的格式化串:
11 %(name)s Logger的名字
12 %(levelno)s 数字形式的日志级别
13 %(levelname)s 文本形式的日志级别
14 %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
15 %(filename)s 调用日志输出函数的模块的文件名
16 %(module)s 调用日志输出函数的模块名
17 %(funcName)s 调用日志输出函数的函数名
18 %(lineno)d 调用日志输出函数的语句所在的代码行
19 %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
20 %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
21 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
22 %(thread)d 线程ID。可能没有
23 %(threadName)s 线程名。可能没有
24 %(process)d 进程ID。可能没有
25 %(message)s用户输出的消息
有两种方式去应用logging模块
1.设置config
import logging
2 logging.basicConfig(
3 level=logging.DEBUG , #多输出一些细节
4 # level = logging.WARNING #就不用输出那些细节了
5 format = '%(name)s %(asctime)s [%(lineno)d] ---%(message)s', #本身就存在在python语法中,拿过来用就行了
6 # level和format也是不能变的,它是参数,不是变量
7 # %(lineno)d指定代码块的行
8 # %(name)s当前管理员的用户
9 datefmt = '%d/%m/%Y %H:%M:%S',#指定日期时间格式
10 filename = 'logging_info' #自动创建了一个文件,并且把日志写到了文件里
11
12 )
13 logging.debug('debug message')
14 logging.info('info message')
15 logging.warning('warning message')
16 logging.error('error message')
17 logging.critical('critical message')
2.logger对象配置
可以控制输入到文件,也可以输入到屏幕
可以同时在几个文件中输出
import logging
2 def mylogger(filename,file=True,stream=True):
3 logger = logging.getLogger()
4 formater = logging.Formatter(
5 fmt='%(name)s %(asctime)s [%(lineno)d] ---%(message)s',
6 datefmt='%d/%m/%Y %H:%M:%S' # 时间格式
7 )
8 logger.setLevel(logging.DEBUG) #指定日志打印的等级
9 if file:
10 file_handler = logging.FileHandler('logging.log',encoding='utf-8')# 创建一个handler,用于写入日志文件
11 file_handler.setFormatter(formater) # 文件流,文件操作符
12 logger.addHandler(file_handler)
13 if stream:
14 stream_handler = logging.StreamHandler() # 再创建一个handler,用于输出到控制台
15 stream_handler.setFormatter(formater) #屏幕流,屏幕操作流
16 #如果想让文件流和屏幕流输出的东西的格式不一样,那么就在写一个 格式formater1,这样就可以了
17 logger.addHandler(stream_handler)
18 return logger
19 logger = mylogger('logging.log',file=False)
20 logger.warning('啦啦啦啦')
21 logger.debug('debug message')
logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。另外,可以通过:logger.setLevel(logging.Debug)设置级别,当然,也可以通过
fh.setLevel(logging.Debug)单对文件流设置某个级别。
python常用模块(3)的更多相关文章
- Python常用模块之sys
Python常用模块之sys sys模块提供了一系列有关Python运行环境的变量和函数. 常见用法 sys.argv 可以用sys.argv获取当前正在执行的命令行参数的参数列表(list). 变量 ...
- Python常用模块中常用内置函数的具体介绍
Python作为计算机语言中常用的语言,它具有十分强大的功能,但是你知道Python常用模块I的内置模块中常用内置函数都包括哪些具体的函数吗?以下的文章就是对Python常用模块I的内置模块的常用内置 ...
- python——常用模块2
python--常用模块2 1 logging模块 1.1 函数式简单配置 import logging logging.debug("debug message") loggin ...
- python——常用模块
python--常用模块 1 什么是模块: 模块就是py文件 2 import time #导入时间模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的 ...
- Python常用模块——目录
Python常用模块学习 Python模块和包 Python常用模块time & datetime &random 模块 Python常用模块os & sys & sh ...
- python 常用模块之random,os,sys 模块
python 常用模块random,os,sys 模块 python全栈开发OS模块,Random模块,sys模块 OS模块 os模块是与操作系统交互的一个接口,常见的函数以及用法见一下代码: #OS ...
- python常用模块之时间模块
python常用模块之时间模块 python全栈开发时间模块 上次的博客link:http://futuretechx.com/python-collections/ 接着上次的继续学习: 时间模块 ...
- python常用模块之subprocess
python常用模块之subprocess python2有个模块commands,执行命令的模块,在python3中已经废弃,使用subprocess模块来替代commands. 介绍一下:comm ...
- python常用模块之string
python常用模块string模块,该模块可以帮我们获取字母.数字.特殊符号. import string #打印所有的小写字母 print(string.ascii_lowercase) #打印所 ...
- python常用模块-调用系统命令模块(subprocess)
python常用模块-调用系统命令模块(subprocess) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. subproces基本上就是为了取代os.system和os.spaw ...
随机推荐
- 攻防世界--re1-100
测试文件:https://adworld.xctf.org.cn/media/task/attachments/dc14f9a05f2846249336a84aecaf18a2.zip 1.准备 获取 ...
- Java编码技巧与代码优化
本文参考整理自https://mp.weixin.qq.com/s/-u6ytFRp-ZAqdLBsMmuDMw 对于在本文中有所疑问的点可以去该文章查看详情 常量&变量 直接赋值常量值, 禁 ...
- MySQL 简介
MySQL 简介 点击查看MySQL官方网站 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB公司开发,后来被Sun公司收购,Sun公司后来又被Oracle公司收购,目前属于Oracle旗 ...
- 02.Linux-CentOS系统Firewalld防火墙配置
1.firewalld的基本使用 启动: systemctl start firewalld关闭: systemctl stop firewalld查看状态: systemctl status fir ...
- CentOS7安装mysql8.0编译报错集合
以下都是我安装mysql8.0遇到的一些报错和解决方法 1.does not appear to contain CMakeLists.txt. 原因:mysql下载的源码包不对 解决方法:下载正确的 ...
- 基于firebird的数据转存
功能:使用于相同的表从一个数据库转存到另一数据库: 方式:直连fdb并加载django,引用django的model完成: 原因:1.select * from *** 返回的数有很多None,直接i ...
- php 调用远程url
// ; Whether to allow the treatment of URLs (like http:// or ftp://) as files. // ; http://php.net/a ...
- 去除重复嵌套的html标签函数
去除重复嵌套的html标签 function strip_multi_tags($str, $tag = 'div'){ preg_match_all('/<'.$tag.'>|<\ ...
- D0g3_Trash_Pwn_Writeup
Trash Pwn 下载文件 1 首先使用checksec查看有什么保护 可以发现,有canary保护(Stack),堆栈不可执行(NX),地址随机化没有开启(PIE) 2 使用IDA打开看看 mai ...
- 对Asycn/Await的研究
1.async 函数就是 Generator 函数的语法糖. 例如: var fs = require('fs'); var readFile = function (fileName){ retur ...