通过堡垒主机进行SSH

时间:2020-02-03 20:21:11

标签: go ssh

我刚刚开始使用Go,并且尝试通过堡垒主机建立ssh连接,我成功地对堡垒主机进行了身份验证,但是在LAN主机上失败。我已经阅读了许多帖子,the answer to this很有帮助。但是我不确定那个人的配置会是什么。我的代码如下。我正在尝试只使用PublicKeys,如果它的重要性是我从Mac上开始,请对Linux进行身份验证,然后无法与另一个Linux主机建立第二个连接。普通的SSH可以正常工作

package main

import (
    "fmt"
    "golang.org/x/crypto/ssh"
    "io/ioutil"
    "log"
    "os/user"
)
const TCP  = "tcp"
const PORT = "22"

func bastionConnect(bastion string, localh string) *ssh.Client {
    var usr, _ = user.Current()
    var homeDir = usr.HomeDir
    fmt.Printf("home is %v\n", homeDir)
    key, err := ioutil.ReadFile(homeDir + "/.ssh/id_rsa")
    if err != nil {
        fmt.Print("i'm dying at reading ssh key")
        panic(err)
    }

    signer, err := ssh.ParsePrivateKey(key)
    if err != nil {
        fmt.Print("i'm dying at parsing private key")
        panic(err)
    }
    fmt.Printf("I'm returning public keys for %v", signer.PublicKey())

    config := &ssh.ClientConfig{
        User:              usr.Username,
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        Auth:              []ssh.AuthMethod{
            ssh.PublicKeys(signer),
        },
    }

    bClient, err := ssh.Dial(TCP, bastion+":22", config)

    if err != nil {
        log.Fatal(err)
    }
    fmt.Print("passed bastion host\n")
    // Dial a connection to the service host, from the bastion
    conn, err := bClient.Dial(TCP, fmt.Sprintf("%s:%s", localh, PORT))

    if err != nil {
        log.Fatal(err)
    }
    ncc, chans, reqs, err := ssh.NewClientConn(conn, fmt.Sprintf("%s:%s", localh, PORT), config)
    if err != nil {
        fmt.Printf("Error trying to conntect to %s via bastion host\n%v\n", localh, err)
        log.Fatal(err)
    }

    sClient := ssh.NewClient(ncc, chans, reqs)

    return sClient
}

func main()  {
    var bastion = "jumpdev.example.org"
    var lanHost = "devserver01"
    bastionConnect(bastion, lanHost)
}

我看到的最后一条日志行是Error trying to connect to devserver01 via bastion host,错误为

2020/02/03 14:40:17 ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey]

请赦免所有Printfs所需要的内容。 在第二个连接中,公钥配置可能会搞砸吗?我还签出了this project,但似乎有点过头了。

1 个答案:

答案 0 :(得分:1)

上面的代码很好,我遇到了一个authorized_keys的问题,该问题一直连接到我,但忘记了本地.ssh/config:(

我想对此做些扩展,所以不仅仅是混乱,我搞砸了帖子。为使lanhost代理连接更完整,我更新了gist here