簡體   English   中英

在 python 腳本中使用 ssh 代理

[英]Using the ssh agent inside a python script

我正在使用 python 腳本拉並推送到 github 存儲庫。 對於 github 存儲庫,我需要使用 ssh 密鑰。

如果我在運行腳本之前手動執行此操作:

eval $(ssh-agent -s)
ssh-add ~/.ssh/myprivkey

一切正常,腳本有效。 但是,過了一會兒,顯然密鑰過期了,我必須再次運行這兩個 cmd

問題是,如果我在 python 腳本中使用os.system(cmd)執行此操作,則它不起作用,只有當我手動執行此操作時它才有效

我知道這一定是使用 ssh 代理的一種混亂方式,但老實說我不知道它是如何工作的,我只是想讓腳本工作,僅此而已

該腳本每小時運行一次,以防萬一

雖然正常的方法是在 ssh 代理已經運行的 shell 中運行 Python 腳本,但您也可以考慮使用sshify.py的替代方法。

# This utility will execute the given command (by default, your shell)
# in a subshell, with an ssh-agent process running and your
# private key added to it. When the subshell exits, the ssh-agent
# process is killed.

Consider defining the ssh key path against a host of github.com in your ssh config file as outlined here: https://stackoverflow.com/a/65791491/14648336

如果 Linux 則在此路徑 ~/.ssh/ 創建一個名為 config 的文件並輸入與上述答案類似的內容:

Host github.com
    HostName github.com
    User your_user_name
    IdentityFile ~/.ssh/your_ssh_priv_key_file_name

這將節省每次啟動代理的需要,並且如果使用 GitPython(您提到使用 Python),也可以防止需要自定義環境變量,如其他一些 SO 答案中所引用的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM