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:
- ssh connect to the "service instance" from "local laptop" over the "bastion"
- use the connection session to run some commands (e.g. "ls -l")
- 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With