在之前的一系列文章中,小爬分享了很多用Pywin32、uiAutomation、sap Gui Script等技術實現應用程序或者Web網站(如SAP、Excel、outLook郵件系統、OA系統)的自動化操作的文章。但是,這些文章都繞開了一個知識點:如何優雅地實現自動登錄。與其說是想聊聊如何實現自動登錄,其實是繞到了另一個技術問題:如何安全可靠的存儲、更新和讀取用戶名、密碼?
都2023年了,即使是給自己用的python腳本,小爬也絕不建議直接在腳本中寫下明文的密碼,亦或是在某個ini配置文件中直接寫密碼,這樣密碼泄露的風險非常高。如果咱們開發的腳本是準備封裝爲exe文件給他人使用,更是應該做好這些用戶名、密碼信息的安全存儲,不然誰敢用你提供的工具。
不賣關子,如果您剛好喜歡用python編程,這裏推薦使用python第三方包,keyring(keyring · PyPI),非常方便。
Python keyring庫使我們輕鬆訪問系統的keyring服務,它可以用於任何 需要安全密碼存儲的應用程序。在windows系統中,keyring支持的後端服務:Windows Credential Locker
Keyring簡單上手
keyring最基礎的用法很簡單,只需要用到 keyring.set_password 以及keyring.get_password 方法:
>>> import keyring >>> keyring.set_password("system", "username", "password") >>> keyring.get_password("system", "username") 'password'
命令行用法
當我們通過pip install keyring安裝完之後,我們便可以在命令行(CMD、Powershell)下輕鬆設置、獲取以及刪除密碼。
PS C:\Users\Admin> keyring -h usage: keyring [-h] [-p KEYRING_PATH] [-b KEYRING_BACKEND] [--list-backends] [--disable] [--print-completion {bash,zsh,tcsh}] [{get,set,del,diagnose}] [service] [username] positional arguments: {get,set,del,diagnose} service username optional arguments: -h, --help show this help message and exit -p KEYRING_PATH, --keyring-path KEYRING_PATH Path to the keyring backend -b KEYRING_BACKEND, --keyring-backend KEYRING_BACKEND Name of the keyring backend --list-backends List keyring backends and exit --disable Disable keyring and exit --print-completion {bash,zsh,tcsh} print shell completion script
知道這些之後,假如我們想存儲比如OA的用戶名 NewJune、密碼mypsd,在命令行中的效果是這樣:
PS C:\Users\admin> keyring set oa newjune Password for 'newjune' in 'oa': PS C:\Users\adminn> keyring get oa newjune mypsw
API
keyring庫給我們提供了這些API來調用:
-
get_keyring(): Return the currently-loaded keyring implementation.返回當前載入的keyring實現。
-
get_password(service, username): Returns the password stored in the active keyring. If the password does not exist, it will return None.返回當前活躍keyring中存儲的密碼,如果密碼不存在,則返回None。
-
get_credential(service, username): 返回活躍keyring中的一個credential對象,對象中包含特定服務的username和password屬性。username參數可以設置爲None,如果某個服務存儲了多組用戶名密碼,則會隨機返回一組。
-
set_password(service, username, password): Store the password in the keyring.將密碼存儲入keyring中。
-
delete_password(service, username): Delete the password stored in keyring. If the password does not exist, it will raise an exception.刪除存儲在keyring中的密碼,如果密碼不存在,則會拋出異常。
有了Keyring庫,我們就可以輕鬆將SAP、OA、瀏覽器等應用的用戶名、密碼進行系統安全級別的存儲,也可以隨時用腳本取出對應的憑據credential,爲程序的自動登錄、後臺作業等場景提供支持,趕緊試試吧!
快來關注本公衆號 獲取更多爬蟲、數據分析的知識!