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

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

本文介绍了写一个shell脚本ssh到远程机器并执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个问题:

  1. 有多个远程 linux 机器,我需要编写一个 shell 脚本,该脚本将在每台机器上执行相同的命令集.(包括一些 sudo 操作).这如何使用 shell 脚本来完成?
  2. ssh 到远程机器时,提示进行 RSA 指纹认证时如何处理.

远程机器是运行时创建的虚拟机,我只有它们的 IP.所以,我不能事先在那些机器上放置一个脚本文件并从我的机器上执行它们.

解决方案

您可以使用 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.

解决方案

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

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.

这篇关于写一个shell脚本ssh到远程机器并执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:36