1、前言
臨時文件通常用來保存無法保存在內存中的數據,或者傳遞給必須從文件讀取的外部程序。一般我們會在/tmp目錄下生成唯一的文件名,但是安全的創建臨時文件并不是那么簡單,需要遵守許多規則。永遠不要自己去嘗試做這件事,而是要借助庫函數實現。而且也要小心清理臨時文件。
臨時文件引起的最大問題就是,可以預測文件名,導致惡意用戶可以預測臨時文件名,從而創建軟鏈接劫持臨時文件。
相關免費學習推薦:python視頻教程
2、tempfile模塊介紹
創建臨時文件一般使用的模塊就是tempfile,此模塊庫函數常用的有以下幾個:
- tempfile.mktemp # 不安全,禁止使用
- tempfile.mkstemp # 隨機創建tmp文件,默認創建的文件在/tmp目錄,當然也可以指定(可以使用)
- tempfile.TemporaryFile # 內存中創建文件,文件不會存儲在磁盤,關閉后即刪除(可以使用)
- tempfile.NamedTemporaryFile(delete=True) 當delete=True時,作用跟上面一樣,當是False時,會存儲在磁盤(可以使用)
3、示例介紹
以下幾種方式分別介紹了安全的創建臨時文件及不安全的方式。
3.1 不正確示例:
不正確1:
import os import tempfile # This will most certainly put you at risk tmp = os.path.join(tempfile.gettempdir(), filename) if not os.path.exists(tmp): with open(tmp, "w") file: file.write("defaults")
不正確2:
import os import tempfile open(tempfile.mktemp(), "w")
不正確3:
filename = "{}/{}.tmp".format(tempfile.gettempdir(), os.getpid()) open(filename, "w")
3.2 正確示例
正確1:
fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'w') as tmp: # do stuff with temp file tmp.write('stuff') finally: os.remove(path)
正確2:
# 句柄關閉,文件即刪除 with tempfile.TemporaryFile() as tmp: # Do stuff with tmp tmp.write('stuff')
正確3:
tmp = tempfile.NamedTemporaryFile(delete=True) try: # do stuff with temp tmp.write('stuff') finally: tmp.close() # 文件關閉即刪除
相關免費學習推薦:python教程(視頻)