Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
872f843c6f | ||
|
|
16e6037dba | ||
|
|
52593ddd7e | ||
|
|
006138172f | ||
|
|
38e44f7b4a | ||
|
|
181150b7a1 | ||
|
|
8619afe531 | ||
|
|
9c2a57b576 |
@@ -0,0 +1,11 @@
|
||||
# common
|
||||
|
||||
通用小工具(自 remote-backend-server internal/libs/common 裁剪)。
|
||||
|
||||
## 用法
|
||||
|
||||
```go
|
||||
import "git.zeroonesoft.cn/golib/remote-core/common"
|
||||
|
||||
exists, err := common.PathExists("C:\\data") // 文件/目录是否存在
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
# file
|
||||
|
||||
被控端文件管理 HTTP 能力(自 remote-backend-server internal/handlers/file 移植,
|
||||
去 DB 依赖):目录浏览、改名、删除、上传、下载(断点支持)、目录创建。
|
||||
|
||||
## 路由
|
||||
|
||||
```go
|
||||
import "git.zeroonesoft.cn/golib/remote-core/file"
|
||||
|
||||
file.RegisterRoutersGatewayFile(r *gin.RouterGroup)
|
||||
```
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| GET/POST | `/file/list` | 目录列表(POST 收 JSON `{path}`,避免路径含 `#` 等字符被 query 截断) |
|
||||
| PUT | `/file/name` | 重命名 |
|
||||
| DELETE | `/file` | 删除文件/目录 |
|
||||
| GET/HEAD | `/file/download` | 下载(HEAD 取大小,GET 支持 Range 续传) |
|
||||
| POST | `/file/upload` | 上传 |
|
||||
| POST | `/file/dir` | 创建目录 |
|
||||
|
||||
## 注意
|
||||
|
||||
- 与 shell/process 同为被控 HTTP 能力,经 zonat 隧道 + web-gateway 反代出网。
|
||||
- 路径参数来自控制端,接入公网前务必在网关侧做鉴权与路径白名单校验。
|
||||
+164
-247
@@ -1,216 +1,149 @@
|
||||
package file
|
||||
|
||||
// 移植自 remote-backend-server internal/handlers/file(去 DB 依赖)。
|
||||
// 标准库 http.HandlerFunc 形态, 路由注册经 webhttp.Router 适配(去 gin 化)。
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jaypipes/ghw"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"git.zeroonesoft.cn/golib/remote-core/common"
|
||||
"strconv"
|
||||
|
||||
"github.com/jaypipes/ghw"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
|
||||
"git.zeroonesoft.cn/golib/remote-core/common"
|
||||
"git.zeroonesoft.cn/golib/remote-core/webhttp"
|
||||
)
|
||||
|
||||
// RegisterRoutersGatewayFile 注册路由
|
||||
func RegisterRoutersGatewayFile(r *gin.RouterGroup) {
|
||||
r.GET("/file/list", getGatewayFileList())
|
||||
r.POST("/file/list", postGatewayFileList())
|
||||
r.DELETE("/file", deleteGatewayFile())
|
||||
r.PUT("/file/name", putGatewayFileName())
|
||||
r.GET("/file/download", getGatewayFileDownload())
|
||||
r.HEAD("/file/download", headGatewayFileDownload())
|
||||
r.POST("/file/upload", postGatewayFileUpload())
|
||||
r.POST("/file/dir", postGatewayFileDir())
|
||||
// RegisterRoutersGatewayFile 注册路由。
|
||||
// 下载注册的是 GET, ServeMux 模式下 HEAD 自动兼容(响应头一致、无响应体);
|
||||
// 原 gin 独立 HEAD handler 在文件缺失时会因 fi 空指针 panic, 一并消失。
|
||||
func RegisterRoutersGatewayFile(r webhttp.Router) {
|
||||
r.GET("/file/list", getGatewayFileList)
|
||||
r.POST("/file/list", postGatewayFileList)
|
||||
r.DELETE("/file", deleteGatewayFile)
|
||||
r.PUT("/file/name", putGatewayFileName)
|
||||
r.GET("/file/download", getGatewayFileDownload)
|
||||
r.HEAD("/file/download", headGatewayFileDownload)
|
||||
r.POST("/file/upload", postGatewayFileUpload)
|
||||
r.POST("/file/dir", postGatewayFileDir)
|
||||
}
|
||||
|
||||
type PathData struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
func fail(w http.ResponseWriter, msg string) {
|
||||
webhttp.WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"code": 1,
|
||||
"msg": msg,
|
||||
"data": "OK",
|
||||
})
|
||||
}
|
||||
|
||||
func ok(w http.ResponseWriter, data any) {
|
||||
webhttp.WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"code": 0,
|
||||
"msg": "操作成功",
|
||||
"data": data,
|
||||
})
|
||||
}
|
||||
|
||||
// 传递文件路径不方便 比如 路径中包含 #
|
||||
func getGatewayFileList() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
dir := c.Query("path")
|
||||
data, err := getFileList(dir)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + err.Error(),
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"msg": "操作成功",
|
||||
"data": gin.H{
|
||||
"list": data,
|
||||
"count": len(data),
|
||||
"path": dir,
|
||||
},
|
||||
})
|
||||
func getGatewayFileList(w http.ResponseWriter, r *http.Request) {
|
||||
dir := r.URL.Query().Get("path")
|
||||
data, err := getFileList(dir)
|
||||
if err != nil {
|
||||
fail(w, "error:"+err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, map[string]any{
|
||||
"list": data,
|
||||
"count": len(data),
|
||||
"path": dir,
|
||||
})
|
||||
}
|
||||
|
||||
func deleteGatewayFile() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
path := c.Query("path")
|
||||
ok, err := common.PathExists(path)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + err.Error(),
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + "文件不存在",
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err = os.Remove(path)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + err.Error(),
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"msg": "操作成功",
|
||||
"data": nil,
|
||||
})
|
||||
func deleteGatewayFile(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Query().Get("path")
|
||||
exists, err := common.PathExists(path)
|
||||
if err != nil {
|
||||
fail(w, "error:"+err.Error())
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
fail(w, "error:文件不存在")
|
||||
return
|
||||
}
|
||||
|
||||
if err = os.Remove(path); err != nil {
|
||||
fail(w, "error:"+err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, nil)
|
||||
}
|
||||
|
||||
func putGatewayFileName() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
oldPath := c.Query("old")
|
||||
newFile := c.Query("new")
|
||||
func putGatewayFileName(w http.ResponseWriter, r *http.Request) {
|
||||
oldPath := r.URL.Query().Get("old")
|
||||
newFile := r.URL.Query().Get("new")
|
||||
|
||||
fileInfo, err := os.Stat(oldPath)
|
||||
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + "文件不存在",
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + err.Error(),
|
||||
"data": "OK",
|
||||
})
|
||||
if _, err := os.Stat(oldPath); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
fail(w, "error:文件不存在")
|
||||
return
|
||||
}
|
||||
|
||||
dir := filepath.Dir(oldPath)
|
||||
|
||||
newPath := filepath.Join(dir, newFile)
|
||||
|
||||
fmt.Println(fileInfo)
|
||||
fmt.Println(oldPath, newPath)
|
||||
|
||||
err = os.Rename(oldPath, newPath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + err.Error(),
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"msg": "操作成功",
|
||||
"data": nil,
|
||||
})
|
||||
fail(w, "error:"+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
dir := filepath.Dir(oldPath)
|
||||
newPath := filepath.Join(dir, newFile)
|
||||
|
||||
if err := os.Rename(oldPath, newPath); err != nil {
|
||||
fail(w, "error:"+err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, nil)
|
||||
}
|
||||
|
||||
func postGatewayFileDir() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
dir := c.Query("dir")
|
||||
ok, err := common.PathExists(dir)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + err.Error(),
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if ok {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + "文件不存在",
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
err = os.MkdirAll(dir, 0750)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + err.Error(),
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"msg": "操作成功",
|
||||
"data": nil,
|
||||
})
|
||||
func postGatewayFileDir(w http.ResponseWriter, r *http.Request) {
|
||||
dir := r.URL.Query().Get("dir")
|
||||
exists, err := common.PathExists(dir)
|
||||
if err != nil {
|
||||
fail(w, "error:"+err.Error())
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
fail(w, "error:文件不存在")
|
||||
return
|
||||
}
|
||||
|
||||
if err = os.MkdirAll(dir, 0750); err != nil {
|
||||
fail(w, "error:"+err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, nil)
|
||||
}
|
||||
|
||||
func postGatewayFileList() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
func postGatewayFileList(w http.ResponseWriter, r *http.Request) {
|
||||
dir := PathData{}
|
||||
// body 解析失败按空路径处理(列盘符), 与原 gin BindJSON 忽略错误的语义一致
|
||||
_ = json.NewDecoder(r.Body).Decode(&dir)
|
||||
|
||||
dir := PathData{}
|
||||
err := c.BindJSON(&dir)
|
||||
fmt.Println("dir", dir)
|
||||
|
||||
data, err := getFileList(dir.Path)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "error:" + err.Error(),
|
||||
"data": "OK",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"msg": "操作成功",
|
||||
"data": gin.H{
|
||||
"list": data,
|
||||
"count": len(data),
|
||||
"path": dir.Path,
|
||||
},
|
||||
})
|
||||
data, err := getFileList(dir.Path)
|
||||
if err != nil {
|
||||
fail(w, "error:"+err.Error())
|
||||
return
|
||||
}
|
||||
ok(w, map[string]any{
|
||||
"list": data,
|
||||
"count": len(data),
|
||||
"path": dir.Path,
|
||||
})
|
||||
}
|
||||
|
||||
type FileInfo struct {
|
||||
@@ -227,17 +160,6 @@ type FileInfo struct {
|
||||
|
||||
func getFileList(dir string) ([]FileInfo, error) {
|
||||
list := make([]FileInfo, 0)
|
||||
/*filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error {
|
||||
list = append(list, FileInfo{
|
||||
Name: info.Name(),
|
||||
Size: info.Size(),
|
||||
Mode: info.Mode().String(),
|
||||
ModTime: time.Time{},
|
||||
IsDir: info.IsDir(),
|
||||
})
|
||||
fmt.Println(info.Mode().Type())
|
||||
return nil
|
||||
})*/
|
||||
|
||||
if dir == "" {
|
||||
partitions, err := disk.Partitions(false)
|
||||
@@ -306,35 +228,25 @@ func getFileList(dir string) ([]FileInfo, error) {
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func getGatewayFileDownload() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
filePath := c.Query("filename")
|
||||
fileName := filepath.Base(filePath)
|
||||
c.Header("Content-Type", "application/octet-stream")
|
||||
c.Header("Content-Disposition", "attachment; filename="+fileName)
|
||||
c.Header("Content-Transfer-Encoding", "binary")
|
||||
fi, err := os.Stat(filePath)
|
||||
if err == nil {
|
||||
c.Header("Content-Length", strconv.FormatInt(fi.Size(), 10))
|
||||
}
|
||||
c.File(filePath)
|
||||
}
|
||||
func getGatewayFileDownload(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Query().Get("filename")
|
||||
fileName := filepath.Base(filePath)
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
|
||||
w.Header().Set("Content-Transfer-Encoding", "binary")
|
||||
http.ServeFile(w, r, filePath)
|
||||
}
|
||||
|
||||
func headGatewayFileDownload() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
filePath := c.Query("filename")
|
||||
fileName := filepath.Base(filePath)
|
||||
c.Header("Content-Type", "application/octet-stream")
|
||||
c.Header("Content-Disposition", "attachment; filename="+fileName)
|
||||
c.Header("Content-Transfer-Encoding", "binary")
|
||||
fmt.Println(filePath)
|
||||
fi, err := os.Stat(filePath)
|
||||
if err == nil {
|
||||
fmt.Println("file size is ", fi.Size(), err)
|
||||
}
|
||||
c.Header("Content-Length", strconv.FormatInt(fi.Size(), 10))
|
||||
func headGatewayFileDownload(w http.ResponseWriter, r *http.Request) {
|
||||
filePath := r.URL.Query().Get("filename")
|
||||
fileName := filepath.Base(filePath)
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
|
||||
w.Header().Set("Content-Transfer-Encoding", "binary")
|
||||
if fi, err := os.Stat(filePath); err == nil {
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
type Win32_Volume struct {
|
||||
@@ -350,49 +262,54 @@ type FileData struct {
|
||||
Md5 string `json:"md5"`
|
||||
}
|
||||
|
||||
func postGatewayFileUpload() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
dir := c.Query("dir")
|
||||
file, err := HttpUploadFile(c, dir)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 1,
|
||||
"msg": "上传失败:" + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"status": "done",
|
||||
"file": file,
|
||||
func postGatewayFileUpload(w http.ResponseWriter, r *http.Request) {
|
||||
dir := r.URL.Query().Get("dir")
|
||||
file, err := HttpUploadFile(r, dir)
|
||||
if err != nil {
|
||||
webhttp.WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"code": 1,
|
||||
"msg": "上传失败:" + err.Error(),
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
webhttp.WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"status": "done",
|
||||
"file": file,
|
||||
})
|
||||
}
|
||||
|
||||
func HttpUploadFile(c *gin.Context, saveDir string) (*FileData, error) {
|
||||
file, err := c.FormFile("file")
|
||||
// HttpUploadFile 接收 multipart 上传并落盘。
|
||||
// 不沿用 gin SaveUploadedFile 的 MkdirAll+Chmod: Windows 盘根上 Chmod 报
|
||||
// "参数不正确" 导致盘根上传必败(remote-service 已用流式接管绕开此坑, 这里
|
||||
// 是非 multipart 请求的兜底路径), 目录创建保留、Chmod 去掉。
|
||||
func HttpUploadFile(r *http.Request, saveDir string) (*FileData, error) {
|
||||
fh, head, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
fileName := file.Filename
|
||||
// 保存路径 绝对路径
|
||||
savePath := filepath.Join(saveDir, file.Filename)
|
||||
|
||||
err = c.SaveUploadedFile(file, savePath)
|
||||
if err != nil {
|
||||
savePath := filepath.Join(saveDir, head.Filename)
|
||||
if err = os.MkdirAll(filepath.Dir(savePath), 0755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fileData := &FileData{
|
||||
OriginalFileName: file.Filename,
|
||||
FileName: fileName,
|
||||
out, err := os.Create(savePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer out.Close()
|
||||
if _, err = io.Copy(out, fh); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FileData{
|
||||
OriginalFileName: head.Filename,
|
||||
FileName: head.Filename,
|
||||
FilePath: savePath,
|
||||
Size: file.Size,
|
||||
}
|
||||
|
||||
return fileData, nil
|
||||
Size: head.Size,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -3,57 +3,34 @@ module git.zeroonesoft.cn/golib/remote-core
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/KarpelesLab/vncpasswd v1.0.1
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/jaypipes/ghw v0.13.0
|
||||
github.com/kardianos/service v1.2.2
|
||||
github.com/runletapp/go-console v0.0.0-20211204140000-27323a28410a
|
||||
github.com/shirou/gopsutil/v3 v3.24.5
|
||||
github.com/sirupsen/logrus v1.10.2
|
||||
github.com/yusufpapurcu/wmi v1.2.4
|
||||
golang.org/x/sys v0.48.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/StackExchange/wmi v1.2.1 // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/creack/pty v1.1.17 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.4 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/iamacarpet/go-winpty v1.0.2 // indirect
|
||||
github.com/jaypipes/pcidb v1.0.1 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.10.0 // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/protobuf v1.36.10 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
howett.net/plist v1.0.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,43 +1,17 @@
|
||||
github.com/KarpelesLab/vncpasswd v1.0.1 h1:w0dhjSXfo59bm9/LLKhO7hV+GUGEn4WjAZTLXTNSciU=
|
||||
github.com/KarpelesLab/vncpasswd v1.0.1/go.mod h1:gh6AFDSUqRZwcdjAm/p8V81P9ePtOI65ajs7KT7D+Fc=
|
||||
github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA=
|
||||
github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8=
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI=
|
||||
github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||
github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.4 h1:9Rcod2ZPO6mOEG6b4GqyoHE/H6//Ze0RuhOo1hT1x0w=
|
||||
github.com/go-playground/validator/v10 v10.30.4/go.mod h1:numpT+RPLE91R9oYWMY/R9zRgJBewr3IXHko4OISPpk=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/iamacarpet/go-winpty v1.0.2 h1:jwPVTYrjAHZx6Mcm6K5i9G4opMp5TblEHH5EQCl/Gzw=
|
||||
@@ -47,38 +21,26 @@ github.com/jaypipes/ghw v0.13.0/go.mod h1:In8SsaDqlb1oTyrbmTC14uy+fbBMvp+xdqX51M
|
||||
github.com/jaypipes/pcidb v1.0.1 h1:WB2zh27T3nwg8AE8ei81sNRb9yWBii3JGNJtT7K9Oic=
|
||||
github.com/jaypipes/pcidb v1.0.1/go.mod h1:6xYUz/yYEyOkIkUt2t2J2folIuZ4Yg6uByCGFXMCeE4=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/kardianos/service v1.2.2 h1:ZvePhAHfvo0A7Mftk/tEzqEZ7Q4lgnR8sGz4xu1YX60=
|
||||
github.com/kardianos/service v1.2.2/go.mod h1:CIMRFEJVL+0DS1a3Nx06NaMn4Dz63Ng6O7dl0qH0zVM=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
|
||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/runletapp/go-console v0.0.0-20211204140000-27323a28410a h1:1hh8CSomjZSJPk7AgHV8o33Su13bZby81PrC6pIvJqQ=
|
||||
@@ -92,51 +54,25 @@ github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnj
|
||||
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
|
||||
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# process
|
||||
|
||||
远程进程管理(被控 HTTP 能力):进程列表 / 结束进程。gopsutil 跨平台实现,
|
||||
与 file/shell 同为被控 HTTP 能力——BS 与客户机被控端共用,经 zonat 隧道 +
|
||||
web-gateway 反代出网(typ=process,页面 www/process.html)。
|
||||
|
||||
## 路由
|
||||
|
||||
```go
|
||||
import "git.zeroonesoft.cn/golib/remote-core/process"
|
||||
|
||||
process.RegisterRoutersProcess(r *gin.RouterGroup)
|
||||
```
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| GET | `/process/list` | 全量进程列表(`ProcItem`:pid/名称/用户/CPU/内存/启动时间/可执行路径/命令行),按内存占用降序 |
|
||||
| POST | `/process/kill` | 结束进程,入参 `{pid, name?}` |
|
||||
|
||||
## 注意
|
||||
|
||||
- `kill` 带 `name` 时做防误杀校验:实际进程名与传入不符则拒绝(防 pid 复用)。
|
||||
- Windows 上 gopsutil 权限不足时自动回退 `taskkill /F /T`(连子进程树强杀)。
|
||||
+79
-77
@@ -5,14 +5,16 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shirou/gopsutil/v3/process"
|
||||
|
||||
"git.zeroonesoft.cn/golib/remote-core/webhttp"
|
||||
)
|
||||
|
||||
// ProcItem 进程列表行。
|
||||
@@ -30,89 +32,89 @@ type ProcItem struct {
|
||||
}
|
||||
|
||||
// RegisterRoutersProcess 装配进程管理路由: GET /process/list, POST /process/kill。
|
||||
func RegisterRoutersProcess(r *gin.RouterGroup) {
|
||||
r.GET("/process/list", listProcesses())
|
||||
r.POST("/process/kill", killProcess())
|
||||
func RegisterRoutersProcess(r webhttp.Router) {
|
||||
r.GET("/process/list", listProcesses)
|
||||
r.POST("/process/kill", killProcess)
|
||||
}
|
||||
|
||||
func fail(w http.ResponseWriter, msg string) {
|
||||
webhttp.WriteJSON(w, http.StatusOK, map[string]any{"code": 1, "msg": msg, "data": nil})
|
||||
}
|
||||
|
||||
// listProcesses 全量进程列表(按内存占用降序)。
|
||||
func listProcesses() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
procs, err := process.Processes()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "枚举进程失败: " + err.Error(), "data": nil})
|
||||
return
|
||||
}
|
||||
items := make([]ProcItem, 0, len(procs))
|
||||
for _, p := range procs {
|
||||
item := ProcItem{Pid: p.Pid}
|
||||
if name, e := p.Name(); e == nil {
|
||||
item.Name = name
|
||||
}
|
||||
if st, e := p.Status(); e == nil && len(st) > 0 {
|
||||
item.Status = st[0]
|
||||
}
|
||||
if u, e := p.Username(); e == nil {
|
||||
item.User = u
|
||||
}
|
||||
if cpu, e := p.CPUPercent(); e == nil {
|
||||
item.CPUPercent = cpu
|
||||
}
|
||||
if mem, e := p.MemoryInfo(); e == nil {
|
||||
item.MemRSS = mem.RSS
|
||||
}
|
||||
if mp, e := p.MemoryPercent(); e == nil {
|
||||
item.MemPercent = mp
|
||||
}
|
||||
if ct, e := p.CreateTime(); e == nil {
|
||||
item.CreateTime = ct
|
||||
}
|
||||
if exe, e := p.Exe(); e == nil {
|
||||
item.Exe = exe
|
||||
}
|
||||
if cmd, e := p.Cmdline(); e == nil {
|
||||
item.Cmdline = cmd
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].MemPercent > items[j].MemPercent })
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "OK", "data": gin.H{"list": items}})
|
||||
func listProcesses(w http.ResponseWriter, _ *http.Request) {
|
||||
procs, err := process.Processes()
|
||||
if err != nil {
|
||||
fail(w, "枚举进程失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
items := make([]ProcItem, 0, len(procs))
|
||||
for _, p := range procs {
|
||||
item := ProcItem{Pid: p.Pid}
|
||||
if name, e := p.Name(); e == nil {
|
||||
item.Name = name
|
||||
}
|
||||
if st, e := p.Status(); e == nil && len(st) > 0 {
|
||||
item.Status = st[0]
|
||||
}
|
||||
if u, e := p.Username(); e == nil {
|
||||
item.User = u
|
||||
}
|
||||
if cpu, e := p.CPUPercent(); e == nil {
|
||||
item.CPUPercent = cpu
|
||||
}
|
||||
if mem, e := p.MemoryInfo(); e == nil {
|
||||
item.MemRSS = mem.RSS
|
||||
}
|
||||
if mp, e := p.MemoryPercent(); e == nil {
|
||||
item.MemPercent = mp
|
||||
}
|
||||
if ct, e := p.CreateTime(); e == nil {
|
||||
item.CreateTime = ct
|
||||
}
|
||||
if exe, e := p.Exe(); e == nil {
|
||||
item.Exe = exe
|
||||
}
|
||||
if cmd, e := p.Cmdline(); e == nil {
|
||||
item.Cmdline = cmd
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].MemPercent > items[j].MemPercent })
|
||||
webhttp.WriteJSON(w, http.StatusOK, map[string]any{"code": 0, "msg": "OK", "data": map[string]any{"list": items}})
|
||||
}
|
||||
|
||||
// killProcess 结束进程: {pid: 必填, name: 可选校验(防 pid 复用误杀)}。
|
||||
// Windows 上 gopsutil 权限不足时回退 taskkill /F /T(连子进程树强杀)。
|
||||
func killProcess() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req struct {
|
||||
Pid int32 `json:"pid"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.Pid <= 0 {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误: pid 必填且为正整数", "data": nil})
|
||||
return
|
||||
}
|
||||
p, err := process.NewProcess(req.Pid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "进程不存在: " + err.Error(), "data": nil})
|
||||
return
|
||||
}
|
||||
if req.Name != "" {
|
||||
if name, e := p.Name(); e == nil && name != "" && name != req.Name {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "进程名不匹配(实际 " + name + "), 已拒绝结束", "data": nil})
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := p.Kill(); err != nil {
|
||||
if runtime.GOOS != "windows" {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "结束进程失败: " + err.Error(), "data": nil})
|
||||
return
|
||||
}
|
||||
if out, e := exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(int(req.Pid))).CombinedOutput(); e != nil {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "结束进程失败: " + err.Error() + "; taskkill: " + string(out), "data": nil})
|
||||
return
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "OK", "data": gin.H{"pid": req.Pid}})
|
||||
func killProcess(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Pid int32 `json:"pid"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Pid <= 0 {
|
||||
fail(w, "参数错误: pid 必填且为正整数")
|
||||
return
|
||||
}
|
||||
p, err := process.NewProcess(req.Pid)
|
||||
if err != nil {
|
||||
fail(w, "进程不存在: "+err.Error())
|
||||
return
|
||||
}
|
||||
if req.Name != "" {
|
||||
if name, e := p.Name(); e == nil && name != "" && name != req.Name {
|
||||
fail(w, "进程名不匹配(实际 "+name+"), 已拒绝结束")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := p.Kill(); err != nil {
|
||||
if runtime.GOOS != "windows" {
|
||||
fail(w, "结束进程失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
if out, e := exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(int(req.Pid))).CombinedOutput(); e != nil {
|
||||
fail(w, "结束进程失败: "+err.Error()+"; taskkill: "+string(out))
|
||||
return
|
||||
}
|
||||
}
|
||||
webhttp.WriteJSON(w, http.StatusOK, map[string]any{"code": 0, "msg": "OK", "data": map[string]any{"pid": req.Pid}})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# remote
|
||||
|
||||
远程控制服务管理(被控端能力):RDP / VNC(TightVNC) / Radmin 的服务状态查询、
|
||||
启停与重置,VNC 服务端安装/配置读写,VNC 密码加解密,远程信息汇总。
|
||||
|
||||
> 自 go-hua/remote 平移并入(包名保持 `remote`),与本库 file/shell/process
|
||||
> 同属被控端远程运维能力。
|
||||
|
||||
## 用法
|
||||
|
||||
```go
|
||||
import "git.zeroonesoft.cn/golib/remote-core/remote"
|
||||
|
||||
// 汇总信息(主机名/IP/MAC/远程端口/VNC 密码等)
|
||||
info := remote.GetRemoteInfo()
|
||||
|
||||
// 远程服务状态与控制
|
||||
_ = remote.GetRdpServiceStatus() // kardianos/service Status
|
||||
_ = remote.GetVncServiceStatus() // 同上
|
||||
_ = remote.GetRadminServiceStatus() // (int, error):1 运行 / 0 停止 / -1 未安装
|
||||
_ = remote.GetServiceStatus("SessionEnv") // 通用按服务名查询
|
||||
err := remote.ServiceStart(name) // 启动 / ServiceStop 停止
|
||||
_ = remote.GetServiceReset(name) // 重置类服务状态
|
||||
|
||||
// RDP / VNC 端口与 VNC 密码读取
|
||||
port, err := remote.GetRdpPort()
|
||||
vncPort, err := remote.GetVncPort()
|
||||
pass, err := remote.GetVncPassword()
|
||||
|
||||
// VNC(TightVNC) 服务端管理(Windows)
|
||||
cfg := remote.VncServerDefaultConfig(true /* 随机密码 */) // VncServerConfig
|
||||
err = remote.WriteVncServerConfig(cfg)
|
||||
cfg, err = remote.ReadVncServerConfig()
|
||||
// 绿色安装最新版 TightVNC:校验 exe → 写注册表全集(随机密码, 需管理员权限) →
|
||||
// 注册系统服务(装而不启, 远程时再 VncStart; 已运行则重启加载新配置)。
|
||||
// 返回生成的明文密码供调用方上报/展示。
|
||||
pass, err := remote.InstallVncServer(`D:\app\tvnc\tvnserver.exe`)
|
||||
err = remote.VncInit() // 初始化/修复配置
|
||||
err = remote.VncStart() // VncStop / VncRestart
|
||||
err = remote.VncInstall() // VncUninstall
|
||||
err = remote.RunVncService() // 以服务方式运行
|
||||
|
||||
// VNC 密码加解密(TightVNC 注册表存储格式)
|
||||
enc := remote.VncPasswordCrypt("plainpass") // []byte
|
||||
plain := remote.VncPasswordDecrypt(enc) // string
|
||||
|
||||
// CAD/SAS 相关注册表开关(Windows)
|
||||
err = remote.EnableSoftwareSASGeneration()
|
||||
```
|
||||
|
||||
## 平台支持
|
||||
|
||||
- `remote.go` / `type.go`:跨平台(依赖 `kardianos/service`)。
|
||||
- `windows.go` / `vnc.go`:`//go:build windows`(注册表、TightVNC 配置)。
|
||||
- `unix.go`:`//go:build linux`(精简实现)。
|
||||
|
||||
## 注意
|
||||
|
||||
- `GetServiceStatus` 系列对未安装服务返回 -1 而非错误;`GetRdpServiceStatus` /
|
||||
`GetVncServiceStatus` 走 `kardianos/service`,未安装返回 error。
|
||||
- `InstallVncServer` / `VncInit` / CAD 开关需要管理员权限,失败信息见返回 error;安装配置对齐最新版 TightVNC(2.8.x) 注册表 37 项全集。
|
||||
- VNC 密码格式与 TightVNC 兼容(`KarpelesLab/vncpasswd` 实现),加解密为确定性
|
||||
变换,注意密文落盘位置的访问控制。
|
||||
@@ -0,0 +1,191 @@
|
||||
package remote
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kardianos/service"
|
||||
"net"
|
||||
)
|
||||
|
||||
// Info 远程控制信息汇总(主机、IP、MAC 与 RDP/VNC 状态端口)
|
||||
type Info struct {
|
||||
Hostname string `json:"hostname"`
|
||||
IpAddr []string `json:"ipAddr"`
|
||||
MacAddr []string `json:"macAddr"`
|
||||
RdpState int `json:"rdpState"`
|
||||
RdpPort int `json:"rdpPort"`
|
||||
VncState int `json:"vncState"`
|
||||
VncPort int `json:"vncPort"`
|
||||
VncPassword string `json:"vncPassword"`
|
||||
}
|
||||
|
||||
// GetRadminServiceStatus 获取服务状态 0.无效 1.运行 2.停止
|
||||
func GetRadminServiceStatus() (int, error) {
|
||||
svcConfig := &service.Config{
|
||||
Name: "RServer3",
|
||||
}
|
||||
s, err := service.New(nil, svcConfig)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var status service.Status
|
||||
status, err = s.Status()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(status), nil
|
||||
}
|
||||
|
||||
// GetVncServiceStatus 获取服务状态 0.无效 1.运行 2.停止
|
||||
func GetVncServiceStatus() (service.Status, error) {
|
||||
svcConfig := &service.Config{
|
||||
Name: "tvnserver",
|
||||
}
|
||||
s, err := service.New(nil, svcConfig)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var status service.Status
|
||||
status, err = s.Status()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
// GetRdpServiceStatus 获取服务状态 0.无效 1.运行 2.停止
|
||||
func GetRdpServiceStatus() (service.Status, error) {
|
||||
svcConfig := &service.Config{
|
||||
Name: "TermService",
|
||||
}
|
||||
s, err := service.New(nil, svcConfig)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var status service.Status
|
||||
status, err = s.Status()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
// getMacAddrs 获取本机所有非空 MAC 地址
|
||||
func getMacAddrs() (macAddrs []string) {
|
||||
netInterfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
fmt.Printf("fail to get net interfaces: %v", err)
|
||||
return macAddrs
|
||||
}
|
||||
|
||||
for _, netInterface := range netInterfaces {
|
||||
macAddr := netInterface.HardwareAddr.String()
|
||||
if len(macAddr) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
macAddrs = append(macAddrs, macAddr)
|
||||
}
|
||||
return macAddrs
|
||||
}
|
||||
|
||||
// getIPs 获取本机所有 IPv4 地址(不含回环)
|
||||
func getIPs() (ips []string) {
|
||||
|
||||
interfaceAddr, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
fmt.Printf("fail to get net interface addrs: %v", err)
|
||||
return ips
|
||||
}
|
||||
|
||||
for _, address := range interfaceAddr {
|
||||
ipNet, isValidIpNet := address.(*net.IPNet)
|
||||
if isValidIpNet && !ipNet.IP.IsLoopback() {
|
||||
if ipNet.IP.To4() != nil {
|
||||
ips = append(ips, ipNet.IP.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
// GetServiceStatus 获取服务状态 0.无效 1.运行 2.停止
|
||||
func GetServiceStatus(name string) (int, error) {
|
||||
svcConfig := &service.Config{
|
||||
Name: name,
|
||||
}
|
||||
s, err := service.New(nil, svcConfig)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var status service.Status
|
||||
status, err = s.Status()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(status), nil
|
||||
}
|
||||
|
||||
// ServiceStart 启动服务
|
||||
func ServiceStart(name string) error {
|
||||
svcConfig := &service.Config{
|
||||
Name: name,
|
||||
}
|
||||
s, err := service.New(nil, svcConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ServiceStop 停止服务
|
||||
func ServiceStop(name string) (i error) {
|
||||
svcConfig := &service.Config{
|
||||
Name: name,
|
||||
}
|
||||
s, err := service.New(nil, svcConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.Stop()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetServiceReset 重启服务
|
||||
func GetServiceReset(name string) (int, error) {
|
||||
svcConfig := &service.Config{
|
||||
Name: name,
|
||||
}
|
||||
s, err := service.New(nil, svcConfig)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var status service.Status
|
||||
status, err = s.Status()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(status), nil
|
||||
}
|
||||
|
||||
// RunVncService 启动 TightVNC 服务
|
||||
func RunVncService() error {
|
||||
svcConfig := &service.Config{
|
||||
Name: "tvnserver",
|
||||
}
|
||||
s, err := service.New(nil, svcConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//go:build windows
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetServiceStatusNonExist(t *testing.T) {
|
||||
// 不存在的服务应返回错误(Radmin 服务普通机器上不会安装)
|
||||
_, err := GetRadminServiceStatus()
|
||||
if err == nil {
|
||||
t.Log("本机安装了 Radmin 服务,跳过该断言")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRemoteInfo(t *testing.T) {
|
||||
info := GetRemoteInfo()
|
||||
if info.Hostname == "" {
|
||||
t.Error("Hostname 不应为空")
|
||||
}
|
||||
if len(info.IpAddr) == 0 {
|
||||
t.Log("本机无 IPv4 地址(CI 环境可能出现)")
|
||||
}
|
||||
// 只读查询,不应 panic
|
||||
_ = info.RdpState
|
||||
_ = info.VncState
|
||||
}
|
||||
|
||||
func TestVncPasswordCryptDecrypt(t *testing.T) {
|
||||
password := "tvncpass"
|
||||
encrypted := VncPasswordCrypt(password)
|
||||
if len(encrypted) == 0 {
|
||||
t.Fatal("加密结果不应为空")
|
||||
}
|
||||
if string(encrypted) == password {
|
||||
t.Error("加密结果不应等于明文")
|
||||
}
|
||||
decrypted := VncPasswordDecrypt(encrypted)
|
||||
if decrypted != password {
|
||||
t.Errorf("解密 = %q, want %q", decrypted, password)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVncServerDefaultConfig(t *testing.T) {
|
||||
cfg := VncServerDefaultConfig(false)
|
||||
if cfg.RfbPort == 0 {
|
||||
t.Error("RfbPort 不应为 0")
|
||||
}
|
||||
if cfg.HttpPort == 0 {
|
||||
t.Error("HttpPort 不应为 0")
|
||||
}
|
||||
}
|
||||
|
||||
// TestVncClientDefaultConfigLatest 锁定对最新版 TightVNC(2.8.x) 注册表全集的支持:
|
||||
// 值与本机最新版安装器落盘值逐项对齐(AcceptHttpConnections/RunControlInterface
|
||||
// 为安全策略有意取 0:不开 5800 Web 通道、不显托盘)。
|
||||
func TestVncClientDefaultConfigLatest(t *testing.T) {
|
||||
cfg := VncClientDefaultConfig(false)
|
||||
if cfg.RfbPort != 5900 || cfg.HttpPort != 5800 {
|
||||
t.Errorf("端口 = %d/%d, want 5900/5800", cfg.RfbPort, cfg.HttpPort)
|
||||
}
|
||||
// 最新版捕获能力:镜像驱动 + D3D + 透明窗口 + 视频区域识别
|
||||
if cfg.UseMirrorDriver != 1 || cfg.UseD3D != 1 {
|
||||
t.Errorf("捕获开关 = mirror:%d d3d:%d, want 1/1", cfg.UseMirrorDriver, cfg.UseD3D)
|
||||
}
|
||||
if cfg.GrabTransparentWindows != 1 || cfg.VideoRecognitionInterval != 3000 {
|
||||
t.Errorf("透明窗口/视频识别 = %d/%d, want 1/3000", cfg.GrabTransparentWindows, cfg.VideoRecognitionInterval)
|
||||
}
|
||||
// 安全策略:不开 HTTP 通道、不出托盘控制台、不接 RDP 会话
|
||||
if cfg.AcceptHttpConnections != 0 || cfg.RunControlInterface != 0 || cfg.ConnectToRdp != 0 {
|
||||
t.Errorf("安全策略 = http:%d tray:%d rdp:%d, want 0/0/0", cfg.AcceptHttpConnections, cfg.RunControlInterface, cfg.ConnectToRdp)
|
||||
}
|
||||
// 连接行为:VNC 认证 + 接受 RFB + 本机输入优先 + 断开踢旧连接
|
||||
if cfg.AcceptRfbConnections != 1 || cfg.UseVncAuthentication != 1 || cfg.LocalInputPriority != 1 || cfg.DisconnectClients != 1 {
|
||||
t.Errorf("连接行为异常: %+v", cfg)
|
||||
}
|
||||
if cfg.QueryTimeout != 30 || cfg.LocalInputPriorityTimeout != 3 || cfg.PollingInterval != 1000 || cfg.AllowLoopback != 1 {
|
||||
t.Errorf("超时/轮询/环回异常: %+v", cfg)
|
||||
}
|
||||
if len(cfg.Password) == 0 {
|
||||
t.Error("固定密码密文不应为空")
|
||||
}
|
||||
if dec := VncPasswordDecrypt(cfg.Password); dec != "tvncpass" {
|
||||
t.Errorf("固定密码回解 = %q, want tvncpass", dec)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInstallVncServerMissingExe 安装入口对 tvnserver.exe 缺失必须报错(不触注册表/服务)
|
||||
func TestInstallVncServerMissingExe(t *testing.T) {
|
||||
_, err := InstallVncServer(`Z:\no\such\dir\tvnserver.exe`)
|
||||
if err == nil {
|
||||
t.Fatal("exe 不存在时应返回错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestVncServerConfigFieldCount 锁定配置字段总数:必须与本机最新版 TightVNC(2.8.x)
|
||||
// 注册表 SOFTWARE\TightVNC\Server 下的 37 个值一一对应。加/删字段前先核对注册表全集,
|
||||
// 并同步检查 ReadVncServerConfig / WriteVncServerConfig 的逐项覆盖(此前曾漏 LogLevel 写、
|
||||
// ConnectToRdp 误读、LogLevel 漏读, 靠本测试与脚本对账拦截)。
|
||||
func TestVncServerConfigFieldCount(t *testing.T) {
|
||||
if got := reflect.TypeOf(VncServerConfig{}).NumField(); got != 37 {
|
||||
t.Errorf("VncServerConfig 字段数 = %d, want 37(最新版注册表全集)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVncPasswordDecryptShortInput 短于 8 字节的密文(缺失/截断)必须返回空串而非 panic
|
||||
func TestVncPasswordDecryptShortInput(t *testing.T) {
|
||||
for _, data := range [][]byte{nil, {}, []byte("abc"), []byte("1234567")} {
|
||||
if got := VncPasswordDecrypt(data); got != "" {
|
||||
t.Errorf("VncPasswordDecrypt(len=%d) = %q, want 空串且不 panic", len(data), got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Package remote 提供 RDP/VNC 等远程控制的服务状态查询、配置读写与启停控制。
|
||||
package remote
|
||||
|
||||
// VncServerConfig TightVNC 服务端配置(对应注册表 SOFTWARE\TightVNC\Server 下的键值)。
|
||||
// 37 项 = 最新版 TightVNC(2.8.x) 标准安装落盘的全集(经本机注册表与 tvnserver.exe
|
||||
// 字符串表双重核对)。另有 ViewOnlyPassword / ControlPassword 两个条件值(只读密码、
|
||||
// 控制接口管理密码,开对应功能才会写入,本库暂不覆盖——WriteVncServerConfig 是
|
||||
// 无条件全量写,加字段会向每台客户机落空值),待产品启用只读接入/控制认证时再扩展。
|
||||
type VncServerConfig struct {
|
||||
ExtraPorts string `json:"extraPorts"` // 额外端口
|
||||
QueryTimeout uint32 `json:"queryTimeout"` // 查询超时
|
||||
QueryAcceptOnTimeout uint32 `json:"queryAcceptOnTimeout"` // 查询接受超时
|
||||
LocalInputPriorityTimeout uint32 `json:"localInputPriorityTimeout"` // 本地输入优先级超时
|
||||
LocalInputPriority uint32 `json:"localInputPriority"` // 本地输入优先
|
||||
BlockRemoteInput uint32 `json:"blockRemoteInput"` // 阻止远程输入
|
||||
BlockLocalInput uint32 `json:"blockLocalInput"` // 阻止本地输入
|
||||
IpAccessControl string `json:"ipAccessControl"` // IP访问控制
|
||||
RfbPort uint32 `json:"rfbPort"` // 主端口
|
||||
HttpPort uint32 `json:"httpPort"` // WEB端口
|
||||
DisconnectAction uint32 `json:"disconnectAction"` // 断开动作
|
||||
AcceptRfbConnections uint32 `json:"acceptRfbConnections"` // 接受RFB连接
|
||||
UseVncAuthentication uint32 `json:"useVncAuthentication"` // 使用VNC认证
|
||||
UseControlAuthentication uint32 `json:"useControlAuthentication"` // 使用控制认证
|
||||
RepeatControlAuthentication uint32 `json:"repeatControlAuthentication"` // 重复控制认证
|
||||
LoopbackOnly uint32 `json:"loopbackOnly"` // 只允许环回
|
||||
AcceptHttpConnections uint32 `json:"acceptHttpConnections"` // HTTP请求连接
|
||||
LogLevel uint32 `json:"logLevel"` // 日志等级
|
||||
EnableFileTransfers uint32 `json:"enableFileTransfers"` // 使文件传输
|
||||
RemoveWallpaper uint32 `json:"removeWallpaper"` // 移除墙纸
|
||||
UseD3D uint32 `json:"useD3D"` // 使用D3D驱动
|
||||
UseMirrorDriver uint32 `json:"useMirrorDriver"` // 使用镜像驱动
|
||||
EnableUrlParams uint32 `json:"enableUrlParams"` // 用URL参数
|
||||
Password []byte `json:"password"` // 密码(需要加密)
|
||||
AlwaysShared uint32 `json:"alwaysShared"` // 总是共享
|
||||
NeverShared uint32 `json:"neverShared"` // 从不共享
|
||||
DisconnectClients uint32 `json:"disconnectClients"` // 断开客户端后操作
|
||||
PollingInterval uint32 `json:"pollingInterval"` // 轮询间隔
|
||||
AllowLoopback uint32 `json:"allowLoopback"` // 允许环回
|
||||
VideoRecognitionInterval uint32 `json:"videoRecognitionInterval"` // 视频轮询间隔
|
||||
GrabTransparentWindows uint32 `json:"grabTransparentWindows"` // 抓取透明窗口
|
||||
SaveLogToAllUsersPath uint32 `json:"saveLogToAllUsersPath"` // 保存日志所有用户路径
|
||||
RunControlInterface uint32 `json:"runControlInterface"` // 运行控制台接口
|
||||
IdleTimeout uint32 `json:"idleTimeout"` // 空闲超时
|
||||
VideoClasses string `json:"videoClasses"` // 视频窗口类名
|
||||
VideoRects string `json:"videoRects"` // 视频窗口区域
|
||||
ConnectToRdp uint32 `json:"connectToRdp"` // 连接到RDP会话
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//go:build linux
|
||||
|
||||
package remote
|
||||
|
||||
import "os"
|
||||
|
||||
// GetRemoteInfo 获取远程控制相关信息(Linux 平台仅主机名/IP/MAC)
|
||||
func GetRemoteInfo() Info {
|
||||
info := Info{}
|
||||
|
||||
/*var status int
|
||||
status, _ = GetRadminServiceStatus()
|
||||
info.RadminState = status
|
||||
|
||||
status, _ = GetVncServiceStatus()
|
||||
info.VncState = status
|
||||
|
||||
status, _ = GetRdpServiceStatus()
|
||||
info.RdpState = status*/
|
||||
|
||||
/* var port int
|
||||
port, _ = GetRadminPort()
|
||||
info.RadminPort = port
|
||||
|
||||
port, _ = GetRdpPort()
|
||||
info.RdpPort = port
|
||||
|
||||
port, _ = GetVncPort()
|
||||
info.VncPort = port*/
|
||||
|
||||
hostname, _ := os.Hostname()
|
||||
info.Hostname = hostname
|
||||
info.IpAddr = getIPs()
|
||||
info.MacAddr = getMacAddrs()
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
// VncServerDefaultConfig 生成 TightVNC 服务端默认配置(Linux 未实现,返回空配置)
|
||||
func VncServerDefaultConfig(randPass bool) VncServerConfig {
|
||||
config := VncServerConfig{}
|
||||
return config
|
||||
}
|
||||
|
||||
// VncClientDefaultConfig 生成 TightVNC 客户端默认配置(Linux 未实现,返回空配置)
|
||||
func VncClientDefaultConfig(randPass bool) VncServerConfig {
|
||||
config := VncServerConfig{}
|
||||
return config
|
||||
}
|
||||
|
||||
// WriteVncServerConfig 写入 TightVNC 服务端配置(Linux 未实现,直接返回 nil)
|
||||
func WriteVncServerConfig(config VncServerConfig) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnableSoftwareSASGeneration 启用软件SAS模拟输入
|
||||
func EnableSoftwareSASGeneration() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnableWinlogonDisableCAD 关闭 Ctrl + Alt + Del 组合键来登录
|
||||
func EnableWinlogonDisableCAD() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnableSystemDisableCAD 关闭 Ctrl + Alt + Del 组合键来登录
|
||||
func EnableSystemDisableCAD() error {
|
||||
return nil
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
//go:build windows
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/KarpelesLab/vncpasswd"
|
||||
"github.com/kardianos/service"
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
var VncService service.Service
|
||||
|
||||
// ReadVncServerConfig 从注册表读取 TightVNC 服务端配置(键值缺失按零值返回)
|
||||
func ReadVncServerConfig() (VncServerConfig, error) {
|
||||
var config VncServerConfig
|
||||
|
||||
key, err := registry.OpenKey(registry.LOCAL_MACHINE, "SOFTWARE\\TightVNC\\Server", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
defer key.Close()
|
||||
|
||||
config.ExtraPorts, _, _ = key.GetStringValue("ExtraPorts")
|
||||
config.QueryTimeout, _, _ = GetDwordValue(key, "QueryTimeout")
|
||||
config.QueryAcceptOnTimeout, _, _ = GetDwordValue(key, "QueryAcceptOnTimeout")
|
||||
config.LocalInputPriorityTimeout, _, _ = GetDwordValue(key, "LocalInputPriorityTimeout")
|
||||
config.LocalInputPriority, _, _ = GetDwordValue(key, "LocalInputPriority")
|
||||
config.BlockRemoteInput, _, _ = GetDwordValue(key, "BlockRemoteInput")
|
||||
config.BlockLocalInput, _, _ = GetDwordValue(key, "BlockLocalInput")
|
||||
config.IpAccessControl, _, _ = key.GetStringValue("IpAccessControl")
|
||||
config.RfbPort, _, _ = GetDwordValue(key, "RfbPort")
|
||||
config.HttpPort, _, _ = GetDwordValue(key, "HttpPort")
|
||||
config.DisconnectAction, _, _ = GetDwordValue(key, "DisconnectAction")
|
||||
config.AcceptRfbConnections, _, _ = GetDwordValue(key, "AcceptRfbConnections")
|
||||
config.UseVncAuthentication, _, _ = GetDwordValue(key, "UseVncAuthentication")
|
||||
config.UseControlAuthentication, _, _ = GetDwordValue(key, "UseControlAuthentication")
|
||||
config.RepeatControlAuthentication, _, _ = GetDwordValue(key, "RepeatControlAuthentication")
|
||||
config.LoopbackOnly, _, _ = GetDwordValue(key, "LoopbackOnly")
|
||||
config.AcceptHttpConnections, _, _ = GetDwordValue(key, "AcceptHttpConnections")
|
||||
config.LogLevel, _, _ = GetDwordValue(key, "LogLevel")
|
||||
config.EnableFileTransfers, _, _ = GetDwordValue(key, "EnableFileTransfers")
|
||||
config.RemoveWallpaper, _, _ = GetDwordValue(key, "RemoveWallpaper")
|
||||
config.UseD3D, _, _ = GetDwordValue(key, "UseD3D")
|
||||
config.UseMirrorDriver, _, _ = GetDwordValue(key, "UseMirrorDriver")
|
||||
config.EnableUrlParams, _, _ = GetDwordValue(key, "EnableUrlParams")
|
||||
config.Password, _, _ = key.GetBinaryValue("Password")
|
||||
config.AlwaysShared, _, _ = GetDwordValue(key, "AlwaysShared")
|
||||
config.NeverShared, _, _ = GetDwordValue(key, "NeverShared")
|
||||
config.DisconnectClients, _, _ = GetDwordValue(key, "DisconnectClients")
|
||||
config.PollingInterval, _, _ = GetDwordValue(key, "PollingInterval")
|
||||
config.AllowLoopback, _, _ = GetDwordValue(key, "AllowLoopback")
|
||||
config.VideoRecognitionInterval, _, _ = GetDwordValue(key, "VideoRecognitionInterval")
|
||||
config.GrabTransparentWindows, _, _ = GetDwordValue(key, "GrabTransparentWindows")
|
||||
config.SaveLogToAllUsersPath, _, _ = GetDwordValue(key, "SaveLogToAllUsersPath")
|
||||
config.RunControlInterface, _, _ = GetDwordValue(key, "RunControlInterface")
|
||||
config.IdleTimeout, _, _ = GetDwordValue(key, "IdleTimeout")
|
||||
config.VideoClasses, _, _ = key.GetStringValue("VideoClasses")
|
||||
config.VideoRects, _, _ = key.GetStringValue("VideoRects")
|
||||
config.ConnectToRdp, _, _ = GetDwordValue(key, "ConnectToRdp")
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// GetDwordValue 读取 REG_DWORD 类型注册表值
|
||||
func GetDwordValue(k registry.Key, name string) (val uint32, valtype uint32, err error) {
|
||||
val64 := uint64(0)
|
||||
val64, valtype, err = k.GetIntegerValue(name)
|
||||
val = uint32(val64)
|
||||
return
|
||||
}
|
||||
|
||||
var vncSvcConfig = &service.Config{
|
||||
Name: "tvnserver",
|
||||
DisplayName: "TightVNC Server",
|
||||
Description: "TightVNC Server (managed by remote-core)",
|
||||
Arguments: []string{"-service"},
|
||||
}
|
||||
|
||||
// InstallVncServer 绿色安装 TightVNC 服务端(需管理员权限)。
|
||||
// 最新版注册表全集配置(VncClientDefaultConfig 37 项, 随机 8 位密码)→ 注册系统服务。
|
||||
// 装而不启:服务注册后保持 Stopped, 等远程指令再 VncStart(避免常驻监听开端口);
|
||||
// 若服务已在运行则重启以加载新配置。返回生成的明文密码(调用方自行上报/展示)。
|
||||
func InstallVncServer(exePath string) (string, error) {
|
||||
if finfo, err := os.Stat(exePath); err != nil || finfo.IsDir() {
|
||||
return "", fmt.Errorf("tvnserver.exe 不存在: %s", exePath)
|
||||
}
|
||||
|
||||
// 最新版 TightVNC 注册表配置全集(含随机密码)
|
||||
config := VncClientDefaultConfig(true)
|
||||
if err := WriteVncServerConfig(config); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 注册系统服务:未安装→安装; 运行中→重启加载新配置; 已停止→保持
|
||||
vncSvcConfig.Executable = exePath
|
||||
if err := VncInit(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
status, err := VncService.Status()
|
||||
switch {
|
||||
case err != nil: // 未安装(kardianos 对未安装服务 Status 返回错误)
|
||||
if err := VncInstall(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
case status == service.StatusRunning:
|
||||
if err := VncRestart(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return VncPasswordDecrypt(config.Password), nil
|
||||
}
|
||||
|
||||
// VncInit 初始化 VNC 服务对象,VncInstall/VncStart 等操作前必须调用
|
||||
func VncInit() error {
|
||||
var err error
|
||||
VncService, err = service.New(nil, vncSvcConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VncInstall 安装 TightVNC 服务
|
||||
func VncInstall() error {
|
||||
err := VncService.Install()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VncUninstall 停止并卸载 TightVNC 服务
|
||||
func VncUninstall() error {
|
||||
_ = VncService.Stop()
|
||||
err := VncService.Uninstall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VncStart 启动 TightVNC 服务
|
||||
func VncStart() error {
|
||||
err := VncService.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VncStop 停止 TightVNC 服务
|
||||
func VncStop() error {
|
||||
err := VncService.Stop()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VncRestart 重启 TightVNC 服务
|
||||
func VncRestart() error {
|
||||
err := VncService.Stop()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = VncService.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VncPasswordCrypt 加密 VNC 密码(TightVNC 注册表存储格式)
|
||||
func VncPasswordCrypt(password string) []byte {
|
||||
return vncpasswd.Crypt(password)
|
||||
}
|
||||
|
||||
// VncPasswordDecrypt 解密 VNC 密码。密文恒为 8 字节(标准 VNC DES),
|
||||
// 不足 8 字节(缺失/截断)直接返回空串——底层 DES 解密会按前 8 字节切片,短输入必 panic。
|
||||
func VncPasswordDecrypt(data []byte) string {
|
||||
if len(data) < 8 {
|
||||
return ""
|
||||
}
|
||||
return vncpasswd.Decrypt(data)
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
//go:build windows
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"golang.org/x/sys/windows/registry"
|
||||
"math/big"
|
||||
"os"
|
||||
)
|
||||
|
||||
// GetRemoteInfo 一次性获取远程控制相关信息(服务状态/端口/密码/主机信息)
|
||||
func GetRemoteInfo() Info {
|
||||
info := Info{}
|
||||
|
||||
status, _ := GetVncServiceStatus()
|
||||
info.VncState = int(status)
|
||||
|
||||
status, _ = GetRdpServiceStatus()
|
||||
info.RdpState = int(status)
|
||||
|
||||
port, _ := GetRdpPort()
|
||||
info.RdpPort = port
|
||||
|
||||
port, _ = GetVncPort()
|
||||
info.VncPort = port
|
||||
|
||||
password, _ := GetVncPassword()
|
||||
info.VncPassword = password
|
||||
|
||||
hostname, _ := os.Hostname()
|
||||
info.Hostname = hostname
|
||||
info.IpAddr = getIPs()
|
||||
info.MacAddr = getMacAddrs()
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
// GetVncPort 从注册表读取 TightVNC 主端口
|
||||
func GetVncPort() (int, error) {
|
||||
var key registry.Key
|
||||
var err error
|
||||
key, err = registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\TightVNC\Server`, registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var val uint64
|
||||
val, _, err = key.GetIntegerValue("RfbPort")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var port int = int(val)
|
||||
return port, nil
|
||||
}
|
||||
|
||||
// GetRdpPort 从注册表读取远程桌面端口
|
||||
func GetRdpPort() (int, error) {
|
||||
var key registry.Key
|
||||
var err error
|
||||
key, err = registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp`, registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var val uint64
|
||||
val, _, err = key.GetIntegerValue("PortNumber")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var port int = int(val)
|
||||
return port, nil
|
||||
}
|
||||
|
||||
// GetVncPassword 读取并解密 TightVNC 连接密码
|
||||
func GetVncPassword() (string, error) {
|
||||
var key registry.Key
|
||||
var err error
|
||||
key, err = registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\TightVNC\Server`, registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
val, _, err := key.GetBinaryValue("Password")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(val) == 0 {
|
||||
return "", err
|
||||
}
|
||||
password := VncPasswordDecrypt(val)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return password, nil
|
||||
}
|
||||
|
||||
// VncServerDefaultConfig 生成 TightVNC 服务端默认配置(连接 RDP 会话)
|
||||
// randPass 为 true 时生成 8 位随机密码,否则使用固定密码
|
||||
func VncServerDefaultConfig(randPass bool) VncServerConfig {
|
||||
password := "tvncpass"
|
||||
if randPass {
|
||||
password = createRandomString(8)
|
||||
}
|
||||
config := VncServerConfig{
|
||||
ExtraPorts: "",
|
||||
QueryTimeout: 30,
|
||||
QueryAcceptOnTimeout: 0,
|
||||
LocalInputPriorityTimeout: 3,
|
||||
LocalInputPriority: 1,
|
||||
BlockRemoteInput: 0,
|
||||
BlockLocalInput: 0,
|
||||
IpAccessControl: "",
|
||||
RfbPort: 5900,
|
||||
HttpPort: 5800,
|
||||
DisconnectAction: 0,
|
||||
AcceptRfbConnections: 1,
|
||||
UseVncAuthentication: 1,
|
||||
UseControlAuthentication: 0,
|
||||
RepeatControlAuthentication: 0,
|
||||
LoopbackOnly: 0,
|
||||
AcceptHttpConnections: 0,
|
||||
LogLevel: 0,
|
||||
EnableFileTransfers: 1,
|
||||
RemoveWallpaper: 1,
|
||||
UseD3D: 1,
|
||||
UseMirrorDriver: 1,
|
||||
EnableUrlParams: 1,
|
||||
Password: VncPasswordCrypt(password),
|
||||
AlwaysShared: 0,
|
||||
NeverShared: 0,
|
||||
DisconnectClients: 1,
|
||||
PollingInterval: 1000,
|
||||
AllowLoopback: 1,
|
||||
VideoRecognitionInterval: 3000,
|
||||
GrabTransparentWindows: 1,
|
||||
SaveLogToAllUsersPath: 0,
|
||||
RunControlInterface: 0,
|
||||
IdleTimeout: 0,
|
||||
VideoClasses: "",
|
||||
VideoRects: "",
|
||||
ConnectToRdp: 1,
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
// VncClientDefaultConfig 生成 TightVNC 客户端默认配置(不连接 RDP 会话)
|
||||
// randPass 为 true 时生成 8 位随机密码,否则使用固定密码
|
||||
func VncClientDefaultConfig(randPass bool) VncServerConfig {
|
||||
password := "tvncpass"
|
||||
if randPass {
|
||||
password = createRandomString(8)
|
||||
}
|
||||
config := VncServerConfig{
|
||||
ExtraPorts: "",
|
||||
QueryTimeout: 30,
|
||||
QueryAcceptOnTimeout: 0,
|
||||
LocalInputPriorityTimeout: 3,
|
||||
LocalInputPriority: 1,
|
||||
BlockRemoteInput: 0,
|
||||
BlockLocalInput: 0,
|
||||
IpAccessControl: "",
|
||||
RfbPort: 5900,
|
||||
HttpPort: 5800,
|
||||
DisconnectAction: 0,
|
||||
AcceptRfbConnections: 1,
|
||||
UseVncAuthentication: 1,
|
||||
UseControlAuthentication: 0,
|
||||
RepeatControlAuthentication: 0,
|
||||
LoopbackOnly: 0,
|
||||
AcceptHttpConnections: 0,
|
||||
LogLevel: 0,
|
||||
EnableFileTransfers: 1,
|
||||
RemoveWallpaper: 0,
|
||||
UseD3D: 1,
|
||||
UseMirrorDriver: 1,
|
||||
EnableUrlParams: 1,
|
||||
Password: VncPasswordCrypt(password),
|
||||
AlwaysShared: 0,
|
||||
NeverShared: 0,
|
||||
DisconnectClients: 1,
|
||||
PollingInterval: 1000,
|
||||
AllowLoopback: 1,
|
||||
VideoRecognitionInterval: 3000,
|
||||
GrabTransparentWindows: 1,
|
||||
SaveLogToAllUsersPath: 0,
|
||||
RunControlInterface: 0,
|
||||
IdleTimeout: 0,
|
||||
VideoClasses: "",
|
||||
VideoRects: "",
|
||||
ConnectToRdp: 0,
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
// WriteVncServerConfig 将 TightVNC 服务端配置写入注册表(项不存在时自动创建)
|
||||
func WriteVncServerConfig(config VncServerConfig) error {
|
||||
|
||||
key, err := registry.OpenKey(registry.LOCAL_MACHINE, "SOFTWARE\\TightVNC\\Server", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
if err == registry.ErrNotExist {
|
||||
// 项不存在 创建它
|
||||
key, _, err = registry.CreateKey(registry.LOCAL_MACHINE, "SOFTWARE\\TightVNC\\Server", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
defer key.Close()
|
||||
|
||||
err = key.SetStringValue("ExtraPorts", config.ExtraPorts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("QueryTimeout", config.QueryTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("QueryAcceptOnTimeout", config.QueryAcceptOnTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("LocalInputPriorityTimeout", config.LocalInputPriorityTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("LocalInputPriority", config.LocalInputPriority)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("BlockRemoteInput", config.BlockRemoteInput)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("BlockLocalInput", config.BlockLocalInput)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetStringValue("IpAccessControl", config.IpAccessControl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("RfbPort", config.RfbPort)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("HttpPort", config.HttpPort)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("DisconnectAction", config.DisconnectAction)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("AcceptRfbConnections", config.AcceptRfbConnections)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("UseVncAuthentication", config.UseVncAuthentication)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("UseControlAuthentication", config.UseControlAuthentication)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("RepeatControlAuthentication", config.RepeatControlAuthentication)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("LoopbackOnly", config.LoopbackOnly)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("AcceptHttpConnections", config.AcceptHttpConnections)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("LogLevel", config.LogLevel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("EnableFileTransfers", config.EnableFileTransfers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("RemoveWallpaper", config.RemoveWallpaper)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("UseD3D", config.UseD3D)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("UseMirrorDriver", config.UseMirrorDriver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("EnableUrlParams", config.EnableUrlParams)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetBinaryValue("Password", config.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("AlwaysShared", config.AlwaysShared)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("NeverShared", config.NeverShared)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("DisconnectClients", config.DisconnectClients)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("PollingInterval", config.PollingInterval)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("AllowLoopback", config.AllowLoopback)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("VideoRecognitionInterval", config.VideoRecognitionInterval)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("GrabTransparentWindows", config.GrabTransparentWindows)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("SaveLogToAllUsersPath", config.SaveLogToAllUsersPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("RunControlInterface", config.RunControlInterface)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("IdleTimeout", config.IdleTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetStringValue("VideoClasses", config.VideoClasses)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetStringValue("VideoRects", config.VideoRects)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = key.SetDWordValue("ConnectToRdp", config.ConnectToRdp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnableSoftwareSASGeneration 启用软件SAS模拟输入
|
||||
func EnableSoftwareSASGeneration() error {
|
||||
// SAS模拟输入
|
||||
key, err := registry.OpenKey(registry.LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
if err == registry.ErrNotExist {
|
||||
// 项不存在 创建它
|
||||
key, _, err = registry.CreateKey(registry.LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
defer key.Close()
|
||||
|
||||
err = key.SetDWordValue("SoftwareSASGeneration", 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnableWinlogonDisableCAD 关闭 Ctrl + Alt + Del 组合键来登录
|
||||
func EnableWinlogonDisableCAD() error {
|
||||
key, err := registry.OpenKey(registry.LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
if err == registry.ErrNotExist {
|
||||
// 项不存在 创建它
|
||||
key, _, err = registry.CreateKey(registry.LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
defer key.Close()
|
||||
|
||||
err = key.SetDWordValue("DisableCAD", 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnableSystemDisableCAD 关闭 Ctrl + Alt + Del 组合键来登录
|
||||
func EnableSystemDisableCAD() error {
|
||||
key, err := registry.OpenKey(registry.LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
if err == registry.ErrNotExist {
|
||||
// 项不存在 创建它
|
||||
key, _, err = registry.CreateKey(registry.LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
defer key.Close()
|
||||
|
||||
err = key.SetDWordValue("DisableCAD", 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createRandomString 生成指定长度的随机字符串
|
||||
func createRandomString(len int) string {
|
||||
var container string
|
||||
var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
|
||||
b := bytes.NewBufferString(str)
|
||||
length := b.Len()
|
||||
bigInt := big.NewInt(int64(length))
|
||||
for i := 0; i < len; i++ {
|
||||
randomInt, _ := rand.Int(rand.Reader, bigInt)
|
||||
container += string(str[randomInt.Int64()])
|
||||
}
|
||||
return container
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# shell
|
||||
|
||||
被控端 Web 终端(自 remote-backend-server internal/handlers/shell 移植,去 DB
|
||||
依赖):WebSocket 交互式终端(Windows ConPTY / Unix pty)+ asciinema 会话录制。
|
||||
|
||||
## 路由
|
||||
|
||||
```go
|
||||
import "git.zeroonesoft.cn/golib/remote-core/shell"
|
||||
|
||||
shell.RegisterRoutersWebShell(r *gin.RouterGroup, recDir)
|
||||
```
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|---|---|---|
|
||||
| GET | `/web/shell` | WebSocket 升级,启动终端(Windows 优先 powershell.exe,缺失回退 cmd.exe;Unix 为 bash) |
|
||||
| GET | `/web/shell/record` | 录制文件列表 |
|
||||
|
||||
## 协议
|
||||
|
||||
WebSocket JSON 信封 `OpDataType{op, data}`:输入/输出流与 `resize`(`ResizeDataType`
|
||||
调整行列)走同一连接。
|
||||
|
||||
## 注意
|
||||
|
||||
- 录制为 asciinema 格式,落盘 `recDir`,可用 asciinema 播放器回放审计。
|
||||
- `CheckOrigin` 放开所有来源(跨域),接入公网必须由网关侧补鉴权。
|
||||
+124
-134
@@ -1,31 +1,25 @@
|
||||
package shell
|
||||
|
||||
// 移植自 remote-backend-server internal/handlers/shell(去 DB 依赖, ConPTY 终端 + asciinema 录制)。
|
||||
// 标准库 http.HandlerFunc 形态, 路由注册经 webhttp.Router 适配(去 gin 化)。
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/runletapp/go-console"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"git.zeroonesoft.cn/golib/remote-core/common"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type windowSize struct {
|
||||
Rows uint16 `json:"rows"`
|
||||
Cols uint16 `json:"cols"`
|
||||
X uint16
|
||||
Y uint16
|
||||
}
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/runletapp/go-console"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"git.zeroonesoft.cn/golib/remote-core/common"
|
||||
"git.zeroonesoft.cn/golib/remote-core/webhttp"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
@@ -46,162 +40,158 @@ type ResizeDataType struct {
|
||||
Rows int `json:"rows"`
|
||||
}
|
||||
|
||||
// RegisterRoutersWebShell 注册路由
|
||||
func RegisterRoutersWebShell(r *gin.RouterGroup, recDir string) {
|
||||
r.GET("/web/shell", getWebShell(recDir))
|
||||
// recStoreDir 会话录制目录, Register 时注入; 录制写入与记录列表两处共用。
|
||||
// 原实现硬编码 ./rec, recDir 形参是死参数(remote-service 传 RunDir/rec 不生效)。
|
||||
var recStoreDir = "./rec"
|
||||
|
||||
// RegisterRoutersWebShell 注册路由。recDir 为会话录制目录, 传空退回 ./rec。
|
||||
func RegisterRoutersWebShell(r webhttp.Router, recDir string) {
|
||||
if recDir != "" {
|
||||
recStoreDir = recDir
|
||||
}
|
||||
r.GET("/web/shell", getWebShell)
|
||||
r.GET("/web/shell/record", RecoderList)
|
||||
}
|
||||
|
||||
func getWebShell(recDir string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
func getWebShell(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
logrus.Errorf("Unable to upgrade connection")
|
||||
return
|
||||
}
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
logrus.Errorf("Unable to upgrade connection")
|
||||
return
|
||||
}
|
||||
|
||||
proc, err := console.New(180, 30)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
arr := make([]string, 0)
|
||||
if runtime.GOOS == "windows" {
|
||||
if ok, _ := common.PathExists("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"); ok {
|
||||
arr = append(arr, "powershell.exe") // powershell.exe cmd.exe
|
||||
} else {
|
||||
arr = append(arr, "cmd.exe")
|
||||
}
|
||||
proc, err := console.New(180, 30)
|
||||
if err != nil {
|
||||
logrus.Errorf("创建终端失败:%s", err.Error())
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
arr := make([]string, 0)
|
||||
if runtime.GOOS == "windows" {
|
||||
if ok, _ := common.PathExists("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"); ok {
|
||||
arr = append(arr, "powershell.exe") // powershell.exe cmd.exe
|
||||
} else {
|
||||
arr = []string{"bash"} // powershell.exe cmd.exe
|
||||
arr = append(arr, "cmd.exe")
|
||||
}
|
||||
|
||||
if err := proc.Start(arr); err != nil {
|
||||
logrus.Errorf("启动出错:%s", err.Error())
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
arr = []string{"bash"} // powershell.exe cmd.exe
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logrus.Errorf("Unable to start pty/cmd")
|
||||
conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
proc.Close()
|
||||
conn.Close()
|
||||
}()
|
||||
if err := proc.Start(arr); err != nil {
|
||||
logrus.Errorf("启动出错:%s", err.Error())
|
||||
conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
proc.Close()
|
||||
conn.Close()
|
||||
}()
|
||||
|
||||
var recorder *Recorder
|
||||
var recorder *Recorder
|
||||
|
||||
os.MkdirAll("./rec", 0766)
|
||||
fileName := path.Join("./rec/", fmt.Sprintf("%s.cast", time.Now().Format("20060102_150405")))
|
||||
logrus.Debugf("记录文件名:%s", fileName)
|
||||
f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0766)
|
||||
if err != nil {
|
||||
conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
|
||||
logrus.Errorf("创建记录文件失败")
|
||||
return
|
||||
}
|
||||
os.MkdirAll(recStoreDir, 0766)
|
||||
fileName := filepath.Join(recStoreDir, fmt.Sprintf("%s.cast", time.Now().Format("20060102_150405")))
|
||||
logrus.Debugf("记录文件名:%s", fileName)
|
||||
f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0766)
|
||||
if err != nil {
|
||||
conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
|
||||
logrus.Errorf("创建记录文件失败")
|
||||
return
|
||||
}
|
||||
|
||||
defer f.Close()
|
||||
recorder = NewRecorder(f)
|
||||
defer f.Close()
|
||||
recorder = NewRecorder(f)
|
||||
|
||||
if recorder != nil {
|
||||
recorder.Lock()
|
||||
recorder.WriteHeader(30, 150)
|
||||
recorder.Unlock()
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
buf := make([]byte, 0x10000)
|
||||
read, err := proc.Read(buf)
|
||||
if err != nil {
|
||||
conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
|
||||
logrus.Errorf("读取错误:%s", err.Error())
|
||||
return
|
||||
}
|
||||
conn.WriteMessage(websocket.BinaryMessage, buf[:read])
|
||||
if recorder != nil {
|
||||
recorder.Lock()
|
||||
recorder.WriteData(InputType, string(buf[:read]))
|
||||
recorder.Unlock()
|
||||
}
|
||||
}
|
||||
}()
|
||||
if recorder != nil {
|
||||
recorder.Lock()
|
||||
recorder.WriteHeader(30, 150)
|
||||
recorder.Unlock()
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
messageType, reader, err := conn.NextReader()
|
||||
buf := make([]byte, 0x10000)
|
||||
read, err := proc.Read(buf)
|
||||
if err != nil {
|
||||
logrus.Errorf("Unable to grab next reader")
|
||||
conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
|
||||
logrus.Errorf("读取错误:%s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if messageType != websocket.TextMessage {
|
||||
logrus.Errorf("无效的消息")
|
||||
//conn.WriteMessage(websocket.TextMessage, []byte("Unexpected text message"))
|
||||
//continue
|
||||
conn.WriteMessage(websocket.BinaryMessage, buf[:read])
|
||||
if recorder != nil {
|
||||
recorder.Lock()
|
||||
recorder.WriteData(InputType, string(buf[:read]))
|
||||
recorder.Unlock()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
buf := make([]byte, 0x10000)
|
||||
n, err := reader.Read(buf)
|
||||
for {
|
||||
messageType, reader, err := conn.NextReader()
|
||||
if err != nil {
|
||||
logrus.Errorf("Unable to grab next reader")
|
||||
return
|
||||
}
|
||||
|
||||
if messageType != websocket.TextMessage {
|
||||
logrus.Errorf("无效的消息")
|
||||
//conn.WriteMessage(websocket.TextMessage, []byte("Unexpected text message"))
|
||||
//continue
|
||||
}
|
||||
|
||||
buf := make([]byte, 0x10000)
|
||||
n, err := reader.Read(buf)
|
||||
|
||||
if err != nil {
|
||||
logrus.Errorf("Error after copying %d bytes", n)
|
||||
}
|
||||
|
||||
if n > 0 {
|
||||
|
||||
opData := OpDataType{}
|
||||
newBuf := buf[:n]
|
||||
err = json.Unmarshal(newBuf, &opData)
|
||||
if err != nil {
|
||||
logrus.Errorf("Error after copying %d bytes", n)
|
||||
logrus.Errorf("解析错误:%s", err.Error())
|
||||
}
|
||||
if opData.Op == "stdin" {
|
||||
value, ok := opData.Data.(string)
|
||||
if ok {
|
||||
n, err = proc.Write([]byte(value))
|
||||
if err != nil {
|
||||
logrus.Errorf("写放数据错误g %d bytes", n)
|
||||
}
|
||||
} else {
|
||||
|
||||
if n > 0 {
|
||||
|
||||
opData := OpDataType{}
|
||||
newBuf := buf[:n]
|
||||
fmt.Println("收到数据", string(newBuf))
|
||||
err = json.Unmarshal(newBuf, &opData)
|
||||
if err != nil {
|
||||
logrus.Errorf("解析错误:%s", err.Error())
|
||||
}
|
||||
if opData.Op == "stdin" {
|
||||
value, ok := opData.Data.(string)
|
||||
if ok {
|
||||
|
||||
n, err = proc.Write([]byte(value))
|
||||
if err != nil {
|
||||
logrus.Errorf("写放数据错误g %d bytes", n)
|
||||
} else {
|
||||
fmt.Println("写入成功")
|
||||
}
|
||||
} else {
|
||||
|
||||
} else if opData.Op == "resize" {
|
||||
// Data 反序列化后是 map[string]interface{}, 不能直接断言 ResizeDataType
|
||||
// (此前断言恒失败, 前端 resize 被静默吞掉, PTY 固定 180x30)
|
||||
raw, merr := json.Marshal(opData.Data)
|
||||
var size ResizeDataType
|
||||
if merr == nil && json.Unmarshal(raw, &size) == nil && size.Cols > 0 && size.Rows > 0 {
|
||||
if serr := proc.SetSize(size.Cols, size.Rows); serr != nil {
|
||||
logrus.Errorf("重置大小错误: %s", serr.Error())
|
||||
}
|
||||
|
||||
} else if opData.Op == "resize" {
|
||||
fmt.Println("resize")
|
||||
value, ok := opData.Data.(ResizeDataType)
|
||||
if ok {
|
||||
err = proc.SetSize(value.Cols, value.Rows)
|
||||
if err != nil {
|
||||
logrus.Errorf("重置大小错误 %d bytes", n)
|
||||
} else {
|
||||
fmt.Println("重置大小成功")
|
||||
}
|
||||
} else {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func RecoderList(c *gin.Context) {
|
||||
files, err := ioutil.ReadDir("./rec")
|
||||
func RecoderList(w http.ResponseWriter, _ *http.Request) {
|
||||
files, err := os.ReadDir(recStoreDir)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(200, gin.H{"ok": false, "msg": err.Error()})
|
||||
webhttp.WriteJSON(w, http.StatusOK, map[string]any{"ok": false, "msg": err.Error()})
|
||||
return
|
||||
}
|
||||
var filesName []string
|
||||
@@ -214,5 +204,5 @@ func RecoderList(c *gin.Context) {
|
||||
filesName = append(filesName, f.Name())
|
||||
}
|
||||
}
|
||||
c.JSON(200, filesName)
|
||||
webhttp.WriteJSON(w, http.StatusOK, filesName)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// Package webhttp 被控 HTTP 能力的极薄适配层。
|
||||
//
|
||||
// file/shell/process 三个被控能力包统一以标准库 http.HandlerFunc 为 handler
|
||||
// 形态、以 Router 接口收拢路由注册, 不再绑死任何 Web 框架。消费方按自身
|
||||
// 技术栈适配: 纯标准库用 ServeMuxRouter 直挂 *http.ServeMux(Go 1.22+ 方法
|
||||
// +路径模式); 已有 gin 栈的用 gin.WrapH 桥接, 中间件链照常生效。
|
||||
//
|
||||
// 由此 gin(连带其拖入的 quic-go/http3、mongo bson、ugorji codec、goccy
|
||||
// 等重依赖)从被控端二进制中整体消失, 体积近乎减半。
|
||||
package webhttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Router file/shell/process 声明路由用的最小接口(pattern 形如
|
||||
// "/file/list", 不含组前缀; 前缀由适配器拼)。
|
||||
type Router interface {
|
||||
GET(pattern string, h http.HandlerFunc)
|
||||
POST(pattern string, h http.HandlerFunc)
|
||||
PUT(pattern string, h http.HandlerFunc)
|
||||
DELETE(pattern string, h http.HandlerFunc)
|
||||
HEAD(pattern string, h http.HandlerFunc)
|
||||
}
|
||||
|
||||
// ServeMuxRouter 把 *http.ServeMux 适配为 Router, 注册
|
||||
// "METHOD prefix+pattern" 模式路由(如 "GET /api/file/list")。
|
||||
// 注册了 GET 的路径自动兼容 HEAD。
|
||||
func ServeMuxRouter(mux *http.ServeMux, prefix string) Router {
|
||||
return &muxRouter{mux: mux, prefix: prefix}
|
||||
}
|
||||
|
||||
type muxRouter struct {
|
||||
mux *http.ServeMux
|
||||
prefix string
|
||||
}
|
||||
|
||||
func (m *muxRouter) route(method, pattern string) string {
|
||||
return method + " " + m.prefix + pattern
|
||||
}
|
||||
|
||||
func (m *muxRouter) GET(pattern string, h http.HandlerFunc) {
|
||||
m.mux.HandleFunc(m.route(http.MethodGet, pattern), h)
|
||||
}
|
||||
|
||||
func (m *muxRouter) POST(pattern string, h http.HandlerFunc) {
|
||||
m.mux.HandleFunc(m.route(http.MethodPost, pattern), h)
|
||||
}
|
||||
|
||||
func (m *muxRouter) PUT(pattern string, h http.HandlerFunc) {
|
||||
m.mux.HandleFunc(m.route(http.MethodPut, pattern), h)
|
||||
}
|
||||
|
||||
func (m *muxRouter) DELETE(pattern string, h http.HandlerFunc) {
|
||||
m.mux.HandleFunc(m.route(http.MethodDelete, pattern), h)
|
||||
}
|
||||
|
||||
func (m *muxRouter) HEAD(pattern string, h http.HandlerFunc) {
|
||||
m.mux.HandleFunc(m.route(http.MethodHead, pattern), h)
|
||||
}
|
||||
|
||||
// WriteJSON 统一 JSON 响应(响应头口径与原 gin c.JSON 一致)。
|
||||
// 业务码仍在 body 的 code 字段, HTTP 状态恒 200, 与既有前端约定不变。
|
||||
func WriteJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
Reference in New Issue
Block a user