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

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样