duananyu9231 2014-06-26 18:37
浏览 780
已采纳

使用SSH和带有golang的pem /密钥连接到服务器

I'm trying to connect to an amazon AWS linux server with a key using the [ssh][1] package of Go programming language. However the package documentation is a bit cryptic/confusing. Does anyone know how to connect through ssh using a key or at least if it's possible ? What bothers me is that in the [Dial][3] example it says

// An SSH client is represented with a ClientConn. Currently only
// the "password" authentication method is supported.

I basically want to mimic the ssh -i x.pem root@server.com behavior and execute a command inside the server ( e.g. whoami )

  • 写回答

2条回答 默认 最新

  • dtukyb8095 2014-06-26 19:03
    关注

    You need to use ssh.PublicKeys to turn a list of ssh.Signers into an ssh.AuthMethod. You can use ssh.ParsePrivateKey to get a Signer from the pem bytes, or if you need to use an rsa, dsa or ecdsa private key, you can give those to ssh.NewSignerFromKey.

    Here's an example fleshed out a bit with Agent support too (since using an agent is usually the next step after simply using a key file).

    sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
    if err != nil {
        log.Fatal(err)
    }
    
    agent := agent.NewClient(sock)
    
    signers, err := agent.Signers()
    if err != nil {
        log.Fatal(err)
    }
    
    // or get the signer from your private key file directly
    // signer, err := ssh.ParsePrivateKey(pemBytes)
    // if err != nil {
    //     log.Fatal(err)
    // }
    
    auths := []ssh.AuthMethod{ssh.PublicKeys(signers...)}
    
    cfg := &ssh.ClientConfig{
        User: "username",
        Auth: auths,
    }
    cfg.SetDefaults()
    
    client, err := ssh.Dial("tcp", "aws-hostname:22", cfg)
    if err != nil {
        log.Fatal(err)
    }
    
    session, err = client.NewSession()
    if err != nil {
        log.Fatal(err)
    }
    
    log.Println("we have a session!")
    
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题