ssh作为一款被广泛使用的远程连接工具以其高效和安全性所为人们著称。但其实ssh表示我能做的事情有很多,这里介绍其中一个基本功能,在不进入shell交互界面的情况下远程执行某些命令。

如果我们要查看一下某台主机的进程情况,是不是必须要登录到目标主机上才能执行 df 命令呢?当然不是的,我们可以使用 ssh 命令在远程的主机上执行 df 命令,然后直接把结果显示出来。整个过程就像是在本地执行了一条命令一样:

语法

ssh [user@]hostname [command]

基础的操作语法如上,只是我们平常执行时是不带后面的 command 的,所以也没有想到 ssh 还可以这么用,而实际上 ssh 作为一款老牌的连接工具是很强大的。

If command is specified, it is executed on the remote host instead of a login shell.

当指定了命令后,ssh 会只在远程主机上执行该命令并返回结果而不执行登录操作。

执行单条命令

当我们需要执行远程命令,但是并不想要登录到目标主机时,此时我们可以通过执行ssh命令来完成不登录到主机执行命令:

ssh root@localhost "ps -fe | grep java"

执行多条命令

如果我们有执行多条命令的需求,则可以通过分号分隔多条命令:

ssh root@localhost "ps -fe | grep java ; netstat -natp"

执行本地shell脚本

如果我们有执行脚本的需求,则可以输入重定向到文件即可:

ssh root@localhost < script.sh

在这种场景下,如果我们有对脚本输入参数的需求,则需要添加 -s 选项,如下:

ssh root@localhost 'bash -s' < script1.sh helloworld

理解起来也很简单,其实我们是执行了 bash命令,并且输入了对应的参数。

-s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This
option allows the positional parameters to be set when invoking an interactive shell.

如果指定了 -s 选项,或者在解析选项之后没有其他参数了,那么该命令会从读取标准输入。这个选项允许在发起交互式终端时设置对应参数。

执行远程shell脚本

远程的 shell 脚本执行方式和执行远端命令的方式是一致的,不同的是我们主要指定远程脚本所在的位置:

ssh root@localshot "/root/script/script1.sh"

应用1-拷贝本地 SSH 公钥到远程节点上

在 Windows CMD 命令下:

# 在 bash 中执行
cat ~/.ssh/id_rsa.pub | ssh root@remote01 "tee .ssh/authorized_keys"
# 在 CMD 中执行
type %USERPROFILE%\.ssh\id_rsa.pub | ssh root@remote01 "tee .ssh/authorized_keys"
# 在 PowerShell 中执行
gc $Env:USERPROFILE\.ssh\id_rsa.pub | ssh root@remote01 "tee .ssh/authorized_keys"

应用2:不使用 scp 命令而是使用 SSH 命令将远程文件拷贝到本地

# 将远程脚本复制到本地
ssh remote01 "cat ./build-mysql-docker.sh" > build-mysql-docker.sh
# 执行打印指定文件的行数
ssh remote01 "sed -n '1,100p' /root/logs/gc.log"