使用多个参数运行Linux命令

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

Running Linux commands with multiple arguments

问题

在进行一些调查后,我可以像这样从Go中运行Linux命令:

  1. func main() {
  2. lsCmd := exec.Command("ls")
  3. lsOut, err := lsCmd.Output()
  4. if err != nil {
  5. panic(err)
  6. }
  7. fmt.Println(">ls")
  8. fmt.Println(string(lsOut))
  9. }

我想要做的是在远程机器上运行以下命令:

  1. ssh -p $someport $someuser@$someip 'ls'

我可以在终端中成功执行此命令,但是当我尝试在Go中运行时,我会得到以下错误:

  1. panic: exec: "ssh -p $someport $someuser@$someip 'ls'": 可执行文件在$PATH中未找到

更新:为了方便起见,我更新了问题。

英文:

After some digging I can run Linux commands from go like this:

  1. func main() {
  2. lsCmd := exec.Command("ls")
  3. lsOut, err := lsCmd.Output()
  4. if err != nil {
  5. panic(err)
  6. }
  7. fmt.Println(">ls")
  8. fmt.Println(string(lsOut))
  9. }

What I want to do is, running following command in remote machine:

  1. ssh -p $someport $someuser@$someip 'ls'

I can do this successfully from my terminal, but when I try to run it within Go, I get following error:

  1. panic: exec: "ssh -p $someport $someuser@$someip 'ls'": executable file not found in $PATH

Update: I updated the question for convenience.

答案1

得分: 7

根据关于exec包的文档,程序名称和参数是Command方法的不同参数。
你应该这样做:

  1. exec.Command("ssh", "-p port", "user@ip", "'ls'")

如果你需要更复杂的操作,你也可以查看go.crypto/ssh包。

英文:

As per the doc about the exec package, program name and arguments are differents parameters of the Command method.
You should do something like that :

  1. exec.Command("ssh", "-p port", "user@ip", "'ls'")

If you need something more elaborate, you could also look at the go.crypto/ssh package.

答案2

得分: -1

如果你想在远程机器上运行多个命令,下面的技巧可能会帮助你实现这个目标。

  1. ssh username@ip < EOf
  2. ls -I
  3. pwd
  4. uname
  5. Eof

请注意,它不会传递任何特殊字符,如. ,等。

英文:

If you want run multiple commands on a remote machine the below trick might help you achieve this.

  1. Ssh username@ip < EOf
  2. ls -I
  3. Pwd
  4. Uname
  5. Eof

Please note that it doesn't pass any special characters like . , etc.

huangapple
  • 本文由 发表于 2014年6月12日 17:08:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/24180517.html
匿名

发表评论

匿名网友

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

确定