I used the following go code to open an ssh connection to a remote host
func ssh(keyname string, user string, address string) {
cmd := exec.Command("ssh", "-tt", user "@" address, "-i", "~/" keyname)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
fmt.Println(err.Error())
}
}
func main() {
ssh("example.pem", "ubuntu", "192.169.0.1")
}
When i run the code i connect successully to the remote host and get a terminal, but when i type commands it doesn't show any outputs just hangs, tried to ssh normally via my terminal and everything is ok. Not sure if this is from my code or SSH
CodePudding user response:
Use following code
package main
import (
"log"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
func main() {
// ssh config
hostKeyCallback, err := knownhosts.New("/home/debian11/.ssh/known_hosts")
if err != nil {
log.Fatal(err)
}
config := &ssh.ClientConfig{
User: "ubuntu",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: hostKeyCallback,
}
// connect to ssh server
conn, err := ssh.Dial("tcp", "192.169.0.1:22", config)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
}
Above is for password based login. Some changes will be required for certificate based auth.
Further reading:
CodePudding user response:
Assigning os.stdin to Stdin solves this problem, subtle
func ssh(keyname string, user string, address string) {
cmd := exec.Command("ssh", "-tt", user "@" address, "-i", "~/" keyname)
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
fmt.Println(err.Error())
}
}