Is it possible to SSH to another host while in an SSH session in golang? I tried chaining some stuff together like this, but the printout says the remote addr of client 2 is 0.0.0.0 and an error is given when I try to execute anything on an ssh.Session from client2.
host1 := "host1.com"
host2 := "host2.com"
client1, err := ssh.Dial("tcp", host, config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
conn, err := client1.Dial("tcp", host2)
if err != nil {
panic(err)
}
sshConn, newChan, requestChan, err := ssh.NewClientConn(conn, host2, config)
if err != nil {
panic(err)
}
client2 := ssh.NewClient(sshConn, newChan, requestChan)
fmt.Println("Client 2 RemoteAddr():", client2.RemoteAddr())
The problem is that you are running all of this code on the same host. Let's call the host you run your app on host0
for convenience.
You start out making a connection from host0
to host1
. That works fine. What you seem to want to do next is make a connection from host1
to host2
. To do that you need to run the SSH code on host1
. But your app, which is and always has been running on host0
, is not in the place to do that.
You will need to put a program on host1
that does the connection to host2
and then send a command down the SSH connection to host1
that will start that program.