23 day of python

hash:算法,结果是什么?是内存地址,

print(hash('123'))
dic = {'name':'alex'}
print(hash('name'))
print(id('name'))

hashlib  模块  与加密相关,被称作 摘要算法。

1,是一堆算法的合集,他包含很多算法(加密的)。

2,hashlib的过程就是将字符串转化成---->数字的过程。

3,hashlib对相同的字符串转化成的数字相同。

4,不同的电脑,对相同的字符串进行加密转化成的数字相同。

用在哪里?

密文(密码)。

  # 将密码用算法加密放置到数据库,每次取出验证。

文件的校验。

初始 hashlib

import hashlib

md5 加密算法    常用算法,可以满足一般的常用的需求

sha  加密算法 级别高一些,数字越大级别越高,加密的效率越低,越安全。

s1 = '12354455'
ret = hashlib.md5()      # 创建一个md5对象
ret.update(s1.encode('utf-8'))      # 调用此update方法对参数进行加密    bytes类型
print(ret.hexdigest())          # 得到加密后的结果  定长
md5

无论字符串多长,返回都是定长的数字,

同一字符串,md5值相同。

 

000000 c108971251713ee7c59db5c097378018

123456 e10adc3949ba59abbe56e057f20f883e

撞库:因为撞库,所以相对不安全,如何解决?

s4 = '123456'
ret = hashlib.md5()        # 创建一个md5对象
ret.update(s4.encode('utf-8'))
print(ret.hexdigest())

 

解决方式:加盐。

s3 = '123456'
ret = hashlib.md5('dasdascascasw'.encode('utf-8'))      # 创建一个md5对象,加盐
ret.update(s3.encode('utf-8'))          # 调用此update方法对参数进行加密  bytes类型
print(ret.hexdigest())          # 得到加密后的结果  定长

如果黑客盗取你的固态盐'dasdascascasw'内容

变成随机的盐:

username = '爽妹'
password = '123456'
ret = hashlib.md5(username[::2].encode('utf-8'))
ret.update(password.encode('utf-8'))
print(ret.hexdigest())

sha 系列

hashlib.sha1()      # sha1与md5级别相同,但是sha1比md5更安全一些,
ret = hashlib.sha1()
ret.update('123456'.encode('utf-8'))
print(ret.hexdigest())

 ret = hashlib.sha512() #级别最高,效率低,安全性最大
 ret.update('123456'.encode('utf-8'))
 print(ret.hexdigest())

文件的校验

对于小文件可以,但是超大的文件内存受不了,(下面具体代码解决)

def func(file_name):
    with open(file_name,mode='rb')as f1:
        ret = hashlib.md5()
        ret.update(f1.read())
        return ret.hexdigest()
print(func('hashlib_file'))
print(func('hashlib_file1'))
s1 = 'I am 旭哥,都别惹我... 不服你试试'
ret = hashlib.md5()
ret.update(s1.encode('utf-8'))
print(ret.hexdigest())
def func(file_name):
    with open(file_name,mode='rb') as f1:
        ret = hashlib.md5()
        while True:
            content = f1.read(1024)
            if content:
                ret.update(content)
            else:
                break
        return ret.hexdigest()
print(func('hashlib_file'))
print(func('hashlib_file1'))

 

hashlib

用在密文,或者文件的校验。

md5

  普通的

  加盐的

  动态加盐的

sha

  普通的

  加盐的

  动态假烟的

文件的校验:

  小文件

  大文件

帮助你操作(创建,增,删,改,查)一个配置文件

创建一个文件。

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']
# #为什么没有 DEFAULT,它是特殊的,可以看做成一个全局的.
print('111' 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> 可迭代对象
print(config['bitbucket.org']['forwardx11'])          #<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('new2.ini')
# config.add_section('日天')
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"))

 

 

log 日志:
什么时候用到日志?
生活中:
1, 公司员工信息工号等等需要日志.
2, 淘宝,京东 你的消费信息,浏览记录等等都记录日志中,个性化推荐.
3, 头条个性化设置(爱好记录的日志中).

工作上:
运维人员,任何员工对服务器做过的任何操作,都会记录到日志中.
如果你要是从事运维开发的工作,各处都需要日志.
debug模式,需要依靠日志的.
定时收集信息,也要记录日志.

logging 模块是辅助你记录日志的,不是自动记录日志的.
低配版,logging
高配版,logger 对象

低配版,logging
import logging
等级是一层一层升高的.

import logging
logging.basicConfig(level=logging.ERROR)
# level = logging.DEBUG
logging.debug('debug message')      # 调试信息
logging.info('info message')        # 正常信息
logging.warning('warning message')      # 警告信息:代码虽然不报错,但是警告你写的不规范,必须改.
logging.error('error message')      # 错误信息.
logging.critical('critical message')    # 严重错误信息.

用法实例:

import logging
try:
    num = input('>>>请输入')
    num = int(num)
except ValueError:
    logging.error('出现了%s'% ValueError)

1,调整格式。(完善报错信息)

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s',
                    )
level = logging.DEBUG   # 设置显示报错的级别。
logging.debug('debug message')   # 调试信息
logging.info('info message')    # 正常信息
logging.warning('warning message')  # 警告信息:代码虽然不报错,但是警告你写的不规范,必须改.
logging.error('error message')  # 错误信息.
logging.critical('critical message') # 严重错误信息.
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='low_logging.log',
                    # filemode='w'
                    )
logging.warning('warning 警告错误!!!!')     # 警告信息:代码虽然不报错,但是警告你写的不规范,必须改。
logging.error('error message')      # 错误信息。
logging.critical('critical message')    # 严重错误信息。
# level = logging.DEBUG 设置显示报错的级别。
try:
    num = input('>>>请输入')
    num = int(num)
except Exception as e:
    logging.warning(e)  # 警告信息:代码虽然不报错,但是警告你写的不规范,必须改。
    logging.error(e)   # 错误信息。
    logging.critical(e)     # 严重错误信息。

low logging 缺点:
1,写入文件 打印日志不能同时进行.
2 ,写入文件时文件编码方式为gbk..

posted @ 2018-07-09 21:28  贾迪123  阅读(57)  评论(0编辑  收藏  举报