码迷,mamicode.com
首页 > Web开发 > 详细

json&pickle模块、configparse/hashlib/subprocess 模块

时间:2020-04-01 01:21:33      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:setting   update   json格式   特定   密文   不同   字符串   width   模拟   

一、json 与pickle模块

序列化:

1、什么是序列化&反序列化

内存中的数据类型---->序列化---->特定的格式(json格式或者pickle格式)
内存中的数据类型<----反序列化<----特定的格式(json格式或者pickle格式)

2、为何要序列化

序列化得到结果=>特定的格式的内容有两种用途

1、可用于存储=》用于存档

2、传输给其他平台使用=》跨平台数据交互

?

强调:
针对用途1的特定一格式:可是一种专用的格式=》pickle只有python可以识别
针对用途2的特定一格式:应该是一种通用、能够被所有语言识别的格式=》json

3、如何序列化与反序列化

示范1

import json
# 序列化
import json
json_res=json.dumps([2,‘bbb‘,False,True])
print(json_res,type(json_res))  #[2, "bbb", false, true] <class ‘str‘>

# 反序列化
l=json.loads(json_res)
print(l,type(l))  #[2, ‘bbb‘, False, True] <class ‘list‘>

示范2:

序列化的结果写入文件的复杂方法

with open(‘test.json‘,mode=‘wt‘,encoding=‘utf-8‘) as f:
    f.write(json_res)

将序列化的结果写入文件的简单方法

with open(‘test.json‘,mode=‘wt‘,encoding=‘utf-8‘) as f:
    json.dump([2,‘bbb‘,False,True],f)

从文件读取json格式的字符串进行反序列化操作的复杂方法

with open(‘test.json‘,mode=‘rt‘,encoding=‘utf-8‘) as f:
    json_res=f.read()
    l=json.loads(json_res)

从文件读取json格式的字符串进行反序列化操作的简单方法

with open(‘test.json‘,mode=‘rt‘,encoding=‘utf-8‘) as f:
    l=json.load(f)

json 兼容性:

json验证: json格式兼容的是所有语言通用的数据类型,不能识别某一语言的所独有的类型

集合是python独有的数据类型

json.dumps({1,2,3,4,5})  #报错:Object of type set is not JSON serializable    

json强调:一定要搞清楚json格式,不要与python混淆

l=json.loads(‘[1, "aaa", true, false]‘)  #属于json 的数据格式可以序列化
l=json.loads("[1,1.3,true,‘aaa‘, true, false]")  #不属于josn的数据格式,报错

可以将json类型的字节反序列化

l=json.loads(b‘[1, "aaa", true, false]‘)
print(l,type(l))  #[1, ‘aaa‘, True, False] <class ‘list‘>
res=json.dumps({‘name‘:‘哈哈哈‘})
print(res,type(res))  #{"name": "\u54c8\u54c8\u54c8"} <class ‘str‘>

4、猴子补丁

在入口处打猴子补丁
import json
import ujson

def monkey_patch_json():
    json.__name__ = ‘ujson‘
    json.dumps = ujson.dumps
    json.loads = ujson.loads
# monkey_patch_json() # 在入口文件出运行
import ujson as json  # 不能直接导入ujson该别名成json

5、pickle模块

pickle模块的基本用法和json相同,只能用于python序列化和反序列化

import pickle
res=pickle.dumps({1,2,3,4,5})
print(res,type(res))

s=pickle.loads(res)
print(s,type(s))

Pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于Python,并且可能不同版本的Python彼此都不兼容,因此,只能用Pickle保存那些不重要的数据,不能成功地反序列化也没关系。

def register():
    import json
    dic = {}
    name = input(‘输入账号: ‘).strip()
    pwd = input(‘输入密码: ‘).strip()
    pwd1 = input(‘确认密码: ‘).strip()
    if pwd1 == pwd:
        dic[name] = pwd
        with open(‘test.json‘, mode=‘at‘, encoding=‘utf-8‘)as f:
            json.dump(dic, f)


register()

二、configparser模块

import configparser

config = configparser.ConfigParser()
config[‘interface‘] = {}
config[‘interface‘][‘length‘] = ‘200‘
config[‘interface‘][‘width‘] = ‘100‘
config[‘file_path‘] = {}
config[‘file_path‘][‘src_file‘] = ‘a.txt‘
config[‘file_path‘][‘dst_file‘] = ‘b.txt‘
with open(‘setting.ini‘, ‘w‘) as configfile:

config=configparser.ConfigParser()
config.read(‘setting.ini‘)
#查看所有的标题
res=config.sections()
print(res)  #[‘interface‘, ‘file_path‘]

#查看标题interface下所有key=value的key
options=config.options(‘interface‘)
print(options)  #[‘length‘, ‘width‘]

#查看标题interface下user的值=>字符串格式
val=config.get(‘interface‘,‘length‘)
print(val)  #200

#查看标题interface下length的值=>整数格式
val1 = config.getint(‘interface‘, ‘length‘)
print(val1, type(val1))  #200 <class ‘int‘>

#config.getboolean()   config.getfloat()





# 删除整个标题interface
config.remove_section(‘interface‘)

#判断标题file_path下是否有dst_file
print(config.has_option(‘file_path‘,‘dst_file‘))

#添加一个标题
config.add_section(‘typeface‘)

#在标题typeface下添加name=‘18‘的配置
config.set(‘typeface‘,‘size‘,‘18‘)

#最后将修改的内容写入文件,完成最终的修改
config.write(open(‘setting.ini‘,‘w‘))
‘‘‘
[interface]
length = 200
width = 100

[file_path]
src_file = a.txt
dst_file = b.txt

[typeface]
size = 18
‘‘‘

三、hashlib模块

1、什么是哈希hash

hash是一类算法,该算法接受传入的内容,经过运算得到一串hash值

特点:

1 只要传入的内容一样,得到的hash值必然一样

2 不能由hash值返解成内容

3 不管传入的内容有多大,只要使用的hash算法不变,得到的hash值长度是一定

2、hash的用途

1 特点2用于密码密文传输与验证

2 特点1、3用于文件完整性校验

3、如何用

import hashlib

m = hashlib.md5()
m.update(‘you‘.encode(‘utf-8‘))
m.update(‘are‘.encode(‘utf-8‘))
m.update(‘beautiful‘.encode(‘utf-8‘))
res = m.hexdigest()
print(res)  # 1cca676950dfbab0c08b0f9b2fc5ed4c

不管怎么传只有内容一样,算法一样,hash值就一样

m.update(‘yo‘.encode(‘utf-8‘))
m.update(‘uarebeauti‘.encode(‘utf-8‘))
m.update(‘ful‘.encode(‘utf-8‘))
res=m.hexdigest()
print(res)  #1cca676950dfbab0c08b0f9b2fc5ed4c

模拟撞库得到密码

password = [‘abcd123‘,
            ‘abcd321‘,
            ‘abcd231‘]

cryptogragh = ‘72113b401a454ea7ebac1f2051b9d05f‘ #‘abcd321‘
dic = {}

for p in password:
    res = hashlib.md5(p.encode(‘utf-8‘))
    dic[p] = res.hexdigest()

dic = {}
for p in password:
    res = hashlib.md5(p.encode(‘utf-8‘))
    dic[p] = res.hexdigest()
    
for k, v in dic.items():
    if v == cryptogragh:
        print(f‘撞库成功,明文密码是{k}发财了!‘)  #撞库成功,明文密码是abcd321发财了!
        break

提升撞库的成本=>密码加盐

import hashlib

m=hashlib.md5()

m.update(‘小鸡‘.encode(‘utf-8‘))
m.update(‘abcd321‘.encode(‘utf-8‘))
m.update(‘炖蘑菇‘.encode(‘utf-8‘))
print(m.hexdigest())

四、 subprocess 模块

import subprocess

obj=subprocess.Popen(‘echo 123 ; ls / ; eccc123‘,shell=True,
                 stdout=subprocess.PIPE,  #正确命名的管道
                 stderr=subprocess.PIPE,  #错误命名的管道
                 )

print(obj)
res=obj.stdout.read()
print(res.decode(‘utf-8‘))

err_res=obj.stderr.read()
print(err_res.decode(‘utf-8‘))

json&pickle模块、configparse/hashlib/subprocess 模块

标签:setting   update   json格式   特定   密文   不同   字符串   width   模拟   

原文地址:https://www.cnblogs.com/zhangtieshan/p/12609772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!