GPG command works in shell but not in Go exec.Command() - go

I am using gnupg to encrypt files with the following command:
gpg --encrypt --sign --armor -r person#email.com name_of_file
This command works fine in shell. But it fails in go program with following error :
gpg: cannot open '/dev/tty': Device not configured
Here is the Code:
func main() {
var stdout, stderr bytes.Buffer
cmd := exec.Command("/bin/sh", "-c", `gpg --encrypt --sign --armor -r person#email.com file_name.csv`)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
log.Println(err)
}
out := stdout.String() + stderr.String()
fmt.Println(out)
}
Why am I getting this error and how can I fix it?

Related

curl command return 404 when using os/exec

I try to get file from private gitlab repository using os/exec with curl and get 404 response status:
func Test_curl(t *testing.T) {
cmd := exec.Command(
`curl`,
`-H`, `PRIVATE-TOKEN:token`,
`https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master`,
)
t.Log(cmd.String())
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
t.Fatal(err)
}
t.Log(out.String())
}
=== RUN Test_curl
t_test.go:166: /usr/bin/curl -H PRIVATE-TOKEN:token https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master
t_test.go:175: {"error":"404 Not Found"}
--- PASS: Test_curl (0.25s)
but when I try to use the same command from zsh, I get right response:
% /usr/bin/curl -H PRIVATE-TOKEN:token https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw\?ref\=master
.DS_Store
.vs/
.vscode/
.idea/
I think the problem in the url, but don't understand how to fix one.
? and = must not be quoted:
cmd := exec.Command(
`curl`,
`-H`, `PRIVATE-TOKEN:token`,
`https://gitlab.some.com/api/v4/projects/23/repository/files/.gitignore/raw?ref=master`,
)
exec.Command does not spawn a shell, therefore shell globs do not need escaping.

golang exec with cmd as argument does not print stdout

cmdstr := "ssh -i ....... blah blah blah" ssh to an ip and run rpm command to install rpm
cmd := exec.Command("/bin/bash", "-c", cmdstr)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
fmt.Println(out.String())
}
out.String() does not print anything
if I have ping command without /bin/bash it prints the out. Anyone knows why ?
cmd.Stdout captures the output of a successful command execution
cmd.Stderr captures the command output if an error occurs during execution
You could try the cmd.Output() variant and capture execution errors from Stderr using
cmdstr := "ssh -i ....... blah blah blah" // ssh to an ip and run rpm command to install rpm
cmd := exec.Command("/bin/bash", "-c", cmdstr)
var errb bytes.Buffer
cmd.Stderr = &errb
output, err := cmd.Output()
if err != nil {
fmt.Printf("error: %s", errb.String()) // capture any error output
}
fmt.Println(string(output)) // when successful

How do I run shell command in golang

I have a shell command
set -a source /etc/environment; set +a
I want to run this command to refresh my env file
the code I tried to do
cmd, err := exec.Command("bash", "set -a source /etc/environment; set +a").Output()
fmt.Println("cmd=================>", cmd)
if err != nil {
fmt.Println(err)
}
it gave me exit status 127
try this
cmd, err := exec.Command("bash","-c", "set -a source /etc/environment; set +a").Output()
fmt.Println("cmd=================>", cmd)
if err != nil {
fmt.Println(err)
}

Array split from string is not working in bash

I have a bash script in which I am receiving response of an api in string format. The response is in the following format:
foo bar test stack over flow
Now I am having following bash script to convert it to array and process further:
#!/bin/bash
result=$(curl "API URL")
resp=($result)
for i in "${resp[#]}"
do
echo "$i"
done
Problem:
If I run this script manually in the terminal (by making it executable) it works fine. But when I try to run it by using Golang sh command
ExecuteCommand("sh /path/to/directory/test.sh")
func ExecuteCommand(command string) error{
cmd := exec.Command("sh", "-c",command)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
return err
}
fmt.Println("Result: " + out.String())
return nil
}
It gives me error:
test.sh: Syntax error: "(" unexpected
can someone help me what am I doing wrong ?
change these lines in your example
ExecuteCommand("/path/to/directory/test.sh")
func ExecuteCommand(command string) error{
cmd := exec.Command(command)
The kernel shebang will intercept the #! line and correctly run the script
U can also create a shortcut from "test.sh" file :
#!/bin/bash
$ sudo ln -s /path/to/directory/test.sh /usr/bin/testSH
If u arent root user give permission to the shortcut :
sudo chmod 777 /usr/bin/testSH
command := "testSH"
cmd := exec.Command("sh", "-c",command).Run()

is there any way run multiple command "os/exec" in one proccess in golang?

i want run multiple command in "os/exec" in one process, as you see below some command like "cd" not worked.
func main() {
cmd := exec.Command("ls")
cmdOutput := &bytes.Buffer{}
cmd.Stdout = cmdOutput
err := cmd.Run()
fmt.Print(string(cmdOutput.Bytes()))
fmt.Println(".......... cd .........")
cdOutput := &bytes.Buffer{}
cdcomand:=exec.Command("cd","model")
cdcomand.Stdout = cdOutput
err = cdcomand.Run()
fmt.Print(string(cdOutput.Bytes()))
fmt.Println(".......... ls .........")
lsOutput := &bytes.Buffer{}
lscmd:=exec.Command("ls")
lscmd.Stdout = lsOutput
err = lscmd.Run()
if err != nil {
os.Stderr.WriteString(err.Error())
}
fmt.Print(string(lsOutput.Bytes()))}
i try with another way:
package main
import (
"os/exec"
"bytes"
"os"
"fmt"
)
func main() {
cmd := exec.Command("ls")
cmdOutput := &bytes.Buffer{}
cmd.Stdout = cmdOutput
err := cmd.Run()
fmt.Print(string(cmdOutput.Bytes()))
fmt.Println(".......... cd and ls .........")
cdOutput := &bytes.Buffer{}
cdcomand:= exec.Command("sh", "-c", "ls && cd model")
cdcomand.Stdout = cdOutput
err = cdcomand.Run()
fmt.Print(string(cdOutput.Bytes()))
fmt.Println(".......... ls .........")
lsOutput := &bytes.Buffer{}
lscmd:=exec.Command("ls")
lscmd.Stdout = lsOutput
err = lscmd.Run()
if err != nil {
os.Stderr.WriteString(err.Error())
}
fmt.Print(string(lsOutput.Bytes()))
}
it did not work too.
in cmd document writes:
A Cmd cannot be reused after calling its Run, Output or CombinedOutput methods.
i've searched all tuts and docs for a way to do this, but i could not find any things. there was no solution in Executing external commands in Go article and advanced command execution in Go with os
each cmd command execute in different process so command like "cd" will not change directory . is there any way run multiple command "os/exec" in one proccess in golang?
Yes!
You could use sh -c "ls && cd model"
cmd := exec.Command("sh", "-c", "ls && cd model")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
On ubuntu
$ man sh
DASH(1) BSD General Commands Manual DASH(1)
NAME
dash — command interpreter (shell)
-c Read commands from the command_string operand instead of from the standard input. Special parameter 0 will be set from the command_name
operand and the positional parameters ($1, $2, etc.) set from the remaining argument operands.
An example using:
$ go version
go version go1.10.2 linux/amd64
// cmd/test/main.go
package main
import (
"bytes"
"os/exec"
"fmt"
)
func main() {
var stdout, stderr bytes.Buffer
cmd := exec.Command("sh", "-c", "echo 'hello' && echo 'hi'")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
fmt.Println(err)
out := stdout.String() + stderr.String()
fmt.Printf(out)
}
$ go run cmd/test/main.go
<nil>
hello
hi

Resources