golang通过HTTP服务器执行Shell命令插件库shell2http的使用
Golang通过HTTP服务器执行Shell命令插件库shell2http的使用
简介
shell2http是一个HTTP服务器,设计用于执行shell命令。它适用于开发、原型设计或远程控制,便于快速迭代和测试基于shell的功能。
只需使用两个命令行参数即可轻松设置:URL路径和shell命令。当对指定路径发起HTTP请求时,将返回shell脚本的标准输出。
安装
MacOS安装
brew install msoap/tools/shell2http
# 更新:
brew upgrade shell2http
从源码安装(需要Go 1.12或更高版本)
go install github.com/msoap/shell2http@latest
# 如果需要,设置PATH链接:
ln -s $(go env GOPATH)/bin/shell2http ~/bin/shell2http
Docker安装
docker pull msoap/shell2http
使用示例
基本用法
shell2http /top "top -l 1 | head -10"
shell2http /date date /ps "ps aux"
环境变量示例
shell2http -export-all-vars /env 'printenv | sort' /env/path 'echo $PATH' /env/gopath 'echo $GOPATH'
shell2http -export-vars=GOPATH /get 'echo $GOPATH'
HTML日历示例
shell2http /cal_html 'echo "<html><body><h1>Calendar</h1>Date: <b>$(date)</b><br><pre>$(cal $(date +%Y))</pre></body></html>"'
使用URL参数
shell2http -form /form 'echo $v_from, $v_to'
文件上传示例
shell2http -form \
GET:/form 'echo "<html><body><form method=POST action=/file enctype=multipart/form-data><input type=file name=uplfile><input type=submit></form>"' \
POST:/file 'cat $filepath_uplfile > uploaded_file.dat; echo Ok'
CGI脚本示例
shell2http -cgi /user_agent 'echo $HTTP_USER_AGENT'
shell2http -cgi /set 'touch file; echo "Location: /another_path\n"' # 重定向
shell2http -cgi /404 'echo "Status: 404"; echo; echo "404 page"' # 自定义HTTP代码
远程音量控制(Mac OS)
shell2http /get 'osascript -e "output volume of (get volume settings)"' \
/up 'osascript -e "set volume output volume (($(osascript -e "output volume of (get volume settings)")+10))"' \
/down 'osascript -e "set volume output volume (($(osascript -e "output volume of (get volume settings)")-10))"'
使用Docker运行
创建test.Dockerfile
:
FROM msoap/shell2http
# 可以安装一些alpine包:
# RUN apk add --no-cache ...
CMD ["/date", "date"]
构建并运行容器:
docker build -f test.Dockerfile -t date-server .
docker run --rm -p 8080:8080 date-server
SSL支持
运行HTTPS服务器
shell2http -cert=./cert.pem -key=./key.pem ...
生成自签名证书
go run $(go env GOROOT)/src/crypto/tls/generate_cert.go -host localhost
选项说明
shell2http支持多种选项,包括:
-host
: 指定HTTP服务器的主机IP-port
: 指定HTTP服务器的端口-form
: 解析查询参数为环境变量,处理上传的文件-cgi
: CGI模式运行脚本-export-vars
: 导出特定的环境变量-export-all-vars
: 导出所有当前环境变量-cache
: 缓存命令输出N秒-basic-auth
: 设置HTTP基本认证-timeout
: 设置执行shell命令的超时时间(秒)
完整选项列表可以通过shell2http -help
查看。
更多关于golang通过HTTP服务器执行Shell命令插件库shell2http的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang通过HTTP服务器执行Shell命令插件库shell2http的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
使用 shell2http 在 Golang 中通过 HTTP 执行 Shell 命令
shell2http 是一个轻量级的库,允许你将 shell 命令作为 HTTP 服务暴露出来。它非常适合创建简单的 API 端点来执行系统管理任务或自动化脚本。
安装 shell2http
go get github.com/msoap/shell2http
基本使用方法
下面是一个简单的示例,展示如何使用 shell2http 创建一个 HTTP 服务器,通过不同的端点执行不同的 shell 命令:
package main
import (
"log"
"net/http"
"github.com/msoap/shell2http"
)
func main() {
// 创建一个新的 shell2http 实例
handler := shell2http.NewHandler()
// 添加命令端点
handler.AddCommand("/date", "date") // 执行 date 命令
handler.AddCommand("/disk", "df -h") // 执行 df -h 命令
handler.AddCommand("/mem", "free -m") // 执行 free -m 命令
// 设置 HTTP 服务器
http.Handle("/", handler)
log.Println("Starting server on :8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
高级功能
1. 带参数的命令
handler.AddCommand("/greet", "echo Hello, ${1}!")
访问 /greet?name=John
会输出 “Hello, John!”
2. 自定义响应格式
handler.AddCommand("/custom", "echo '{\"status\":\"ok\", \"data\":\"some data\"}'")
3. 限制访问
handler.AddCommandWithAuth("/admin", "sudo some_admin_command", "admin", "secretpassword")
4. 异步执行长时间运行的命令
handler.AddAsyncCommand("/longtask", "sleep 10; echo Done")
完整示例
下面是一个更完整的示例,包含错误处理和日志记录:
package main
import (
"log"
"net/http"
"os"
"github.com/msoap/shell2http"
)
func main() {
// 创建日志文件
logFile, err := os.OpenFile("shell2http.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer logFile.Close()
// 设置日志输出
logger := log.New(logFile, "shell2http: ", log.LstdFlags)
// 创建 handler 并设置日志
handler := shell2http.NewHandler()
handler.SetLogger(logger)
// 添加命令端点
handler.AddCommand("/date", "date")
handler.AddCommand("/disk", "df -h")
handler.AddCommand("/mem", "free -m")
// 带参数的示例
handler.AddCommand("/greet", "echo Hello, ${1}!")
// 异步命令示例
handler.AddAsyncCommand("/backup", "tar -czf /tmp/backup.tar.gz /var/www")
// 安全端点
handler.AddCommandWithAuth("/admin", "sudo systemctl status", "admin", "secret123")
// 自定义 404 处理
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
handler.ServeHTTP(w, r)
})
// 启动服务器
logger.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
logger.Fatal("Server error: ", err)
}
}
安全注意事项
- 输入验证:永远不要直接将用户输入传递给 shell 命令,这可能导致命令注入漏洞
- 权限控制:确保命令以最小必要权限运行
- 认证:对敏感操作实施认证
- 日志记录:记录所有执行的命令和请求来源
替代方案
如果你需要更复杂的控制,可以考虑:
- 直接使用
os/exec
包 - 使用
gorilla/mux
等路由库构建自定义处理程序 - 对于生产环境,考虑使用更完整的框架如 Gin 或 Echo
shell2http 最适合简单的管理任务和原型开发,对于生产环境中的复杂需求,可能需要更完整的解决方案。