Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux SSH 免密登录与远程执行 Shell 命令实战

編輯:關於 Linux

通过 SSH 密钥对实现免密登录,配合 ssh user@host "command" 语法,即可在本地脚本中远程执行命令、部署应用、重载服务。本文记录密钥生成、分发、远程执行与自动化脚本示例。

一、生成 SSH 密钥对(本地机器 A)

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 ""

二、分发公钥至远程机器 B

# 方法 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 &"

五、Expect 自动化交互(需输入密码/确认的场景)

#!/usr/bin/expect
set timeout 30
spawn ssh user@192.168.56.2
expect "password:"
send "your_password\r"
interact

SSH 免密与远程执行示意图

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

Copyright © Windows教程網 All Rights Reserved