英文:
SSH from Golang code successfully but hangs
问题
我使用以下Go代码来打开与远程主机的SSH连接:
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")
}
当我运行这段代码时,成功连接到远程主机并获得一个终端,但是当我输入命令时,没有任何输出,只是卡住了。我尝试通过终端正常使用SSH,一切正常。不确定这是我的代码还是SSH的问题。
英文:
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
答案1
得分: 1
请使用以下代码:
package main
import (
"log"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
func main() {
// ssh配置
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,
}
// 连接到ssh服务器
conn, err := ssh.Dial("tcp", "192.169.0.1:22", config)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
}
以上代码是基于密码的登录方式。如果要使用证书进行身份验证,需要进行一些更改。
进一步阅读:
英文:
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:
答案2
得分: 0
将os.Stdin分配给Stdin可以解决这个问题,微妙的地方
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())
}
}
英文:
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())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论