源码:
package main
import "net/http"
import (
"fmt"
"os/exec"
)
func main() {
http.HandleFunc("/runcmd", handleRunCommand)
http.ListenAndServe("0.0.0.0:13399", nil)
}
func handleRunCommand(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
cmd := r.URL.Query().Get("cmd")
if cmd == "" {
http.Error(w, "Missing 'cmd' parameter", http.StatusBadRequest)
return
}
output, err := runShellCommand(cmd)
if err != nil {
http.Error(w, fmt.Sprintf("Error executing command: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, string(output))
}
func runShellCommand(command string) ([]byte, error) {
cmd := exec.Command("bash", "-c", command)
return cmd.CombinedOutput()
}
源码介绍:
首先是引入代码中需要用到的包,然后是对外暴露服务的端口号和方法名,然后就是传入cmd入参ssh操作指令执行,这里封装的是get请求。
部署运行:
1.将源码写在cmd.go的文件中,文件的名字自己定义。
2.把源码.go文件放在服务器上,通过go build cmd.go执行生成二进制文件,这里需要服务器上有go执行指令,没有需要提前安装。
3. chmod 777 cmd 给二进制文件赋予可执行权限,./cmd & 执行二进制程序。
4.http://服务器IP:端口号/方法名/cmd=执行指令 进行请求,这里封装的是get请求所以需要这样传参。