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

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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多