简体   繁体   English

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

[英]Go x/crypto/ssh — How to establish ssh connection to private instance over a bastion node

I want to implement this scenario: On AWS, I have a VPC, in which it is deployed a public and private subnet. 我想实现这个场景:在AWS上,我有一个VPC,它部署了一个公共和私有子网。 In the public subnet, I have a "bastion" instance, while in private subnet, there is one node running some services(AKA "service instance"). 在公有子网中,我有一个“堡垒”实例,而在私有子网中,有一个节点运行一些服务(AKA“服务实例”)。 By using *nux ssh command, I can do things like this to connect to the "service instance" from my local laptop: 通过使用* nux ssh命令,我可以做这样的事情从我的本地笔记本电脑连接到“服务实例”:

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: 我有一个Go程序,想要做以下事情:

  1. ssh connect to the "service instance" from "local laptop" over the "bastion" ssh通过“堡垒”从“本地笔记本电脑”连接到“服务实例”
  2. use the connection session to run some commands (eg "ls -l") 使用连接会话来运行一些命令(例如“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? 顺便说一下,我发现了这个: https//github.com/golang/go/issues/6223 ,这意味着它绝对能够做到这一点,对吧?

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 . 您可以使用“x / crypto / ssh”直接执行此操作而不使用nc命令,因为有一种方法可以从远程主机拨打连接并将其显示为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. 一旦有了ssh.Client ,就可以使用Dial方法获得你和最终主机之间的虚拟网络net.Conn You can then turn that into a new ssh.Conn with ssh.NewClientConn , and create a new ssh.Client with ssh.NewClient 然后,您可以把它转换成一个新的ssh.Connssh.NewClientConn ,并创建一个新ssh.Clientssh.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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM