美文网首页
快速写一个http接口来远程执行命令

快速写一个http接口来远程执行命令

作者: 9c46ece5b7bd | 来源:发表于2018-05-18 12:46 被阅读95次

源码如下:

package main
import (
    "os/exec"
    "net/http"
    "log"
    "strings"
)


func main() {
        // /exec?cmd=xx&args=yy runs the shell command in the host
        http.HandleFunc("/exec", func(w http.ResponseWriter, r *http.Request) {
                defer func() { log.Printf("finish %v\n", r.URL) }()
                out, err := genCmd(r).CombinedOutput()
                if err != nil {
                        w.WriteHeader(500)
                        w.Write([]byte(err.Error()))
                        return
                }
                w.Write(out)
        })
        log.Fatal(http.ListenAndServe(":9999", nil))
}

func genCmd(r *http.Request) (cmd *exec.Cmd) {
        var args []string
        if got := r.FormValue("args"); got != "" {
                args = strings.Split(got, " ")
        }

        if c := r.FormValue("cmd"); len(args) == 0 {
                cmd = exec.Command(c)
        } else {
                cmd = exec.Command(c, args...)
        }
        return
}

测试程序:

$ nohup go run exec-server.go & 
$ curl "http://localhost:9999/exec?cmd=date"
Fri May 18 12:35:37 CST 2018
$ curl "http://localhost:9999/exec?cmd=echo&args="myblogs:http://xxbandy.github.io""
myblogs:http://xxbandy.github.io

查看后台服务日志:

$ cat nohup.out
2018/05/18 12:42:16 finish /exec?cmd=date
2018/05/18 12:44:00 finish /exec?cmd=echo&args=myblogs:http://xxbandy.github.io

相关文章

网友评论

      本文标题:快速写一个http接口来远程执行命令

      本文链接:https://www.haomeiwen.com/subject/oihgdftx.html