使用Golang的os/exec执行带参数的ssh命令会导致退出状态为127。

huangapple go评论111阅读模式
英文:

Executing ssh command with args using Golang os/exec leads to Exit status 127

问题

在我的golang程序中,我需要通过ssh在远程服务器上执行命令。
我的计算机有一个存储的私钥,可以无需密码连接到服务器。

这是我运行远程命令的代码:

out, err := exec.Command("ssh", "myserver.com", "'ls'").Output()
fmt.Println(string(out), err)

这段代码按预期工作,但是当我在ssh服务器上执行的命令中添加参数时,我会收到一个带有Exit Status 127的错误。

示例代码:

out, err := exec.Command("ssh", "myserver.com", "'ls .'").Output()
fmt.Println(string(out), err, exercise)

这段代码导致出现exit status 127的错误。

为了避免这个问题,我应该如何格式化我的ssh命令?

英文:

In my golang program, I need to execute a command on a remote server via ssh.
My computer has a private key stored to connect to the server without password.

Here's my code for running remote commands:

out, err := exec.Command("ssh", "myserver.com", "'ls'").Output()
fmt.Println(string(out), err)

This code works as expected, however, when I add arguments to the command executed on the ssh server, the I get an error with Exit Status 127

Example Code:

out, err := exec.Command("ssh", "myserver.com", "'ls .'").Output()
fmt.Println(string(out), err, exercise)

This code leads to: exit status 127

How do I have to format my ssh command in order to avoid this?

答案1

得分: 4

.”是你的命令中的另一个参数,必须单独在参数列表中传递:

out, err := exec.Command("ssh", "myserver.com", "ls", ".").Output()

或者:

out, err := exec.Command("ssh", "myserver.com", "ls", "/path/to/any/other/dir").Output()
英文:

. is another argument in your command which has to be passed in the argument list separately:

out, err := exec.Command("ssh", "myserver.com", "ls", ".").Output()

or:

out, err := exec.Command("ssh", "myserver.com", "ls", "/path/to/any/other/dir").Output()

huangapple
  • 本文由 发表于 2022年9月8日 16:04:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/73645637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定