使用SSH和带有golang的pem/密钥连接到服务器 [英] Connect to a server using SSH and a pem / key with golang

查看:398
本文介绍了使用SSH和带有golang的pem/密钥连接到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Go编程语言的[ssh] [1]包通过密钥连接到Amazon AWS AWS Linux服务器.但是,软件包文档有些含糊/令人困惑.有谁知道如何通过使用密钥的ssh进行连接,或者至少在可能的情况下?令我困扰的是[Dial] [3]示例中的内容

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.

我基本上想模仿ssh -i x.pem root@server.com的行为,并在服务器内部执行命令(例如whoami)

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

推荐答案

您需要使用ssh.PublicKeysssh.Signers的列表转换为ssh.AuthMethod.您可以使用ssh.ParsePrivateKey从pem字节中获取Signer,或者,如果需要使用rsa,dsa或ecdsa私钥,则可以将其提供给ssh.NewSignerFromKey.

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.

这也是一个在Agent支持下充实的示例(因为使用Agent通常是仅使用密钥文件之后的下一步).

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!")

...

这篇关于使用SSH和带有golang的pem/密钥连接到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆