infinite loop when bash call Go program input - go

I wrote a bash script to automate download my Go program and install to my linux machine. I can via the curl to download but when my Go program prompt the user input, it go to infinite loop. The error shows EOF error.
Do anyone have any idea about it?
Install.sh
#!/bin/bash
set -e
set -o noglob
curl https://coderkk.net/ReadInput -o ReadInput
chmod a+x ReadInput
./ReadInput
ReadInput.go
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
var text string
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("Please enter you name here : ")
text, _ = reader.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
if text != "" {
break
}
}
fmt.Printf("Hi %s\n", text)
}

The problem is not related to Go - although you shouldn't ignore any potential errors from reader.ReadString - it is due to how you are invoking your downloaded script.
The pipe takes the output of curl and turns that into the stdin for sh. This is fine but your script requires stdin from the terminal - which is now lost.
Change your invocation method to something like this:
sh -c "$(curl -sfL https://coderkk.net/install.sh)"
this will pass the contents of your script to the sh interpreter but preserve the user's terminal stdin.

Related

How to directly invoke the system shell in Go (golang)?

As per the golang documentation, go does not make a call to the system's shell when you are using exec.Command().
From the golang.org documentation on the "os/exec" package:
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.
This presents a problem. Because of this design choice you cannot use piping when executing a command. Therefore the following code does not execute as desired.
package main
import (
"fmt"
"os/exec"
)
func main() {
exec.Command("echo", "Hello", ">>", "~/thing").Run()
cmdOut, _ := exec.Command("cat", "~/thing").Output()
fmt.Println(cmdOut)
}
Instead of printing out the contents of a file that should contain the word 'Hello,' it instead prints out a blank newline. I have tried directly invoking bash like this:
package main
import (
"fmt"
"os/exec"
)
func main() {
exec.Command("bash", "-c", "echo", "Hello", ">>", "~/thing").Run()
cmdOut, _ := exec.Command("cat", "~/thing").Output()
fmt.Println(cmdOut)
}
This, however, produces the same result as the original code. How can I directly invoke the system shell when using golang?
The second argument should be one string. In shell command you need to pass it as one string too. Also ~ is interpreted by bash. You can safely assume that sh exists. Bash shell is not a must.
package main
import (
"fmt"
"os/exec"
)
func main() {
exec.Command("sh", "-c", "echo Hello >> ~/thing").Run()
cmdOut, _ := exec.Command("sh", "-c", "cat ~/thing").Output()
fmt.Println(cmdOut)
}

How to provide go bin with commands

I use the following code to create command which should run according to some flags that are
passed from the cli.
I use the cobra repo
https://github.com/spf13/cobra
when I run it with go run main.go echo test
I get
Print: test
which works.
Now I run go install open the
bin directory and click on the file newApp (this my name of my app)
and it prints
Usage:
MZR [command]
Available Commands:
echo Echo anything to the screen
help Help about any command
print Print anything to the screen
Flags:
-h, --help help for MZR
Use "MZR [command] --help" for more information about a command.
[Process completed]
And I cannot use any commands (like MZR echo) which I was able when I run it locally with go run main.go echo test
But I want to use it like following MZR -h or MZR echo ,
How I can do it ?
(and also give to my friend the file from the bin that created after go install - which is Unix executable - 3.8 MB )
e.g. like this repo which use the same command line tools and to run it you use hoarder --server
https://github.com/nanopack/hoarder
This is the code for example (to make it more simpler )
package main
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
func main() {
var echoTimes int
var cmdPrint = &cobra.Command{
Use: "print [string to print]",
Short: "Print anything to the screen",
Long: `print is for printing anything back to the screen.
For many years people have printed back to the screen.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}
var cmdEcho = &cobra.Command{
Use: "echo [string to echo]",
Short: "Echo anything to the screen",
Long: `echo is for echoing anything back.
Echo works a lot like print, except it has a child command.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}
var cmdTimes = &cobra.Command{
Use: "times [# times] [string to echo]",
Short: "Echo anything to the screen more times",
Long: `echo things multiple times back to the user by providing
a count and a string.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for i := 0; i < echoTimes; i++ {
fmt.Println("Echo: " + strings.Join(args, " "))
}
},
}
cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
var rootCmd = &cobra.Command{Use: "MZR"}
rootCmd.AddCommand(cmdPrint, cmdEcho)
cmdEcho.AddCommand(cmdTimes)
rootCmd.Execute()
}
The name of the executable is taken from the directory name. Rename the directory newApp to MZR. With this change, the go install command will create a executable with the name MZR. If the executable is on your path, then you can run it from the command line using MZR -h or MZR echo,

Using Go to spawn a shell with a TTY from "nc -e /bin/bash"

I want to escape a restricted shell spawning a bash shell via Go. In other words, I want to do this but using Go:
python -c 'import pty; pty.spawn("/bin/bash")'
I am totally new to Go. I have tried this (following the answer in this question Go: How to spawn a bash shell) but nothing happens:
package main
import "os"
import "os/exec"
func main() {
shell := exec.Command("/bin/bash")
shell.Stdout = os.Stdout
shell.Stdin = os.Stdin
shell.Stderr = os.Stderr
shell.Run()
}
Also if I add the fmt.Println("hello") line at the end of the main function nothing is printed
UPDATE
Maybe I did not expalined well. What I am trying to achieve it's to spawn a shell gotten a restricted shell. This is what I did:
Listener:
nc.traditional -l -p 8080 -e /bin/bash
Connects to listener: And I exec the code here
nc.traditional localhost 8080 -v
Your program works fine for me. I put some error checking in and an extra print statement which should make what is happening clearer. You are getting an interactive shell, it just looks exactly like your previous shell.
$ go run Go/shell.go
$ # whoa another shell
$ exit
exit
exiting
$ # back again
$
Here is the revised program
package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func main() {
shell := exec.Command("/bin/bash")
shell.Stdout = os.Stdout
shell.Stdin = os.Stdin
shell.Stderr = os.Stderr
err := shell.Run()
if err != nil {
log.Fatalf("command failed: %v", err)
}
fmt.Printf("exiting\n")
}

Call source from inside a Go program

For fun and to better learn Go, I'm trying to re-implement antigen in Go.
Problem is: source is a shell built-in function, so I can't call it with os/exec Command function, because it expects an executable in PATH.
How can I do this? And, is it possible to make a source from inside a go program affect the user shell?
You can write the command directly in the terminal device. But, to do that, first you need to know which device is using the user. A script that executes your program can be a solution.
#!/bin/bash
echo Running from foo script, pid = $$
go run foo.go `tty`
Then, the program has to write the commands to the terminal device.
package main
import (
"C"
"fmt"
"os"
"syscall"
"unsafe"
)
func main() {
// Get tty path
if len(os.Args) < 2 {
fmt.Printf("no tty path\n")
os.Exit(1)
}
ttyPath := os.Args[1]
// Open tty
tty, err := os.Open(ttyPath)
if err != nil {
fmt.Printf("error opening tty: %s\n", err.Error())
os.Exit(2)
}
defer tty.Close()
// Write a command
cmd := "echo Hello from go, pid = $$\n"
cmdstr := C.CString(cmd)
cmdaddr := uintptr(unsafe.Pointer(cmdstr))
for i := range []byte(cmd) {
_, _, err := syscall.Syscall(syscall.SYS_IOCTL, tty.Fd(), syscall.TIOCSTI, cmdaddr+uintptr(i))
if uintptr(err) != 0 {
fmt.Printf("syscall error: %s\n", err.Error())
os.Exit(3)
}
}
}
Here is an example output:
$ echo $$
70318
$ ./foo
Running from foo script, pid = 83035
echo Hello from go, pid = $$
$ echo Hello from go, pid = $$
Hello from go, pid = 70318
Note that I am executing the script with ./ not source, so the PID of the script differs. But later, the command executed by the go program has the same PID.

Passing go code directly into go run without a file

Is it possible to pass a string of go code into go run instead of go run /some/path/script.go? I tried:
echo "some awesome go code here" | go run
But does not work. Thanks.
I don't think that there is such an option. At least not with the standard *g compilers or
go run.
You can try using gccgo as GCC supports reading from stdin.
Since I thought that this would be a useful thing to have, I wrote a relatively small Python script that achieves what I think you want. I called it go-script, and here are some usage examples:
# Assuming that test.go is a valid go file including package and imports
$ go-script --no-package < test.go
# Runs code from stdin, importing 'fmt' and wrapping it in a func main(){}
$ echo 'fmt.Println("test")' | go-script --import fmt --main
$ echo 'fmt.Println("test")' | go-script -ifmt -m
Help:
Usage: go-script [options]
Options:
-h, --help show this help message and exit
-i PACKAGE, --import=PACKAGE
Import package of given name
-p, --no-package Don't specify 'package main' (enabled by default)
-m, --main Wrap input in a func main() {} block
-d, --debug Print the generated Go code instead of running it.
The source (also available as a gist):
#!/usr/bin/env python
from __future__ import print_function
from optparse import OptionParser
import os
import sys
parser = OptionParser()
parser.add_option("-i", "--import", dest="imports", action="append", default=[],
help="Import package of given name", metavar="PACKAGE")
parser.add_option("-p", "--no-package", dest="package", action="store_false", default=True,
help="Don't specify 'package main' (enabled by default)")
parser.add_option("-m", "--main", dest="main", action="store_true", default=False,
help="Wrap input in a func main() {} block")
parser.add_option("-d", "--debug", dest="debug", action="store_true", default=False,
help="Print the generated Go code instead of running it.")
(options, args) = parser.parse_args()
stdin = ""
for line in sys.stdin.readlines():
stdin += "%s\n" % line
out = ""
if options.package:
out += "package main\n\n"
for package in options.imports:
out += "import \"%s\"\n" % package
out += "\n"
if options.main:
out += "func main() {\n%s\n}\n" % stdin
else:
out += stdin
if options.debug:
print(out)
else:
tmpfile = "%s%s" % (os.environ["TMPDIR"], "script.go")
f = open(tmpfile, 'w')
print(out, file=f)
f.close()
os.execlp("go", "", "run", tmpfile)
This works
cat <<EOF | tee /tmp/blah.go | go run /tmp/blah.go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
EOF
If you want to not have to open a file and edit it first. Although I wouldn't find this super practical for every day use.

Resources