将SSH公钥复制到服务器上。

huangapple go评论75阅读模式
英文:

Copying ssh public key to server

问题

我正在尝试使用Go语言在本地$HOME/.ssh/目录下添加一个公钥。

我已经使用相同的代码运行多个命令而没有问题,但对于这个特定的命令却有问题。

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)
}

基本上,我想运行以下命令:

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

如果我直接在命令行中运行它,是可以正常工作的。

我想在不同的OS X机器上运行这个程序,其中一些机器上没有安装ssh-copy-id。所以,我不考虑使用它。

但无论如何,我对其他建议也持开放态度。提前谢谢。

英文:

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.

答案1

得分: 4

你不需要在Go语言中执行/bin/sh -c "cat file"来读取文件。正常打开文件,并将其提供给ssh命令即可。

keyFile, err := os.Open(filename)
if err != nil {
    log.Fatal(err)
}

cmd := exec.Command("ssh", "user@host", "cat >> ~/.ssh/authorized_keys")
cmd.Stdin = keyFile

// 以你想要的方式运行命令
out, err := cmd.CombinedOutput()
if err != nil {
    fmt.Println(string(out))
    log.Fatal(err)
}

以上是翻译好的内容,请确认是否满意。

英文:

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)
}

答案2

得分: 1

你可以简单地使用rsync或scp来完成这个目的。

英文:

You could simply execute rsync or scp for this purpose.

huangapple
  • 本文由 发表于 2015年10月8日 22:59:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/33019398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定