5 Commits
Author SHA1 Message Date
w11 006138172f fix(remote): 补 ReadVncServerConfig 漏读的 LogLevel(读/写/结构体三处均达 37 项全集)+VncPasswordDecrypt 短于 8 字节直接返回空串(底层 DES 按前 8 字节切片, 短输入必 panic); 新增字段数锁定与短密文防护单测 2026-09-23 19:55:37 +08:00
w11 38e44f7b4a fix(remote): VNC 升级支持最新版 TightVNC——修 ReadVncServerConfig 的 ConnectToRdp 误读 ExtraPorts、补 WriteVncServerConfig 漏写的 LogLevel(读/写均达 37 项全集)、InstallVncServer 从固定密码空壳实现为真安装(校验 exe→写最新版全集配置+随机密码→注册服务, 装而不启/运行中重启, 返回明文密码); 锁定最新版默认值与安装异常路径的单测 2026-09-23 19:39:08 +08:00
4566704 181150b7a1 docs: 补齐 common/file/process/shell 四个既有包的 README
- 每包定位/路由表/用法与注意事项(鉴权告诫、录制审计、防误杀语义)
- 至此 remote-core 全部包 README 覆盖
2026-09-20 12:50:55 +08:00
4566704 8619afe531 chore(deps): go mod tidy 收敛 remote 依赖声明 2026-09-20 12:41:28 +08:00
4566704 9c2a57b576 feat(remote): 自 go-hua/remote 并入远程控制服务管理
- RDP/VNC(TightVNC)/Radmin 服务状态查询与启停重置、VNC 安装/配置读写/密码
  加解密、GetRemoteInfo 汇总、CAD/SAS 注册表开关
- 与本库 file/shell/process 同属被控端远程运维能力; 新增依赖
  kardianos/service、KarpelesLab/vncpasswd
- 附 remote_test.go 与包 README(含平台支持矩阵与权限注意)
2026-09-20 12:39:30 +08:00
13 changed files with 1219 additions and 1 deletions
+11
View File
@@ -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") // 文件/目录是否存在
```
+26
View File
@@ -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 反代出网。
- 路径参数来自控制端,接入公网前务必在网关侧做鉴权与路径白名单校验。
+3 -1
View File
@@ -3,13 +3,16 @@ module git.zeroonesoft.cn/golib/remote-core
go 1.26.0 go 1.26.0
require ( require (
github.com/KarpelesLab/vncpasswd v1.0.1
github.com/gin-gonic/gin v1.12.0 github.com/gin-gonic/gin v1.12.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
github.com/jaypipes/ghw v0.13.0 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/runletapp/go-console v0.0.0-20211204140000-27323a28410a
github.com/shirou/gopsutil/v3 v3.24.5 github.com/shirou/gopsutil/v3 v3.24.5
github.com/sirupsen/logrus v1.10.2 github.com/sirupsen/logrus v1.10.2
github.com/yusufpapurcu/wmi v1.2.4 github.com/yusufpapurcu/wmi v1.2.4
golang.org/x/sys v0.48.0
) )
require ( require (
@@ -51,7 +54,6 @@ require (
golang.org/x/arch v0.22.0 // indirect golang.org/x/arch v0.22.0 // indirect
golang.org/x/crypto v0.57.0 // indirect golang.org/x/crypto v0.57.0 // indirect
golang.org/x/net v0.58.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 golang.org/x/text v0.42.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
+5
View File
@@ -1,3 +1,5 @@
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 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA=
github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8= 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 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
@@ -49,6 +51,8 @@ github.com/jaypipes/pcidb v1.0.1/go.mod h1:6xYUz/yYEyOkIkUt2t2J2folIuZ4Yg6uByCGF
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= 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 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kardianos/service v1.2.2 h1:ZvePhAHfvo0A7Mftk/tEzqEZ7Q4lgnR8sGz4xu1YX60=
github.com/kardianos/service v1.2.2/go.mod h1:CIMRFEJVL+0DS1a3Nx06NaMn4Dz63Ng6O7dl0qH0zVM=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= 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/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -126,6 +130,7 @@ golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZ
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= 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-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.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.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+23
View File
@@ -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`(连子进程树强杀)。
+63
View File
@@ -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` 实现),加解密为确定性
变换,注意密文落盘位置的访问控制。
+191
View File
@@ -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
}
+115
View File
@@ -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)
}
}
}
+43
View File
@@ -0,0 +1,43 @@
// Package remote 提供 RDP/VNC 等远程控制的服务状态查询、配置读写与启停控制。
package remote
// VncServerConfig TightVNC 服务端配置(对应注册表 SOFTWARE\TightVNC\Server 下的键值)
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会话
}
+69
View File
@@ -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
View File
@@ -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)
}
+455
View File
@@ -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
}
+27
View File
@@ -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` 放开所有来源(跨域),接入公网必须由网关侧补鉴权。