更新密码找回uniapp

This commit is contained in:
hero920103 committed 2026-11-16 17:22:50 +08:00
1 parent 7f9a66da0f
commit 3fdda89833
1304 files changed
+3503 -26132

No files matched your search

+44 -74
View File
@@ -1,21 +1,3 @@
// Command deploy 本地目录 → 服务器目录的「差异比对 + 增量上传」工具。
//
// 用途:只上传本地改动过的文件,跳过未改动的文件,避免每次整包覆盖。
//
// 工作流程:
// 1. SSH 连上服务器,执行 md5sum 拿到远端目录的文件清单与指纹
// 2. 本地遍历目录计算 MD5(按排除规则跳过日志、可执行文件等)
// 3. 比对两份清单,得出「新增 / 已修改」的文件清单并打印
// 4. 确认后把差异文件打成 tar 流,通过 SSH 管道在远端解开
// 5. 回读远端指纹复核,确认上传结果
//
// 之所以用 Go 实现而不是直接调 scp:Windows 自带的 OpenSSH scp 不支持
// 非交互传密码(sshpass / pscp 都没装),x/crypto/ssh 可以直接用密码登录,
// 全程无交互,适合丢进 .bat 里一键执行。
//
// 用法:
//
// deploy -host 212.64.112.158 -port 8822 -user root -dir /www/wwwroot/api.yunzer.cn -local .
package main
import (
@@ -38,29 +20,23 @@ import (
"golang.org/x/crypto/ssh"
)
// ============================ 默认排除规则 ============================
// defaultExcludeDirs 不参与同步的目录名
var defaultExcludeDirs = []string{
".git", ".idea", ".vscode", ".svn",
"node_modules", "bin", "dist", "tmp", "temp",
}
// defaultExcludeFiles 不参与同步的文件名(支持 * 通配)
var defaultExcludeFiles = []string{
"*.exe", "*.log", "*.pid", "*.bak", "*.tmp", "*.pub",
"nohup.out", "output.log", "go.log",
"test-output-*.txt", "migrate_*.csv",
"server", // 无扩展名的编译产物
"*_id_ed25519", // SSH 私钥:绝对不能传到服务器
"server",
"*_id_ed25519",
".deploy_known_hosts",
}
// ============================ 配置 ============================
type options struct {
host string
port string // ← 新增
port string
user string
pass string
keyFile string
@@ -75,13 +51,12 @@ type options struct {
quiet bool
}
// errCancelled 用户在上传前确认时选择了取消(区别于真正的失败)
var errCancelled = errors.New("用户取消")
func main() {
var opt options
flag.StringVar(&opt.host, "host", "212.64.112.158", "服务器地址")
flag.StringVar(&opt.port, "port", "22", "SSH 端口") // ← 新增
flag.StringVar(&opt.port, "port", "22", "SSH 端口")
flag.StringVar(&opt.user, "user", "root", "SSH 用户名")
flag.StringVar(&opt.pass, "pass", "", "SSH 密码(留空则读环境变量 DEPLOY_PASS)")
flag.StringVar(&opt.keyFile, "key", "", "SSH 私钥路径(指定后用密钥登录,忽略密码)")
@@ -106,15 +81,13 @@ func main() {
if err := run(opt); err != nil {
if errors.Is(err, errCancelled) {
os.Exit(3) // 取消不是失败,用独立退出码告知调用方
os.Exit(3)
}
fmt.Printf("[失败] %v\n", err)
os.Exit(1)
}
}
// ============================ 主流程 ============================
func run(opt options) error {
localRoot, err := filepath.Abs(opt.local)
if err != nil {
@@ -139,7 +112,7 @@ func run(opt options) error {
}
fmt.Printf("本地目录 : %s\n", localRoot)
fmt.Printf("远程目录 : %s@%s:%s:%s\n", opt.user, opt.host, opt.port, opt.dir) // ← 输出带端口
fmt.Printf("远程目录 : %s@%s:%s:%s\n", opt.user, opt.host, opt.port, opt.dir)
client, err := dial(opt, localRoot)
if err != nil {
@@ -147,7 +120,6 @@ func run(opt options) error {
}
defer client.Close()
// 只执行远程命令(不比对、不上传)
if strings.TrimSpace(opt.execCmd) != "" {
fmt.Printf("\n[执行] %s\n", opt.execCmd)
out, xerr := runRemote(client, opt.execCmd)
@@ -161,21 +133,18 @@ func run(opt options) error {
return nil
}
// 1. 远端清单
remote, err := remoteInventory(client, opt.dir)
if err != nil {
return err
}
fmt.Printf("远端文件 : %d 个\n", len(remote))
// 2. 本地清单
local, err := localInventory(localRoot, excludeDirs, excludeFiles)
if err != nil {
return err
}
fmt.Printf("本地文件 : %d 个(已排除日志 / 可执行文件等)\n", len(local))
// 3. 比对
var changed, added []string
remoteOnly := make([]string, 0)
for rel, lh := range local {
@@ -229,13 +198,11 @@ func run(opt options) error {
return errCancelled
}
// 4. 上传
if len(toUpload) > 0 {
fmt.Printf("\n[上传] 打包 %d 个文件并传输...\n", len(toUpload))
if err := upload(client, opt, localRoot, toUpload); err != nil {
return err
}
// 5. 复核
fmt.Println("[复核] 重新读取远端指纹...")
after, err := remoteInventory(client, opt.dir)
if err != nil {
@@ -261,7 +228,6 @@ func run(opt options) error {
fmt.Printf("[复核] %d 个文件指纹一致 ✓\n", len(toUpload))
}
// 6. 删除远端多余文件
if opt.del && len(remoteOnly) > 0 {
fmt.Printf("\n[删除] 清理远端 %d 个多余文件...\n", len(remoteOnly))
if err := removeRemote(client, opt.dir, remoteOnly); err != nil {
@@ -269,7 +235,6 @@ func run(opt options) error {
}
}
// 7. 重启
if strings.TrimSpace(opt.restart) != "" {
fmt.Printf("\n[重启] 执行: %s\n", opt.restart)
out, err := runRemote(client, opt.restart)
@@ -288,15 +253,12 @@ func run(opt options) error {
return nil
}
// ============================ 文件清单 ============================
type fileInfo struct {
MD5 string
Size int64
Path string
}
// localInventory 遍历本地目录,计算 MD5
func localInventory(root string, excludeDirs, excludeFiles []string) (map[string]fileInfo, error) {
out := make(map[string]fileInfo)
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
@@ -319,7 +281,7 @@ func localInventory(root string, excludeDirs, excludeFiles []string) (map[string
return nil
}
if !info.Mode().IsRegular() {
return nil // 跳过符号链接 / 设备文件等
return nil
}
if matchAny(name, excludeFiles) {
return nil
@@ -334,11 +296,9 @@ func localInventory(root string, excludeDirs, excludeFiles []string) (map[string
return out, err
}
// remoteInventory 远端 md5sum 清单
func remoteInventory(client *ssh.Client, dir string) (map[string]fileInfo, error) {
res := make(map[string]fileInfo)
// 目录不存在时按空目录处理(上传阶段会创建)
if out, err := runRemote(client, fmt.Sprintf("[ -d %s ] && echo yes || echo no", shQuote(dir))); err == nil {
if !strings.Contains(out, "yes") {
fmt.Printf("[提示] 远端目录 %s 不存在,将新建\n", dir)
@@ -356,7 +316,6 @@ func remoteInventory(client *ssh.Client, dir string) (map[string]fileInfo, error
if strings.TrimSpace(line) == "" {
continue
}
// 格式: <md5> <path>
idx := strings.Index(line, " ")
if idx < 0 {
continue
@@ -389,7 +348,6 @@ func fileMD5(path string) (string, int64, error) {
return hex.EncodeToString(h.Sum(nil)), size, nil
}
// matchAny 名称是否命中排除规则(支持 * 通配)
func matchAny(name string, patterns []string) bool {
for _, p := range patterns {
if p == name {
@@ -402,7 +360,6 @@ func matchAny(name string, patterns []string) bool {
return false
}
// printList 打印文件清单(最多 20 条,避免刷屏)
func printList(mark string, files []string) {
const maxShow = 20
for i, f := range files {
@@ -414,16 +371,12 @@ func printList(mark string, files []string) {
}
}
// ============================ 上传 ============================
// upload 把差异文件打成 tar 流,通过 SSH 管道在远端解开
func upload(client *ssh.Client, opt options, localRoot string, files []string) error {
buf, err := buildTar(localRoot, files)
if err != nil {
return err
}
// 远端目录不存在时先创建(tar 解包要求目标目录已存在)
if out, merr := runRemote(client, fmt.Sprintf("mkdir -p %s", shQuote(opt.dir))); merr != nil {
return fmt.Errorf("创建远端目录失败: %w(%s)", merr, strings.TrimSpace(out))
}
@@ -444,7 +397,6 @@ func upload(client *ssh.Client, opt options, localRoot string, files []string) e
if err != nil {
return err
}
// 远端解包(tar 会自动创建缺失的目录)
if err := session.Start(fmt.Sprintf("tar -xf - -C %s", shQuote(opt.dir))); err != nil {
return err
}
@@ -457,14 +409,12 @@ func upload(client *ssh.Client, opt options, localRoot string, files []string) e
return fmt.Errorf("远端解包失败: %w(stderr: %s stdout: %s)", err, strings.TrimSpace(stderr.String()), strings.TrimSpace(string(out)))
}
// 属主对齐目标目录(服务器上多为 www:www,避免解包后变成 root:root)
if err := alignOwner(client, opt.dir, files); err != nil {
fmt.Printf("[提示] 属主修正跳过: %v\n", err)
}
return nil
}
// alignOwner 把上传文件的属主改成目标目录的属主
func alignOwner(client *ssh.Client, dir string, files []string) error {
if len(files) == 0 {
return nil
@@ -482,7 +432,6 @@ func alignOwner(client *ssh.Client, dir string, files []string) error {
return nil
}
// buildTar 生成待上传文件的 tar 包(含目录条目,保证远端目录结构存在)
func buildTar(localRoot string, files []string) ([]byte, error) {
dirs := make(map[string]bool)
for _, rel := range files {
@@ -540,8 +489,6 @@ func buildTar(localRoot string, files []string) ([]byte, error) {
return buf.Bytes(), nil
}
// fileMode 归一化文件权限:脚本可执行,其它一律 0644
// (Windows 本地读到的权限恒为 0666,直接带上会让服务器上的文件变成人人可写)
func fileMode(rel string) int64 {
switch strings.ToLower(filepath.Ext(rel)) {
case ".sh", ".bash", ".py", ".pl", ".rb":
@@ -550,7 +497,6 @@ func fileMode(rel string) int64 {
return 0o644
}
// removeRemote 删除远端多余文件
func removeRemote(client *ssh.Client, dir string, files []string) error {
for _, rel := range files {
cmd := fmt.Sprintf("rm -f -- %s", shQuote(strings.TrimRight(dir, "/")+"/"+rel))
@@ -561,8 +507,6 @@ func removeRemote(client *ssh.Client, dir string, files []string) error {
return nil
}
// ============================ SSH ============================
func dial(opt options, localRoot string) (*ssh.Client, error) {
var auth []ssh.AuthMethod
if opt.keyFile != "" {
@@ -586,16 +530,47 @@ func dial(opt options, localRoot string) (*ssh.Client, error) {
Timeout: 20 * time.Second,
}
// ← 关键:用 net.JoinHostPort 支持自定义端口(同时兼容 IPv6)
addr := net.JoinHostPort(opt.host, opt.port)
client, err := ssh.Dial("tcp", addr, cfg)
if err != nil {
return nil, fmt.Errorf("连接服务器失败(%s): %w", addr, err)
const maxAttempts = 4
var lastErr error
for attempt := 1; attempt <= maxAttempts; attempt++ {
client, err := ssh.Dial("tcp", addr, cfg)
if err == nil {
return client, nil
}
lastErr = err
if !isTransientDialError(err) || attempt == maxAttempts {
break
}
wait := time.Duration(attempt) * 2 * time.Second
fmt.Printf("[重试] 第 %d 次连接 %s 失败(%v),%s后重试…\n", attempt, addr, err, wait)
time.Sleep(wait)
}
return client, nil
return nil, fmt.Errorf("连接服务器失败(%s): %w", addr, lastErr)
}
func isTransientDialError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
for _, k := range []string{"unable to authenticate", "no supported methods", "主机密钥已变化"} {
if strings.Contains(msg, k) {
return false
}
}
for _, k := range []string{
"wsarecv", "wsasend", "forcibly closed", "connection reset", "broken pipe",
"i/o timeout", "connection refused", "unexpected eof", "handshake failed",
} {
if strings.Contains(msg, k) {
return true
}
}
return false
}
// hostKeyChecker 首次连接记录指纹,之后变化则拒绝连接(防止服务器被替换)
func hostKeyChecker(localRoot string) ssh.HostKeyCallback {
store := filepath.Join(localRoot, ".deploy_known_hosts")
known := map[string]string{}
@@ -619,7 +594,6 @@ func hostKeyChecker(localRoot string) ssh.HostKeyCallback {
}
}
// runRemote 执行远程命令并返回输出
func runRemote(client *ssh.Client, cmd string) (string, error) {
session, err := client.NewSession()
if err != nil {
@@ -636,14 +610,10 @@ func runRemote(client *ssh.Client, cmd string) (string, error) {
return out.String(), nil
}
// ============================ 辅助 ============================
// shQuote 单引号包裹(内部单引号转义),避免命令注入与路径空格问题
func shQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// confirm 交互确认
func confirm(prompt string) bool {
fmt.Printf("%s [y/N]: ", prompt)
var answer string