douyi1855
2016-03-10 03:23
浏览 87
已采纳

Go x / crypto / ssh-如何通过堡垒节点建立与私有实例的ssh连接

I want to implement this scenario: On AWS, I have a VPC, in which it is deployed a public and private subnet. In the public subnet, I have a "bastion" instance, while in private subnet, there is one node running some services(AKA "service instance"). By using *nux ssh command, I can do things like this to connect to the "service instance" from my local laptop:

ssh -t -o ProxyCommand="ssh -i <key> ubuntu@<bastion-ip> nc %h %p" -i <key> ubuntu@<service-instance-ip>

I have a Go program, and want to do the following things:

  1. ssh connect to the "service instance" from "local laptop" over the "bastion"
  2. use the connection session to run some commands (e.g. "ls -l")
  3. upload files from "local laptop" to "service instance"

I've tried but not able to implement the same process as doing

ssh -t -o ProxyCommand="ssh -i <key> ubuntu@<bastion-ip> nc %h %p" -i <key> ubuntu@<service-instance-ip>

Could anyone help to show me an example? Thanks!

BTW, I found this: https://github.com/golang/go/issues/6223, which means it is definately able to do that, right?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzhulan1815 2016-03-10 18:48
    已采纳

    You can do this even more directly with the "x/crypto/ssh" without the nc command, since there is a method to dial a connection from the remote host and presents it as a net.Conn.

    Once you have an ssh.Client, you can use the Dial method to get a virtual net.Conn between you and the final host. You can then turn that into a new ssh.Conn with ssh.NewClientConn, and create a new ssh.Client with ssh.NewClient

    // connect to the bastion host
    bClient, err := ssh.Dial("tcp", bastionAddr, config)
    if err != nil {
        log.Fatal(err)
    }
    
    // Dial a connection to the service host, from the bastion
    conn, err := bClient.Dial("tcp", serviceAddr)
    if err != nil {
        log.Fatal(err)
    }
    
    ncc, chans, reqs, err := ssh.NewClientConn(conn, serviceAddr, config)
    if err != nil {
        log.Fatal(err)
    }
    
    sClient := ssh.NewClient(ncc, chans, reqs)
    // sClient is an ssh client connected to the service host, through the bastion host.
    
    点赞 评论

相关推荐 更多相似问题