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

将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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作