dongqian6484
2015-10-08 14:59
浏览 654
已采纳

将ssh公钥复制到服务器

I'm trying to add a public key under my local $HOME/.ssh/ directory using Go.

I've been running multiple commands with this the same code without problem, but not for this particular one.

identity := fmt.Sprintf("cat %s/.ssh/%s.pub", fileUtil.FindUserHomeDir(), p.sshkey.name)
address := fmt.Sprintf("| ssh %s@%s 'cat >> ~/.ssh/authorized_keys', p.projectname.name, p.host.name)

cmd := exec.Command(identity, address)

err := cmd.Run()
if err != nil {
    log.Fatal(err)
}

Basically I'm trying to run:

cat /home/foo/.ssh/foobar.pub | ssh foo@bar.com 'cat >> ~/.shh/authorized_keys'"

Which works fine if I run it through the command line directly.

I want to run this program in different OS X machines, where some don't have ssh-copy-id installed. So, I'm not considering to use it.

But anyway, I'm open to other suggestions. Thank you in advance.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douchu5131 2015-10-08 16:00
    已采纳

    You don't need to execute /bin/sh -c "cat file" to read a file in Go. Open the file normally, and give that to the ssh command

    keyFile, err := os.Open(filename)
    if err != nil {
        log.Fatal(err)
    }
    
    cmd := exec.Command("ssh", "user@host", "cat >> ~/.ssh/authorized_keys")
    cmd.Stdin = keyFile
    
    // run the command however you want
    out, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Println(string(out))
        log.Fatal(err)
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douken1726 2015-10-08 17:57

    You could simply execute rsync or scp for this purpose.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题