Execute ssh in golang - go

I'm looking for a way to launch ssh in a terminal from a golang program.
func main() {
cmd := exec.Command("ssh", "user#192.168.0.17", "-p", "2222")
err := cmd.Run()
if err != nil {
panic(err)
}
}
This works great until I enter the correct password, then the program exits. I guess when authentified, another ssh script in launched, but I can't figure out how to solve this. I have searched some infos about it but all I found is how to create a ssh session in go, and I would like to avoid this, if possible.

You should pass in stdin, stdout, and stderr:
package main
import (
"os"
"os/exec"
)
func main() {
cmd := exec.Command("ssh", "user#192.168.0.17", "-p", "2222")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
panic(err)
}
}

I have found another way to solve my issue, by using :
binary, lookErr := exec.LookPath("ssh")
if lookErr != nil {
panic(lookErr)
}
syscall.Exec(binary, []string{"ssh", "user#192.168.0.17", "-p", "2222"}, os.Environ())
This will close the program's process and launch ssh on another one.
Thanks for helping me !

Related

Spawn vim using golang

I am trying to run a simple program that spawns a vim process.
The user should be able (when the exec.Command starts) to switch to vim window and the process execution should halt there.
When user closes vim (wq!) the program execution should resume from that point.
The following simple attempt fails but I cannot figure out why
package main
import (
"log"
"os/exec"
)
func main() {
cmd := exec.Command("vim", "lala")
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}
▶ go run main.go
2022/11/25 09:16:44 exit status 1
exit status 1
Why the exit status 1?
You missed these two lines:
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
Thanks to these two lines the user is able to edit with vim the file in the terminal. The control is returned to the program when the user quit from the terminal (e.g., with the command :wq). Below, you can find the whole code:
package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("vim", "lala")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}
Hope this helps!
Because you should set Stdin and Stdoutfor cmd:
package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("vim", "lala")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}

How to execute interactive CLI command in golang?

I'm trying to execute a command that asks for several inputs for example if you try to copy a file from local device to the remote device we use scp test.txt user#domain:~/ then it asks us for the password. What I want is I want to write a go code where I provide the password in the code itself for example pass:='Secret Password'. Similarly, I have CLI command where it asks us for several things such as IP, name, etc so I need to write a code where I just declare all the values in the code itself and when I run the code it doesn't ask anything just take all the inputs from code and run CLI command in case of copying file to remote it should not ask me for password when I run my go binary it should directly copy my file to remote decide.
func main() {
cmd := exec.Command("scp", "text.txt", "user#domain:~/")
stdin, err := cmd.StdinPipe()
if err = cmd.Start(); err != nil {
log.Fatalf("failed to start command: %s", err)
}
io.WriteString(stdin, "password\n")
if err = cmd.Wait(); err != nil {
log.Fatalf("command failed: %s", err)
}
}
If I use this code it is stuck on user#domain's password:
And no file is copied to the remote device.
Solution 1
You can bypass this with printf command
cmd := "printf 'John Doe\nNew York\n35' | myInteractiveCmd"
out, err := exec.Command("bash", "-c", cmd).Output()
Solution 2
You can use io.Pipe(). Pipe creates a synchronous in-memory pipe and you can write your answers into io.Writer and your cmd will read from io.Reader.
r, w := io.Pipe()
cmd := exec.Command("myInteractiveCmd")
cmd.Stdin = r
go func() {
fmt.Fprintf(w, "John Doe\n")
fmt.Fprintf(w, "New York\n")
fmt.Fprintf(w, "35\n")
w.Close()
}()
cmd.Start()
cmd.Wait()
Testing info
To test this I wrote cmd which asks for name, city, age and writes the result in file.
reader := bufio.NewReader(os.Stdin)
fmt.Print("Name: ")
name, _ := reader.ReadString('\n')
name = strings.Trim(name, "\n")
...
One way to go about this is to use command-line flags:
package main
import (
"flag"
"fmt"
"math"
)
func main() {
var (
name = flag.String("name", "John", "Enter your name.")
ip = flag.Int("ip", 12345, "What is your ip?")
)
flag.Parse()
fmt.Println("name:", *name)
fmt.Println("ip:", *ip)
}
Now you can run the program with name and ip flags:
go run main.go -name="some random name" -ip=12345678910`
some random name
ip: 12345678910
This channel is a good resource—he used to work for the Go team and made tons of videos on developing command-line programs in the language. Good luck!
I come across this question when trying to run the linux make menuconfig through golang os/exec.
To accomplish what you are trying to achieve try to set the cmd.Stdin to os.Stdin. Here is a working example:
package main
import (
"fmt"
"os"
"os/exec"
)
type cmdWithEnv struct {
pwd string
command string
cmdArgs []string
envs []string
}
func runCommand(s cmdWithEnv) error {
cmd := exec.Command(s.command, s.cmdArgs...)
if len(s.pwd) != 0 {
cmd.Dir = s.pwd
}
env := os.Environ()
env = append(env, s.envs...)
cmd.Env = env
fmt.Printf("%v\n", cmd)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin // setting this allowed me to interact with ncurses interface from `make menuconfig`
err := cmd.Start()
if err != nil {
return err
}
if err := cmd.Wait(); err != nil {
return err
}
return nil
}
func buildPackage() {
makeKernelConfig := cmdWithEnv{
pwd: "linux",
command: "make",
cmdArgs: []string{"-j12", "menuconfig"},
envs: []string{"CROSS_COMPILE=ccache arm-linux-gnueabihf-", "ARCH=arm"},
}
runCommand(makeKernelConfig)
}
func main() {
buildPackage()
}

Go: Run External Python script

I have tried following the Go Docs in order to call a python script which just outputs "Hello" from GO, but have failed until now.
exec.Command("script.py")
or I've also tried calling a shell script which simply calls the python script, but also failed:
exec.Command("job.sh")
Any ideas how would I achieve this?
EDIT
I solved following the suggestion in the comments and adding the full path to exec.Command().
Did you try adding Run() or Output(), as in:
exec.Command("script.py").Run()
exec.Command("job.sh").Run()
You can see it used in "How to execute a simple Windows DOS command in Golang?" (for Windows, but the same idea applies for Unix)
c := exec.Command("job.sh")
if err := c.Run(); err != nil {
fmt.Println("Error: ", err)
}
Or, with Output() as in "Exec a shell command in Go":
cmd := exec.Command("job.sh")
out, err := cmd.Output()
if err != nil {
println(err.Error())
return
}
fmt.Println(string(out))
First of all do not forget to make your python script executable (permissions and #!/usr/local/bin/python at the beginning).
After this you can just run something similar to this (notice that it will report you errors and standard output).
package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("script.py")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Println(cmd.Run())
}
Below worked for me on Windows 10
python := path.Clean(strings.Join([]string{os.Getenv("userprofile"), "Anaconda3", "python.exe"}, "/"))
script := "my_script.py"
cmd := exec.Command("cmd", python, script)
out, err := cmd.Output()
fmt.Println(string(out))
if err != nil {
log.Fatal(err)
}

How to start vim from go?

I've got a command line tool written in Golang and I need to start vim from it. However it's not working, and there's not any error or much else to work with. I've reduced the code to just this:
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("vim", "test.txt")
err := cmd.Run()
fmt.Println(err)
}
When I run this, I can see the vim process for a 2-3 seconds but the application doesn't actually open. Then the program simply exits (and the vim process closes) with an "exit status 1".
I've also tried this to capture stderr:
package main
import (
"bytes"
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("vim", "test.txt")
var stderr bytes.Buffer
cmd.Stderr = &stderr
err := cmd.Run()
fmt.Println(err)
fmt.Println(stderr)
}
But in this case, the program gets stuck indefinitely.
Any idea what could be the issue?
Pass on stdin and stdout from the calling program which, provided it was run from a terminal (likely for a command line program) will start vim for you and return control when the user has finished editing the file.
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("vim", "test.txt")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err := cmd.Run()
fmt.Println(err)
}
VIM needs a proper terminal and detects the absence of one.
If you use the StderrPipe and read it while vim is running you will see this:
2014/02/02 20:25:49 Vim: Warning: Output is not to a terminal
2014/02/02 20:25:49 Vim: Warning: Input is not from a terminal
Example for reading stderr while executing (on play):
func logger(pipe io.ReadCloser) {
reader := bufio.NewReader(pipe)
for {
output, err := reader.ReadString('\n')
if err != nil {
log.Println(err)
return
}
log.Print(string(output))
}
}
pipe, err := cmd.StderrPipe()
go logger(pipe)
cmd.Run()
For vim to run you probably need to emulate a terminal.
Maybe goat (doc) can help you out:
tty := term.NewTTY(os.Stdin)
cmd := exec.Command("vim", "test.txt")
cmd.Stdin = t
cmd.Stdout = t
// ...

Redirect stdout pipe of child process in Go

I'm writing a program in Go that executes a server like program (also Go). Now I want to have the stdout of the child program in my terminal window where I started the parent program. One way to do this is with the cmd.Output() function, but this prints the stdout only after the process has exited. (That's a problem because this server-like program runs for a long time and I want to read the log output)
The variable out is of type io.ReadCloser and I don't know what I should do with it to achieve my task, and I can't find anything helpful on the web on this topic.
func main() {
cmd := exec.Command("/path/to/my/child/program")
out, err := cmd.StdoutPipe()
if err != nil {
fmt.Println(err)
}
err = cmd.Start()
if err != nil {
fmt.Println(err)
}
//fmt.Println(out)
cmd.Wait()
}
Explanation to the code: uncomment the Println function to get the code to compile, I know that Println(out io.ReadCloser) is not a meaningful function.
(it produces the output &{3 |0 <nil> 0} ) These two lines are just required to get the code to compile.
Now I want to have the stdout of the child program in my terminal
window where I started the parent program.
No need to mess with pipes or goroutines, this one is easy.
func main() {
// Replace `ls` (and its arguments) with something more interesting
cmd := exec.Command("ls", "-l")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
}
I believe that if you import io and os and replace this:
//fmt.Println(out)
with this:
go io.Copy(os.Stdout, out)
(see documentation for io.Copy and for os.Stdout), it will do what you want. (Disclaimer: not tested.)
By the way, you'll probably want to capture standard-error as well, by using the same approach as for standard-output, but with cmd.StderrPipe and os.Stderr.
For those who don't need this in a loop, but would like the command output to echo into the terminal without having cmd.Wait() blocking other statements:
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
)
func checkError(err error) {
if err != nil {
log.Fatalf("Error: %s", err)
}
}
func main() {
// Replace `ls` (and its arguments) with something more interesting
cmd := exec.Command("ls", "-l")
// Create stdout, stderr streams of type io.Reader
stdout, err := cmd.StdoutPipe()
checkError(err)
stderr, err := cmd.StderrPipe()
checkError(err)
// Start command
err = cmd.Start()
checkError(err)
// Don't let main() exit before our command has finished running
defer cmd.Wait() // Doesn't block
// Non-blockingly echo command output to terminal
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
// I love Go's trivial concurrency :-D
fmt.Printf("Do other stuff here! No need to wait.\n\n")
}

Resources