且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

编写Shell脚本以ssh到远程计算机并执行命令

更新时间:2022-12-23 09:50:55

有多台远程linux机器,我需要编写一个shell脚本,它将在每台机器上执行相同的命令集. (包括一些sudo操作).如何使用Shell脚本完成此操作?

There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?

您可以使用ssh进行此操作,例如:

You can do this with ssh, for example:

#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
    ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done

ssh'到远程计算机时,当提示进行RSA指纹认证时如何处理.

When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.

您可以将StrictHostKeyChecking=no选项添加到ssh:

You can add the StrictHostKeyChecking=no option to ssh:

ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"

这将禁用主机密钥检查,然后自动将主机密钥添加到已知主机列表中.如果您不想将主机添加到已知主机文件中,请添加选项-o UserKnownHostsFile=/dev/null.

This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null.

请注意,这会禁用某些安全检查,例如防止中间人攻击.因此,不应将其应用于对安全敏感的环境中.

Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.