且构网

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

写一个shell脚本ssh到远程机器并执行命令

更新时间:2023-11-11 20:15:34

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

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

#!/bin/bash用户名=某个用户HOSTS="host1 host2 host3"脚本=密码;ls"对于 ${HOSTS} 中的 HOSTNAME ;做ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"完毕

ssh 到远程机器时,提示需要进行 RSA 指纹认证时如何处理.

您可以在 ssh 中添加 StrictHostKeyChecking=no 选项:

ssh -o StrictHostKeyChecking=no -l 用户名主机名 "pwd; ls"

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

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

I have two questions:

  1. 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?
  2. When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.

The remote machines are VMs created on the run and I just have their IPs. So, I cant place a script file beforehand in those machines and execute them from my machine.

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?

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

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

You can add the StrictHostKeyChecking=no option to ssh:

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

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.