I need to use lxd-p2c(https://github.com/lxc/lxd/tree/master/lxd-p2c) in golang code.
I try to pass password to the binary lxd-p2c built by the code above, which uses term.ReadPassword(0)(https://github.com/lxc/lxd/blob/master/lxd-p2c/utils.go#L166) to read password in Linux.
I did some search on the internet and tried following code but they just did not work.
# 1
cmd := exec.Command(command, args...)
cmd.Stdin = strings.NewReader(password)
# 2
cmd := exec.Command(command, args...)
stdin, _ := cmd.StdinPipe()
io.WriteString(stdin, password)
Similar but simple code to test: https://play.golang.org/p/l-9IP1mrhA (code from https://stackoverflow.com/a/32768479/9265302)
build the binary and call it in go.
edit:
No workaround found and I removed term.ReadPassword(0) in the source code.
Checking the error in your playground displays inappropriate ioctl for device.
Searching for the error message I found this thread, which notes that non-terminal input is not supported for terminal.ReadPassword. My guess is that passing Stdin input this way makes it pass the input with a character device instead of with the necessary terminal device like tty or any such, making the read fail. lxd-p2c can't read the password from such an input device.
Related
The answer IsExecOwner(file string) in https://stackoverflow.com/a/60128480/293195 addresses the topic but I am not sure if that is the equivalent to test -x in POSIX Shell? If the user is in the group of that file and the group has the executable bit set, this solution is probably not correct.
Do I need to consult https://godoc.org/golang.org/x/sys/unix
It's
func Access(path string, mode uint32) (err error)
in https://godoc.org/golang.org/x/sys/unix#Access
with mode := X_OK Referenz: https://linux.die.net/man/2/access
I am trying to patch a file using the below command
patch -p0 < <file_path>
My runCommand syntax is as below:
func runCommand(cmd string, args ...string) error {
ecmd := exec.Command(cmd, args...)
ecmd.Stdout = os.Stdout
ecmd.Stderr = os.Stderr
ecmd.Stdin = os.Stdin
err := ecmd.Run()
return err
}
Now I am passing my patch command as below:
cmd = "patch"
args := []string{"-p0", "<", "/tmp/file"}
err = runCommand(cmd, args...)
But I am seeing the below error:
patch: **** Can't find file '<' : No such file or directory
Can you please let me know what I am missing here?
You're missing this paragraph from the documentation:
Unlike the "system" library call from C and other languages, the
os/exec package intentionally does not invoke the system shell and
does not expand any glob patterns or handle other expansions,
pipelines, or redirections typically done by shells. The package
behaves more like C's "exec" family of functions. To expand glob
patterns, either call the shell directly, taking care to escape any
dangerous input, or use the path/filepath package's Glob function. To
expand environment variables, use package os's ExpandEnv.
The shell is responsible for handling < operations. You can set stdin yourself with the file as input or you can use the shell. To use the shell, try something like:
runCommand("/bin/sh", "patch -p0 < /tmp/file")
Note that this won't work on Windows. Reading the file and writing to stdin yourself is a more easily portable solution.
I'm experimenting with cgo to use C code from golang, but in my little hello-world test, I've ran into something I can't understand or find more information about.
I'm starting with a simple test similar to examples I've found
package main
import (
"fmt"
"unsafe"
)
/*
#import <stdio.h>
#import <stdlib.h>
*/
import "C"
func main() {
go2c := "Printed from C.puts"
var cstr *C.char = C.CString(go2c)
defer C.free(unsafe.Pointer(cstr))
C.puts(cstr)
fmt.Printf("Printed from golang fmt\n")
}
This simple example just echoes strings to stdout from both golang (using fmt.Printf) and raw C (using C.puts) via the basic cgo binding.
When I run this directly in my terminal, I see both lines:
$ ./main
Printed from C.puts
Printed from golang fmt
When I run this but redirect output in any way – pipe to less, shell redirection to a file, etc – I only see golang's output:
./main | cat
Printed from golang fmt
What happens to the C.puts content when piping / redirecting?
Secondary questions: Is this a cgo quirk, or a c standard library quirk I'm not aware of? Is this behaviour documented? How would I go about debugging this on my own (e.g. is there a good/plausible way for me to 'inspect' what FD1 really is in each block?)
Update: If it's relevant, I'm using go version go1.6.2 darwin/amd64.
This is C behavior you're seeing.
Go does not buffer stdout, while in C it is usually buffered. When the C library detects stdout is a tty, it may use line buffering, so the additional \n inserted by puts will cause the output to be displayed.
You need to flush stdout to ensure you get all the output:
go2c := "Printed from C.puts"
var cstr *C.char = C.CString(go2c)
defer C.free(unsafe.Pointer(cstr))
C.puts(cstr)
C.fflush(C.stdout)
fmt.Printf("Printed from golang fmt\n")
See also
Why does printf not flush after the call unless a newline is in the format string?
Is stdout line buffered, unbuffered or indeterminate by default?
The C library buffering is per line, so the first line can be left in the buffer before it is properly flushed (done at exit time in C programs). You can either try to flush stdout, or try adding a trailing \n in the first string. Does it work if you add the \n?
I did a little program which was able to parse input from command line. It worked well by means of std.in. However, when I looked up the official document for further learning, I found there was too much stuff for me.
var (
Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
)
I read the document of func NewFile, type uintpty, Package syscall individually but could not figure out the whole. Also, I did not know the meaning of /dev/stdin, either.
I never learned another static programming language except for go. How could I realize the magic of stdin?
From the syscall package, Stdin is just the number 0:
var (
Stdin = 0
Stdout = 1
Stderr = 2
)
This is simply because the posix standard is that stdin is attached to the first file descriptor, 0.
Since stdin is always present and open by default, os.NewFile can just turn this file descriptor into an os.File, and uses the standard Linux filepath "/dev/stdin" as an easily recognizable file name.
var timesFlag int
flag.IntVar(×Flag, "times", 1, "Number of times to print")
flag.Parse()
If I run the program and type in prog -times=abc (<--- not an int)
fmt.Parse spits out this ugly error message on the console:
invalid value "-abc" for flag -times: strconv.ParseInt: parsing "-abc": invalid syntax
Obviously, I can't prevent the user from typing in anything from the command line. The error looks like garbage to the user and needs to look more friendlier. How do I silent this error from going to stderr/stdout and detect there was an error generated?
The flag.CommandLine variable of type the FlagSet is used to handle command line arguments if you use the functions of the flag package which are not methods of the FlagSet type.
You can set the output (an io.Writer) where error messages are printed with the FlagSet.SetOutput() method. You can set a bytes.Buffer so messages will only end up in a buffer (and not on your console). Note that do not set nil as that means to print to the standard output (console).
And call FlagSet.Parse() yourself where you can pass os.Args[1:] as the arguments to be parsed. FlagSet.Parse() returns an error which you can handle yourself.