[CmdletBinding()] param( [string] $Server = '218.93.190.75', [ValidatePattern('^[A-Za-z0-9._-]+$')] [string] $SshUser = 'root', [switch] $RunNow, [ValidatePattern('^\d{4}-\d{2}-\d{2}$')] [string] $Date ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) . (Join-Path $root 'scripts\deploy-auth.ps1') $target = "${SshUser}@${Server}" $remoteBase = '/opt/caiwuxitong/runtime/private/cmb-mail' $auth = Start-CaiwuDeploymentAuth -Server $Server -SshUser $SshUser try { & ssh @($auth.Options) $target "install -d -m 700 '$remoteBase' '$remoteBase/logs' '$remoteBase/state'" if ($LASTEXITCODE -ne 0) { throw '创建招商银行邮件运行目录失败' } & scp @($auth.Options) ` (Join-Path $PSScriptRoot 'fetch_daily.py') ` (Join-Path $PSScriptRoot 'run-server.sh') ` "${target}:$remoteBase/" if ($LASTEXITCODE -ne 0) { throw '上传招商银行邮件脚本失败' } $install = @' set -eu BASE_DIR="/opt/caiwuxitong/runtime/private/cmb-mail" SOURCE_CONFIG="/opt/caiwuxitong/runtime/private/wangshang-mail/accounts.json" chmod 700 "$BASE_DIR/run-server.sh" chmod 600 "$BASE_DIR/fetch_daily.py" python3 - "$SOURCE_CONFIG" "$BASE_DIR/config.json" <<'PY' import json import os import sys source = json.load(open(sys.argv[1], encoding="utf-8")) mail = dict(source.get("mail") or {}) if not mail.get("host") or not mail.get("username") or not mail.get("auth_code"): raise SystemExit("现有 163 邮箱配置不完整") config = { "sender": "95555@message.cmbchina.com", "subject": "招商银行企业交易明细", "mail": { "host": mail["host"], "port": int(mail.get("port", 993)), "username": mail["username"], "auth_code": mail["auth_code"], "search_grace_days": max(3, int(mail.get("search_grace_days", 2))), }, } temporary = sys.argv[2] + ".tmp" with open(temporary, "w", encoding="utf-8") as stream: json.dump(config, stream, ensure_ascii=False, indent=2) stream.write("\n") os.chmod(temporary, 0o600) os.replace(temporary, sys.argv[2]) PY cat > /etc/cron.d/caiwu-cmb-mail <<'CRON' CRON_TZ=Asia/Shanghai SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 10 2,3,4,5 * * * root /usr/bin/flock -n /run/caiwu-cmb-mail.lock /bin/sh /opt/caiwuxitong/runtime/private/cmb-mail/run-server.sh >> /opt/caiwuxitong/runtime/private/cmb-mail/cron.log 2>&1 CRON chmod 644 /etc/cron.d/caiwu-cmb-mail '@ & ssh @($auth.Options) $target $install if ($LASTEXITCODE -ne 0) { throw '安装招商银行邮件配置或定时任务失败' } if ($RunNow) { $arguments = if ([string]::IsNullOrWhiteSpace($Date)) { '' } else { " '$Date'" } & ssh @($auth.Options) $target ( "/usr/bin/flock -n /run/caiwu-cmb-mail.lock /bin/sh '$remoteBase/run-server.sh'" + $arguments ) if ($LASTEXITCODE -ne 0) { throw '立即执行招商银行邮件账单任务失败' } } } finally { Stop-CaiwuDeploymentAuth $auth } Write-Host "招商银行邮件账单任务已安装。每天 02:10、03:10、04:10、05:10 自动重试。"