This commit is contained in:
12600k-rog-d4
2026-08-13 22:49:50 +08:00
parent 5e296bfe19
commit 2aaaa16ae2
24 changed files with 1415 additions and 327 deletions

View File

@@ -4,6 +4,7 @@ import (
"fmt"
"net"
"os"
"strings"
"time"
"golang.org/x/crypto/ssh"
@@ -16,6 +17,7 @@ type Config struct {
KeyFile string
Port int
Timeout time.Duration
SudoPwd string // 非 root 用户执行特权命令(sudo)时的密码
}
// NewConfig 创建配置
@@ -54,9 +56,61 @@ func RunCommand(client *ssh.Client, command string) (string, error) {
out, err := session.CombinedOutput(command)
if err != nil {
return string(out), fmt.Errorf("命令执行失败: %w", err)
return cleanOutput(out), fmt.Errorf("命令执行失败: %w", err)
}
return string(out), nil
return cleanOutput(out), nil
}
// isNoiseLine 判断某行是否为登录横幅/欢迎语等噪声fnOS 的 admin 用户会把
// "Could not chdir to home directory" 之类写入 stdout污染命令解析
func isNoiseLine(line string) bool {
s := strings.TrimSpace(line)
if s == "" {
return false
}
prefixes := []string{
"Could not chdir to",
"Last login:",
"Welcome to",
"/etc/motd",
"Permission denied",
"bash: line 1:",
}
for _, p := range prefixes {
if strings.HasPrefix(s, p) {
return true
}
}
// 某些横幅是 "Could: command not found" 这类由前面噪声行残生,
// 形如 "xxx: command not found" 且前半段是噪声关键词的也过滤
if strings.Contains(s, ": command not found") {
return true
}
return false
}
// cleanOutput 过滤掉登录横幅等噪声行,仅保留真实命令输出
func cleanOutput(raw []byte) string {
lines := strings.Split(string(raw), "\n")
var kept []string
for _, ln := range lines {
if isNoiseLine(ln) {
continue
}
kept = append(kept, ln)
}
return strings.Join(kept, "\n")
}
// EnsureHome 确保远端登录用户的 HOME 目录存在,消除 fnOS "Could not chdir to
// home directory" 登录横幅(该横幅会写入 stdout 污染命令输出)。
func EnsureHome(client *ssh.Client) {
out, err := RunCommand(client, "echo $HOME")
home := strings.TrimSpace(out)
if err != nil || home == "" || home == "/" {
return
}
RunCommand(client, fmt.Sprintf("mkdir -p %s", home))
}
// buildSSHConfig 构建认证配置