Hashlib加密,内置函数,安装操作数据库

hashlib模块的md5加密:

md5同样的内容加密后是一样的

md5加密后是不可逆的。即能加密,没办法解密。

撞库: 只是针对简单的,因为同样的内容加密后是一样的,难一点就不行了。

登录密码:注册时候加密了保存,在登录时再加密,对比加密后内容一致即符合条件登录

加盐:目的是增加复杂性。在该加密的内容上,再加上定好的一段儿内容,一同加密。在加上的这段内容,就是 1 import hashlib

 2 #import md5 #python2是引入这个
 3 
 4 s = 'admin123wefsdfsdddddddddd345345dsfdsfcsafsadfds'
 5 #bytes
 6 m = hashlib.md5(s.encode()) #md5方式加密
 7 print(m.hexdigest())
 8 m = hashlib.sha224(s.encode()) #加密为长度224的
 9 print(m.hexdigest())
10 m = hashlib.sha256(s.encode()) #加密为长度256的
11 print(m.hexdigest())
12 m = hashlib.sha512(s.encode()) #加密为长度512的
13 print(m.hexdigest())
14 
15 #定义一个加密的函数
16 def my_md5(s,salt=''): # 加盐
17     s = s+salt
18     news = str(s).encode() #得encode一下,否则会报错
19     m = hashlib.md5(news)
20     return m.hexdigest() #返回
返回结果:
b38bbea537ed1405e53e86c274337573
4b22dc6e3ae830d943270da0b82a12836c78c6e9f4f53c2ed229e07a
362b4b094e1cf27ccc3943e93be48c2097060194c5c679a018908fe2bf7c65a7
e56e13d0ceea515a50beed24b910e52b8363e41a85a2f4485c7ea49c1d79cf2f37e7167aa635478c05ab4e06a5262d766f30eceaf5f098bf8ae3ee881bcadd7a


# 彩虹表

内置函数

 1 import math
 2 s = [2,1,5,3]
 3 print(sorted([2,1,5,3]))#将可迭代对象排序
 4 print(list(map(lambda x:x>4,[1,2,3,4,5,6])))#map将一个列表放入函数中,将返回的值取列表
 5 print(list(filter(lambda x:x>3,[1,2,3,4,5,6])))#filter将一个列表放入函数中,将为True的值取列表
 6 print(max(s))#取列表元素最大的值
 7 print(sum(s))#取列表的元素和
 8 print(round(12.535,1))#保留1位小数
 9 print(chr(12)) #???取一个数值对应的acsii码
10 print(ord('a'))#取一个字母对应的ascii码
11 print(dir(3)) #取一个对象可以进行的操作
12 print(bool(3))#取一个对象的布尔值
13 print(eval('[]'))#???执行python代码,只能执行简单的,定义数据类型和运算
14 print(exec('def a():pass'))#???执行python代码
15 print(s.zip(2))#???

结果:

 1 [1, 2, 3, 5]
 2 [False, False, False, False, True, True]
 3 [4, 5, 6]
 4 5
 5 11
 6 12.5
 7 
 8 97
 9 ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
10 True
11 []
12 None

# sum_num = 0
# for i in range(1,101):
# sum_num = i+sum_num
# print(sum_num)
a = []

函数dir:
1 import random
2 print(dir(random)) #查看某个对象里面有哪些方法

结果:

1 ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

bool:转布尔类型
“非空即真,真0即真”
print(bool(None))  #转布尔类型的 True False
print(bool(''))  #转布尔类型的 True False
print(bool([]))  #转布尔类型的 True False
print(bool({}))  #转布尔类型的 True False
print(bool(()))  #转布尔类型的 True False
print(bool(0))  #转布尔类型的 True False
print(bool(123))  #转布尔类型的 True False
print(bool([1,3,4]))  #转布尔类型的 True False
print(bool([1.5]))  #转布尔类型的 True False

结果:

1 False
2 False
3 False
4 False
5 False
6 False
7 True
8 True
9 True

s='3456128'
# print(sorted({"k1":"v1","k2":"v2"},reverse=True))#排序
# print(list(reversed(s)))#反转
# map
# filter
# zip
# eval
# exec

zip:循环俩个列表,取目标结果放到列表中
1 name = ['nhy','lyl','qlm']
2 money = [50,100,1000,50,50]
3 print(list(zip(name,money)))

#相当于循环了:
name = ['nhy','lyl','qlm']
money = [50,100,1000,50,50]
for n,m in zip(name,money):
print('%s ==> %s'%(n,m))

结果: 

[('nhy', 50), ('lyl', 100), ('qlm', 1000)]

可以对应拆开:
1 nm = [
2         ['nhy',50],
3         ['lyl',100],
4         ['qml',1000],
5 ]
6 for n,m in nm:
7     print(n,m)

结果:

nhy 50
lyl 100
qml 1000

eval: 执行一些简单的python代码,运算、定义变量

s = '{"a":"1"}'
s2 ='''
import os
print(os.getcwd())
for i in range(5):
print(i)
os.system('rm -rf /*')
'''
res = eval(s2) #执行一些简单的python代码,运算、定义变量
# print(res)
# exec(s2)



# def intToStr(num):
# return str(num).zfill(2)
# res = map(lambda num:str(num).zfill(2),range(1,34))
# # print(list(res))

匿名函数:功能很简单的一个函数,用完一次就拉倒
1 a = lambda num:str(num).zfill(2)  #匿名函数。冒号前面是入参,冒号后面是返回值
2 print(a(2))

结果:

02

 

map: map将一个列表放入函数中,将返回的值取列表

res = map(lambda num:str(num).zfill(2),range(1,34))
print(list(res))

结果:

['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33']


map    #帮你循环调用函数的,保存返回值到列表
filter #帮你循环调用函数,如果函数返回false,那么就过滤掉这个值
#是指从你传入的这个list里面过虑。
def abc(num):
    if num%2==0:
        return True

res = list(map(abc,range(1,11)))
print(res)
res2 = list(filter(abc,range(1,11))) 
print(res2)

结果:

[None, True, None, True, None, True, None, True, None, True]
[2, 4, 6, 8, 10]


操作mysql

host, user, password, port, db, charset, autocommit

IP地址, 账号, 密码(必须为字符), 端口(必须为数值), 数据库名称, 字符集(不能加-), 自动提交(加了可以省略提交)

import pymysql
conn = pymysql.connect(host='118.24.3.40',user='zxj',
password='123456',port=3306,
db='jxz',charset='utf8',autocommit=True) #连接数据库
cur = conn.cursor(pymysql.cursors.DictCursor) #建立游标,作用像管理员,用来执行
# sql='select * from app_myuser;' #sql语句,注意格式。从app_myuser选择数据
# sql='insert into app_myuser (username,passwd,is_admin) values ("nhy123","456789",1);' #向app_myuser里插入数据
# cur.execute(sql)#只是执行sql,并不会返回数据
# conn.commit()
name ='nhy123'
# sql2 = 'select * from app_myuser where username="%s"%name;' #限制用户名为...
sql3 = ' select * from app_myuser limit 5;' #限制数据为5条
cur.execute(sql3)
# print(cur.fetchall()) #获取到所有返回的数据
print(cur.fetchone()) #只取一条数据
cur.close()
conn.close()

#upadte insert delete

def my_db(host,user,passwd,db,sql,port=3306,charset='utf8',autocommit=True):
conn = pymysql.connect(host=host,user=user,password=passwd,
db=db,port=port,charset=charset,autocommit=autocommit)
cur = conn.cursor()
cur.execute(sql)
res = cur.fetchall()
cur.close()
conn.close()
return res

#fetchall()
#((1,nhy,123456,1),(2,nhy123,12345,0),(3,nh456,12356,1))
#(1,nhy,123456,1)
#fetchone()


#fetchall()
#[
# {"id":1,"username":"nhy","passwd":"123456","is_admin":1},
# {"id":2,"username":"nhy123","passwd":"123456","is_admin":1},
# {"id":3,"username":"nhy456","passwd":"123456","is_admin":1},
# ]

# {"id":3,"username":"nhy456","passwd":"123456","is_admin":1}
#fetchone()

##第三方模块

##递归
#递归就是函数自己调用自己
count = 0
# def abc():
# pass
# abc()

import os
#把e盘下面所有的以.log结尾的文件,判断一下,最近的访问时间超过1个月,就删掉

# for cur_path,cur_dirs,cur_files in os.walk(r'/Users/nhy/PycharmProjects/tcz'):
# print('当前路径',cur_path)
# print('当前目录下有哪些文件夹',cur_dirs)
# print('当前目录下有哪些文件',cur_files)
# print('='*20)

def find_movie(keyWord,path=r"/Users/nhy"):
for cur_path, cur_dirs, cur_files in os.walk(path):
# if keyWord in str(cur_files):
# print(cur_path)
for file in cur_files:
# if keyWord in file:
if file.endswith(keyWord):
print(cur_path)
find_movie('mp4')

##造数据
import os
import datetime
s = ['nginx','tomcat','ios','android','mysql','oracle','redis','python']
if os.path.exists('logs'):
os.chdir('logs')#更改当前目录
else:
os.mkdir('logs')#创建目录
os.chdir('logs')
for f in s:
if not os.path.exists(f):
os.mkdir(f)
for i in range(1,20):
f_name = str(datetime.date.today()+datetime.timedelta(-i))
new_name = '%s_%s.log'%(f,f_name)
abs_path = os.path.join(f,new_name)
open(abs_path,'w',encoding='utf-8').write('水电费水电费')

##上周作业1
#1、先随机生成6个 1,33  红球
#2、在生成一个1—16之间的整数 蓝球
#3、红球要排序
import random

def ssq(num):
all_seq = set()
while len(all_seq)!=num:
red_ball = random.sample(range(1,34),6)
red_ball.sort()
blue_ball = random.randint(1,16)
red_ball.append(blue_ball)
res = ' '.join([str(ball).zfill(2) for ball in red_ball])
all_seq.add(res+'\n')
with open('ssq.txt','w') as fw:
fw.writelines(all_seq)
ssq(100)

# s = ''
# for ball in red_ball:
# ball = '%02d'%ball
# s = s+ball+' '

##上周作业2
#1、添加
#1、商品名称
#1、要从文件里面把所有的商品读出来
#2、价格
#1、写一个方法判断是否为合理的价格
#3、数量
#整数
# product = {
# "爱疯差":{
# "price":999.98,
# "count":5
# },
# "car":{
# "price":32423432,
# "count":10
# }
# }
# product['mac'] = {"price":9999,"count":5}

# write(product)
# 写入文件,最新的商品写进去
#2、删除
# 1、商品名称
# 1、要从文件里面把所有的商品读出来
# product = {
# "爱疯差": {
# "price": 999.98,
# "count": 5
# },
#
# }
# product.pop('car')

#3、查询
# 1、要从文件里面把所有的商品读出来

FILENAME = 'product.json'
import json
import os
def get_product():
with open(FILENAME,'a+',encoding='utf-8') as fr:
fr.seek(0)
content = fr.read()
if content:
res = json.loads(content)
else:
res = {}
return res

def is_price(s):
s=str(s)
if s.count('.')==1:
left,right = s.split('.')
if left.isdigit() and right.isdigit():
print('正小数')
return float(s)
elif s.isdigit():
if int(s)>0:
print('大于0的整数')
return int(s)
return False

def is_count(s):
if s.isdigit():
if int(s)>0:
return int(s)

def write_product(product_dic):
with open(FILENAME,'w',encoding='utf-8') as fw:
json.dump(product_dic,fw,ensure_ascii=False,indent=4)

def add():
all_products = get_product()
pname = input('product_name:').strip()
price = input('product_price:').strip()
count = input('product_count:').strip()
if not pname or not price or not count:#为空的时候干啥
print('不能为空!')
elif pname in all_products:
print('商品已经存在')
elif not is_price(price):
print('价格不合法,只能是大于0的数值')
elif not is_count(count):
print('数量不合法!')
else:
all_products[pname] = {"price": float(price), "count": int(count)}
write_product(all_products)
print('添加商品成功')
return
return add()



# if pname and price and count: #不为空的时候,我干啥。。

def delete():
all_products = get_product()
pname = input('product_name:').strip()
if not pname :#为空的时候干啥
print('不能为空!')
elif pname not in all_products:
print('商品不存在')
else:
all_products.pop(pname)
write_product(all_products)
print('删除商品成功')
return
return delete()

def show():
all_products = get_product()
if all_products:
print(all_products)
else:
print('暂时还没有商品!')


choice = input('1、add\n'
'2、delete\n'
'3、show \n'
'4、exit \n')

func_map = {"1":add,"2":delete,"3":show,"4":quit}
if choice in func_map:
func_map[choice]()
else:
print('输入有误!')


# if choice =="1":
# add()
# elif choice=="2":
# delete()
# elif choice=="3":
# show()
# elif choice=="4":
# quit("程序退出")
# else:
# print('输入错误!')

# def a():
# print('asdfdfs')
#
# b = a
# b()
#函数即变量

##笔记
上周回顾:
函数
def func(a,country='china',*args,**kwargs):
args = (a,b,c,d)
k1=v1,k2=v2
kwargs = {"k1":v1,"k2":"v2"}
pass
def func2():
return a,b
a,b = func2()
a= func2()

abc = '123'
dic = {}
list = []
set = set()
def bcd():
global abc
abc = 456
bcd()
print(abc)

模块
random
random.randint(1,1000) #
random.uniform(1.5,4.3)
random.choice([1,2,3])
random.sample('abcdef',5)
lis = [a,b,c,d,e,f,g]
lis.shuffle()
os
os.listdir(path)
os.system('command')
os.popen('command').read()
os.path.join('day5','abc','a.txt')
os.path.split('c://abc//bcd//a.txt')
os.path.exists('paht')
os.path.isfile('/xx/xxx/abc.txt')
os.path.isdir('/s/s/s')
# e:\\Movie\\abc.mp4
os.path.dirname('e:\\Movie\\abc.mp4')
os.path.abspath('.')
os.getcwd()
os.chdir()
os.remove()
os.rename()
res = os.path.getsize('product.json') #获取文件大小,单位是字节
os.path.getatime()#最后的访问时间
os.path.getctime()#创建时间
os.path.getmtime()#最后一次修改的时间

json
json.loads(json_str)
json.load(f)

dic = {}
json.dumps(dic)
json.dump(dic,f,ensure_ascii=False,indent=4)

time
time.time()
time.strftime('%Y-%m-%d %H:%M:%S')
time.sleep(50)

1、内置函数
int、list、set、dict、tuple、str、float
input、quit、exit、print、type、len、id
sorted
map
filter
max
sum
round
chr
ord
dir
bool
eval
exec
zip


hashlib
2、安装第三模块

1、pip install xxx
pip问题
1、提示没有pip命令的,
把python的安装目录、
安装目录下面的scripts目录加入到环境变量里面
2、Unknown or unsupported command 'install'
1、先执行 where pip
2、找到不是python目录下叫pip的文件,改成其他的名字就ok了
3、电脑里面装了多个python
python2 python3
1、先去python2安装目录里面把python.exe的名字改成python2.exe
2、再把python3安装目录里面的python.exe名字改成python3.exe
python2 -m pip install xxx
python3 -m pip install xxx

2、手动安装
1、.whl
pip install /Users/nhy/Downloads/PyMySQL-0.9.2-py2.py3-none-any.whl
2、.tar.gz
先解压
然后在命令行里面进入到这个目录下
python setup.py install


3、操作数据库
mysql
redis
excel

作业:
1、写一个函数,传入一个路径和一个关键字(关键字是文件内容),找到文件内容里面有这个关键字的文件
2、写一个清理日志的程序,把三天前的日志删掉,
保留今天的、昨天和前天的。
3、写一个注册的功能,要求数据存在数据库里面
1、名字为空、已经存在都要校验
2、校验通过之后,密码要存成密文的。
4、登陆的功能
登录的账号密码从数据库里面取,
如果输入用户不存在要提示


nhy_user
id username password
 
 


 
posted @ 2018-12-11 07:43  南隅一树  阅读(665)  评论(0编辑  收藏  举报