使用多个参数运行Linux命令

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

Running Linux commands with multiple arguments

问题

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

func main() {
    lsCmd := exec.Command("ls")
    lsOut, err := lsCmd.Output()
    if err != nil {
        panic(err)
    }
    fmt.Println(">ls")
    fmt.Println(string(lsOut))
}

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

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

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

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

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

英文:

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

func main() {
	lsCmd := exec.Command("ls")
	lsOut, err := lsCmd.Output()
	if err != nil {
		panic(err)
	}
	fmt.Println(">ls")
	fmt.Println(string(lsOut))
}

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

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:

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方法的不同参数。
你应该这样做:

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 :

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

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

ssh username@ip < EOf

ls -I

pwd

uname

Eof

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

英文:

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

Ssh username@ip < EOf

ls -I

Pwd

Uname

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:

确定