修复SSH公钥部署脚本并更新进度

This commit is contained in:
xuans committed 2026-09-30 16:09:45 +08:00
1 parent 58e5e52e53
commit 9af39b071e
5 files changed
+54 -9

No files matched your search

+13 -9
View File
@@ -351,15 +351,7 @@ func (c *sshClientAdapter) InstallAuthorizedKey(ctx context.Context, publicKey s
return fmt.Errorf("SSH 公钥格式无效:%w", err)
}
encoded := base64.StdEncoding.EncodeToString(ssh.MarshalAuthorizedKey(key))
script := fmt.Sprintf(`set -eu
umask 077
install -d -m 700 "$HOME/.ssh"
touch "$HOME/.ssh/authorized_keys"
chmod 600 "$HOME/.ssh/authorized_keys"
decoded="$(printf '%s' '%s' | base64 -d)"
if ! grep -Fqx -- "$decoded" "$HOME/.ssh/authorized_keys"; then
printf '%%s\\n' "$decoded" >> "$HOME/.ssh/authorized_keys"
fi`, "%s", encoded)
script := authorizedKeyInstallScript(encoded)
result, err := c.Run(ctx, []string{"sh", "-c", script})
if err != nil {
return fmt.Errorf("部署 SSH 公钥失败:%w", err)
@@ -369,6 +361,18 @@ fi`, "%s", encoded)
}
return nil
}
func authorizedKeyInstallScript(encoded string) string {
return fmt.Sprintf(`set -eu
umask 077
install -d -m 700 "$HOME/.ssh"
touch "$HOME/.ssh/authorized_keys"
chmod 600 "$HOME/.ssh/authorized_keys"
decoded="$(printf '%%s' '%s' | base64 -d)"
if ! grep -Fqx -- "$decoded" "$HOME/.ssh/authorized_keys"; then
printf '%%s\n' "$decoded" >> "$HOME/.ssh/authorized_keys"
fi`, encoded)
}
func (c *sshClientAdapter) Run(ctx context.Context, command []string) (CommandResult, error) {
if len(command) == 0 {
return CommandResult{}, errors.New("远程命令不能为空")
+13
View File
@@ -66,3 +66,16 @@ func TestJoinShellArgsQuotesArguments(t *testing.T) {
t.Fatalf("远程命令参数未正确转义:%s", joined)
}
}
func TestAuthorizedKeyInstallScriptUsesRealNewline(t *testing.T) {
script := authorizedKeyInstallScript("encoded-public-key")
if !strings.Contains(script, "printf '%s' 'encoded-public-key'") {
t.Fatalf("authorized key payload was not inserted safely: %s", script)
}
if !strings.Contains(script, "printf '%s\\n'") {
t.Fatalf("authorized key should be terminated by a real newline: %s", script)
}
if strings.Contains(script, "printf '%s\\\\n'") {
t.Fatalf("authorized key script still writes a literal backslash-n: %s", script)
}
}
+2
View File
@@ -971,6 +971,7 @@ func (s *Server) provisionServerSSHKey(ctx context.Context, item deployment.Serv
}
publicKey, err := s.sshKeys.AuthorizedPublicKey(ctx, item.PrivateKeyRef)
if err != nil {
s.logSSHProvisionFailure("authorized_public_key", item, err)
item.SSHKeyStatus = deployment.SSHKeyStatusFailed
item.SSHKeyError = "自动部署 SSH 公钥失败"
return item, err
@@ -992,6 +993,7 @@ func (s *Server) provisionServerSSHKey(ctx context.Context, item deployment.Serv
return item, err
}
if err := passwordClient.Close(); err != nil {
s.logSSHProvisionFailure("password_close", item, err)
item.SSHKeyStatus = deployment.SSHKeyStatusFailed
item.SSHKeyError = "自动部署 SSH 公钥失败"
return item, err