通过 SSH 密钥对实现免密登录,配合 ssh user@host "command" 语法,即可在本地脚本中远程执行命令、部署应用、重载服务。本文记录密钥生成、分发、远程执行与自动化脚本示例。
ssh-keygen -t ed25519 -C "admin@local" -f ~/.ssh/id_ed25519 -N ""
# 或 RSA 4096
# ssh-keygen -t rsa -b 4096 -C "admin@local" -f ~/.ssh/id_rsa -N ""
# 方法 1:ssh-copy-id(推荐)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@192.168.56.2
# 方法 2:手动追加
cat ~/.ssh/id_ed25519.pub | ssh user@192.168.56.2 "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
ssh user@192.168.56.2
# 应直接进入远程 Shell 无需输入密码
# 单条命令
ssh user@192.168.56.2 "systemctl reload nginx"
# 多条命令(分号分隔)
ssh user@192.168.56.2 "cd /opt/app && git pull && systemctl restart app"
# 执行本地脚本远程运行
ssh user@192.168.56.2 "bash -s" < ./deploy.sh
# 后台运行远程命令
ssh -f user@192.168.56.2 "nohup ./long_task.sh > /dev/null 2>&1 &"
#!/usr/bin/expect
set timeout 30
spawn ssh user@192.168.56.2
expect "password:"
send "your_password\r"
interact

建立 SSH 免密信任后,结合 ssh "command"、scp/rsync 与 ssh -f 后台执行,即可构建高效的远程自动化运维工作流。