day25模塊 hashlib configparser logging
今日內容
json 補充
3.1 hashlib 加密,摘要算法
3.2 configparser 配置文件
3.3 logging 模塊
json字符串和python 字符串到底差在什麽地方?
json字符串在數據最外面始終是單引號引起來的.
json字符串如果數據是容器類的數據類型,且裏面有字符串,字符串一定是雙引號引起來的.
而python "{‘alex‘:‘wusir‘}" 不區分單雙引號.
對於單獨的字符串:
python顯示: "alex" 不區分單雙引號
json顯示: ‘ "alex" ‘ 外面還有一個單引號
3.1 hashlib:hash:算法,結果是內存地址.
hashlib 模塊與加密相關,實際上他是摘要算法.
1. hashlib 是一堆算法的合集,它包含很多算法(加密的).
2.hashlib 的過程就是將字符串轉化成 一串由數字和字母組合的字符串的過程.(經過hashlib轉化的結果是等長的)
3.hashlib對相同的字符串轉化成的()數字加字母)是相同的
4. 不同的電腦對相同的字符串進行加密,轉化成的數字相同.
hashlib 用在哪裏?
1.密文(密碼):將密碼用算法加密放置到數據庫.每次取出驗證.
2. 文件的校驗
初識 hashlib
import hashlib
#md5 加密算法, 常用算法,可以滿足一般的常用需求.
#sha 1(有好幾個等級) : 加密算法,級別高一些,數字越大級別越高,加密的效率越低,越安全.
#md5
s = "123456"
ret = hashlib.md5() #創建一個md5對象
ret.update(s.encode("utf-8")) #調用次update方法對參數進行加密bytes類型
print(ret.hexdigest()) #得到加密後的結果 定長
s2 = "dflajfldajkldjfljsejfl;jef;laeja;j;lajld"
ret = hashlib.md5() #創建一個md5對象
ret.update(s2.encode("utf-8")) #調用次update方法對參數進行加密bytes類型
print(ret.hexdigest()) #得到加密後的結果 定長
s3 = "dflajfldajkldjfljsejfl;jef;laeja;j;lajle"
ret = hashlib.md5() #創建一個md5對象
ret.update(s3.encode("utf-8")) #調用次update方法對參數進行加密 bytes類型
print(ret.hexdigest()) #得到加密後的結果 定長
s2 和s3就只有一個字母不一樣,得到加密後的結果也是大不一樣.
無論字符串多長,返回都是定長的(數字和字符串)
同一字符串,md5值相同.
黑客:將你常用的密碼 000000 111111 等.對應的md5關系表給打印出來,因此就會有可能破解密碼.
撞庫:因為撞庫,所以相對不安全,如何解決?
import hashlib
s = "123456"
ret = hashlib.md5()
ret.update(s.encode("utf-8")
print(ret.hexdigest())
解決方式:加鹽
s1 = "123456"
ret = hashlib.md5("&&%%$".encode("utf-8")) #創建一個md5對象,加鹽
ret.update(s1.encode("utf-8")) #調用此update方法對參數進行加密bytes類型
print(ret.hexdigest()) #得到加密後的結果 定長
如果黑客盜取到固定的鹽,"&&%%$"內容,還是會破解密碼
變成隨機的鹽:
import hashlib
username= "ajdklfja"
password = "123456"
ret = hashlip.md5(username[::-2].encode("utf-8"))
ret.update(password.encode("utf-8"))
print(ret.hexdigest())
sha 系列
hashlib.sha1() #sha1與md5級別相同,但是sha1比md5更安全一些,因為sha1用得少.
import hashlib
ret = hashlib.sha1()
ret.update("122345".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 f: #用rb模式,文件裏的內容就不需要再編譯成bytes類型了.
ret = hashlib.md5()
ret.update(f.read()) #因為文件使用rb模式打開的所以這裏不用編譯成bytes類型
return ret.hexdigest()
print(func("hashlib_file"))
print(func("hashlib_file"))
上面的代碼對於小文件可以(f.read()是一次性讀取文件)但是超大的文件,內存就受不了.
import hashlib
s = "我愛你中國,我是地球人.也是亞洲人,更是中國人"
ret = hashlib.md5()
ret.update(s.encode("utf-8"))
print(ret.hexdigest())
get = hashlib.md5()
get.update(s[0:10].encode("utf-8"))
get.update(s[10:].encode("utf-8"))
print(get.hexdigest())
兩次打印的結果是一樣的
def func(file_name):
with open(file_name,mode="rb")as f:
ret = hashlib.md5
#for i in f: #這個方法跟下面的方法得到的結果一樣.
# ret.update(i)
#return ret.hexdigest()
while True:
content = f1.read(1024)
if content:
ret.update(content)
else:
break
return ret.hexdigest()
print(func("hashlib_file"))
print(func("hashlib_file"))
hashlib :用在密文(密碼),或者文件的校驗.
md5:普通的, 加鹽的 , 動態加鹽的
sha系列: 普通的 , 加鹽的, 動態加鹽的
文件的校驗:小文件,大文件.
3.2 configparser (配置文件)(了解):放置一些常用的變量(以 .ini 結尾)
configparser 幫助操作(創建,增加,刪,改,查)一個配置文件.
創建一個文件:
import configparser
config = configparser.ConfigParser()
config[‘DEFAULT‘] = {"ServerAliveInerval":"45",
‘Compression‘:"yes",
‘ComperssionLevel‘:"9",
‘ForwardXl1‘:‘yes‘
}
config[‘bitbucket.org‘] = {"user":"hg"}
config[‘topsecret.server.com‘] = {‘Host Port‘ : ‘45345‘,‘ForwardXl1‘ : ‘no‘}
with open("example.ini","w")as f:
config.write(f)
以上操作便是創建一個example.ini的配置文件
import configparser
config = configparser.ConfigParser()
查找內容,基於字典的形式.
print(config.sections()) #打印出 [] 空列表.
config.read("example.ini")#順序:創建一個對象,然後將文件讀到內存中,再進行相應的操作.
print(config.sections())#就會打印出文件的sections
#打印的結果為什麽沒有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"]["ForwardXl1"])#no
print(config["bitubcket.org"])#輸出的是一個可叠代器
print(config["bitbucket.org"]["forwardxl1"])#yes
for key in config[‘bitbucket.org‘]#註意有default會默認default的鍵,意思就是default也能打印出來
print(key)
print(config.options(‘bitbucket.org‘))#同for循環,找到"bitbucket.org"下所有的鍵
print(config.items("bitbucket.org"))#找到"bitbucket.org"下所有的鍵值對,包括DEFAULT下的
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‘‘,"forwardxl1")
config.set("topsecret.server.com","k1","1111")
config.set("yuan","k2","22222")
config.write(open("new2.ini","w")
log 日誌:
什麽時候用到日誌?
生活中:
1.公司員工信息工號等等需要日誌.
2.淘寶,京東 你的消費信息,瀏覽記錄等等都記錄日誌中,個性化推薦.
3.頭條個性化設置(愛好記錄的日誌中)
等等
工作上:
運維人員,任何員工對服務器做過的任何操作,都會記錄到日誌中.如果你要是從事運維開發的工作,各處都需要日誌.
debug模式,需要依靠日誌的,
定時收集信息,也要記錄日誌.
logging 模塊是輔助你記錄日誌的,不是自動記錄日誌的.
低配版,logging
高配版,logger 對象
低配版,logging
import logging
等級是一層一層升高的.
logging.basicConfig(level=logging.DEBUG)
level = logging.DEBUG設置顯示報錯的級別
logging.debug("debug message") #調試信息
logging.info("info message")#正常信息
logging.warning("warning message")#警告信息:代碼雖然不報錯,但是警告寫的不規範,必須改
logging.error("error message")#錯誤信息
logging.critical("critical message")#嚴重錯誤信息
用法實例:
try:
num = input("<<<<")
num = int(num)
except ValueError:
logging.error("出現了%s"%ValueError)
1.調整格式.(完善報錯信息)
logging.basicConfig(level = logging.DEBUG,
format = "%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s",
)
logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
logging.critical("critical message")
logging.basicConfig(level= logging.DEBUG,
format = "%(astime)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 message")
logging.error("error message")
logging.critical("critical message")
try:
num = input("<<<<")
num = int(num)
except Exception as e:
logging.warning(e)
logging.error(e)
logging.critical(e)
低配版 logging 缺點:
1.寫入文件打印日誌不能同時進行
2.寫入文件時文件編碼方式為gbk
day25模塊 hashlib configparser logging