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
")
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.
This is a good enough choice to meet your requirements. I think it's not a good idea to reinvent the wheel.
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!