【问题标题】:Can setup ssh Keys to work from within a go program for git commands?可以设置 ssh 密钥以在 go 程序中为 git 命令工作吗?
【发布时间】:2020-03-03 22:07:50
【问题描述】:

我无法从 Go 的 exec.Command 运行 git pull --tags,因为我没有访问权限..

代码...

func SimpleCommand(start string, args ...string) (result string) {
    cmd := exec.Command(start, args...)

    //cmd.Dir = dir
    bytes, err := cmd.Output()
    if err != nil {
        fmt.Print(err)
    }
    s := string(bytes)

    return s

}
func main() {
    SimpleCommand("git", "pull", "--tags")


}

通常当我运行 git 命令时,我会在 Git-bash 中手动执行它,并且我的 .bashrc 文件设置如下...

 eval $(ssh-agent -s) 
 ssh-add c:/sshkeys/id_rsa 
 ssh-add c:/sshkeys/github

这很好用,但是当我在 Go 程序中运行 git 命令时,它显然不会运行这些命令。所以我得到以下错误...

git@gitlab.com:权限被拒绝(公钥)。致命:无法读取 来自远程存储库。

请确保您拥有正确的访问权限和存储库 存在。

我尝试使用 SimpleCommand 函数单独运行这些命令,但是找不到 eval 命令(它似乎不是可执行文件),

我也觉得应该有更好的方法来做到这一点,我无法让 go 程序以这样的方式管理 ssh 密钥,以便能够使用它们来运行 git 命令。

【问题讨论】:

  • Go 不在 bash shell 中运行命令。而是尝试设置core.sshCommand。例如git config core.sshCommand "ssh -i c:/sshkeys/id_rsa -i s:/sshkeys/github"。这很有用,因为 git config 设置可以是全局的或本地的。
  • 查看这个答案以获取各种解决方法的线索stackoverflow.com/questions/7772190/…
  • @Mark 我昨晚进行了更深入的研究,发现了 core.sshCommand 并最终让它工作,我会发布更多答案,但如果你想继续?
  • @user3755946 一定要发布你的答案,很高兴你得到它的工作。

标签: git go ssh


【解决方案1】:

不知道 core.sshCommand,现在对我有用。

设置当前存储库以在特定位置使用 ssh 密钥...

设置功能...

func SetupGitSsh() {
    sshKeysDir := "c:/sshkeys/id_rsa"
    sshloc := fmt.Sprintf("ssh -i %s", sshKeysDir)
    DirCommand("git", "c:\\DEV\\outsideprj", "config", "core.sshCommand", sshloc)
}

DirCommand 函数...

func DirCommand(app string, dir string, args ...string) {

    cmd := exec.Command(app, args...)
    cmd.Dir = dir
    stdout, err := cmd.Output()

    if err != nil {
        fmt.Println(err.Error())
        return
    }

    fmt.Print(string(stdout))
}

【讨论】:

    猜你喜欢
    • 2014-06-26
    • 2015-09-23
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2021-08-16
    • 2012-05-05
    相关资源
    最近更新 更多