dto5637 2019-01-29 10:14
浏览 1324

如何在Golang中执行交互式CLI命令?

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.

  • 写回答

2条回答 默认 最新

  • doulao2128 2019-01-30 07:50
    关注

    https://github.com/manifoldco/promptui

    This is a good enough choice to meet your requirements. I think it's not a good idea to reinvent the wheel.

    评论

报告相同问题?