2

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 Answer 1

4

. 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()
Sign up to request clarification or add additional context in comments.

3 Comments

Omg, I didn't know that the ssh command can also be passed without ''. This works indeed. Thanks a lot!
Regarding ssh you also might have a look into: pkg.go.dev/golang.org/x/crypto/ssh For better security and advanced control
@Tobi696 Don't forget to accpet this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.