编写Shell脚本以ssh到远程计算机并执行命令 [英] write a shell script to ssh to a remote machine and execute commands

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

问题描述

我有两个问题:

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

远程计算机是在运行中创建的VM,我只有它们的IP.因此,我无法事先在这些计算机中放置脚本文件并从我的计算机中执行它们.

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.

推荐答案

有多台远程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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆