在Go中生成Bash Shell

huangapple go评论82阅读模式
英文:

Spawn Bash Shell in Go

问题

我正在编写一个用于播放音乐的Go语言机器人,但是在让这个bash shell工作时遇到了一些问题。

proc := exec.Command("/bin/bash")
stdin, errIn := proc.StdinPipe()
stdout, errOut := proc.StdoutPipe()
WriteAndWait(stdin, stdout, "cd /home/user/bot1337/")
WriteAndWait(stdin, stdout, "rm song.mp3")
WriteAndWait(stdin, stdout, "youtube-dl --extract-audio --audio-format mp3 " + Sanitize(command[1]))
WriteAndWait(stdin, stdout, "mv *.mp3 song.mp3")
WriteAndWait(stdin, stdout, "xmms2 play song.mp3")
WriteAndWait(stdin, stdout, "quit")

WriteAndWait函数如下:

func WriteAndWait(stdout io.Writer, stdin io.Reader, command string) {
    stdout.Write([]byte(command + "; echo -e '\\x63\\x68\\x65\\x63\\x6b'\r\n"))
    buf := make([]byte, 256)
    for {
        fmt.Println("Reading...")
        rlen, _ := stdin.Read(buf)
        strin := string(buf[:rlen])
        fmt.Println(strin)
        if strings.Contains(strin, "check") {
            return
        }
    }
}

进程被创建了,但是程序在Read()上挂起了,它无法从stdin读取任何内容。

谢谢你的帮助!

英文:

I'm writing a bot to play music in Go, and I'm having some trouble getting this bash shell to work

proc := exec.Command("/bin/bash")
stdin, errIn := proc.StdinPipe()
stdout, errOut := proc.StdoutPipe()
WriteAndWait(stdin, stdout, "cd /home/user/bot1337/")
WriteAndWait(stdin, stdout, "rm song.mp3")
WriteAndWait(stdin, stdout, "youtube-dl --extract-audio --audio-format mp3 " + Sanitize(command[1]))
WriteAndWait(stdin, stdout, "mv *.mp3 song.mp3")
WriteAndWait(stdin, stdout, "xmms2 play song.mp3")
WriteAndWait(stdin, stdout, "quit")

The WriteAndWait function

func WriteAndWait(stdout io.Writer, stdin io.Reader, command string) {
    stdout.Write([]byte(command + "; echo -e '\\x63\\x68\\x65\\x63\\x6b'\r\n"))
    buf := make([]byte, 256)
    for {
        fmt.Println("Reading...")
        rlen, _ := stdin.Read(buf)
        strin := string(buf[:rlen])
        fmt.Println(strin)
        if strings.Contains(strin, "check") {
            return
        }
    }
}

The process gets created, but it the program hangs on Read() - it can never read anything from stdin

Thanks in advance for your help!

答案1

得分: 1

你忘记启动你的进程了。exec.Command只是创建了进程对象,但并没有启动它。

只需在管道初始化后加上proc.Start(),就可以解决问题了。

英文:

You forgot to start your process. exec.Command creates the process object, but does not start it.

Just put proc.Start() after your pipe init and it should do the trick.

huangapple
  • 本文由 发表于 2014年7月17日 04:02:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/24789608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定