Linux 写一个shell脚本ssh到远程机器并执行命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13928116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
write a shell script to ssh to a remote machine and execute commands
提问by Balanivash
I have two questions:
我有两个问题:
- 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?
- When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
- 有多个远程 linux 机器,我需要编写一个 shell 脚本,该脚本将在每台机器上执行相同的命令集。(包括一些 sudo 操作)。这如何使用 shell 脚本来完成?
- ssh到远程机器时,提示RSA指纹认证时如何处理。
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.
远程机器是运行时创建的虚拟机,我只有它们的 IP。所以,我不能事先在这些机器中放置一个脚本文件并从我的机器上执行它们。
采纳答案by Andreas Fester
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?
有多个远程 linux 机器,我需要编写一个 shell 脚本,该脚本将在每台机器上执行相同的命令集。(包括一些 sudo 操作)。这如何使用 shell 脚本来完成?
You can do this with ssh, for example:
您可以使用 ssh 执行此操作,例如:
#!/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.
ssh到远程机器时,提示RSA指纹认证时如何处理。
You can add the StrictHostKeyChecking=no
option to ssh:
您可以将StrictHostKeyChecking=no
选项添加到 ssh:
ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"
This will disable the host key checkand 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
.
这将禁用主机密钥检查并自动将主机密钥添加到已知主机列表中。如果您不想将主机添加到已知主机文件中,请添加选项-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.
请注意,这会禁用某些安全检查,例如防止中间人攻击。因此,它不应应用于安全敏感的环境中。
回答by rai.skumar
You can follow this approach :
你可以按照这种方法:
- Connect to remote machine using Expect Script. If your machine doesn't support expect you can download the same. Writing Expect script is very easy (google to get help on this)
- Put all the action which needs to be performed on remote server in a shell script.
- Invoke remote shell script from expect script once login is successful.
- 使用Expect Script连接到远程机器。如果您的机器不支持expect,您可以下载相同的。编写 Expect 脚本非常简单(谷歌获得这方面的帮助)
- 将所有需要在远程服务器上执行的操作放在一个 shell 脚本中。
- 登录成功后,从expect 脚本调用远程shell 脚本。
回答by DigitalRoss
There are a number of ways to handle this.
有很多方法可以处理这个问题。
My favorite way is to install http://pamsshagentauth.sourceforge.net/on the remote systems and also your own public key. (Figure out a way to get these installed on the VM, somehow you got an entire Unix system installed, what's a couple more files?)
我最喜欢的方法是在远程系统上安装http://pamsshagentauth.sourceforge.net/以及您自己的公钥。(想办法在虚拟机上安装这些文件,不知何故你安装了整个 Unix 系统,还有几个文件?)
With your ssh agent forwarded, you can now log in to every system without a password.
转发您的 ssh 代理后,您现在无需密码即可登录到每个系统。
And even better, that pam module will authenticate for sudo with your ssh key pair so you can run with root (or any other user's) rights as needed.
更好的是,该 pam 模块将使用您的 ssh 密钥对对 sudo 进行身份验证,因此您可以根据需要使用 root(或任何其他用户的)权限运行。
You don't need to worry about the host key interaction. If the input is not a terminal then ssh will just limit your ability to forward agents and authenticate with passwords.
您无需担心主机密钥交互。如果输入不是终端,那么 ssh 只会限制您转发代理和使用密码进行身份验证的能力。
You should also look into packages like Capistrano.Definitely look around that site; it has an introduction to remote scripting.
您还应该查看像 Capistrano 这样的软件包。一定要环顾那个网站;它介绍了远程脚本。
Individual script lines might look something like this:
单个脚本行可能如下所示:
ssh remote-system-name command arguments ... # so, for exmaple,
ssh target.mycorp.net sudo puppet apply
回答by salva
If you are able to write Perl code, then you should consider using Net::OpenSSH::Parallel.
如果您能够编写 Perl 代码,那么您应该考虑使用Net::OpenSSH::Parallel。
You would be able to describe the actions that have to be run in every host in a declarative manner and the module will take care of all the scary details. Running commands through sudo
is also supported.
您将能够以声明方式描述必须在每个主机中运行的操作,并且该模块将处理所有可怕的细节。sudo
还支持通过运行命令。
回答by Arjun G Perambra
Install sshpass using, apt-get install sshpass
then edit the script and put your linux machines IPs, usernames and password in respective order. After that run that script. Thats it ! This script will install VLC in all systems.
使用 sshpass 安装, apt-get install sshpass
然后编辑脚本并按各自的顺序放置您的 linux 机器 IP、用户名和密码。之后运行该脚本。就是这样 !此脚本将在所有系统中安装 VLC。
#!/bin/bash
SCRIPT="cd Desktop; pwd; echo -e 'PASSWORD' | sudo -S apt-get install vlc"
HOSTS=("192.168.1.121" "192.168.1.122" "192.168.1.123")
USERNAMES=("username1" "username2" "username3")
PASSWORDS=("password1" "password2" "password3")
for i in ${!HOSTS[*]} ; do
echo ${HOSTS[i]}
SCR=${SCRIPT/PASSWORD/${PASSWORDS[i]}}
sshpass -p ${PASSWORDS[i]} ssh -l ${USERNAMES[i]} ${HOSTS[i]} "${SCR}"
done
回答by Fibo
For this kind of tasks, I repeatedly use Ansiblewhich allows to duplicate coherently bash scripts in several containets or VM. Ansible (more precisely Red Hat) now has an additional web interface AWXwhich is the open-source edition of their commercial Tower.
对于此类任务,我反复使用Ansible,它允许在多个容器或 VM 中一致地复制 bash 脚本。Ansible(更准确地说是Red Hat)现在有一个额外的 Web 界面AWX,这是他们商业 Tower 的开源版本。
Ansible: https://www.ansible.com/
AWX:https://github.com/ansible/awx
Ansible Tower: commercial product, you will probably fist explore the free open-source AWX, rather than the 15days free-trail of Tower
Ansible:https
:
//www.ansible.com/ AWX:https: //github.com/ansible/awx
Ansible Tower:商业产品,你可能会首先探索免费的开源 AWX,而不是 15days free-trail塔之
回答by Viraj Wadate
This work for me.
这对我有用。
Syntax : ssh -i pemfile.pem user_name@ip_address 'command_1 ; command 2; command 3'
语法:ssh -i pemfile.pem user_name@ip_address 'command_1 ; 命令 2; 命令 3'
#! /bin/bash
echo "########### connecting to server and run commands in sequence ###########"
ssh -i ~/.ssh/ec2_instance.pem ubuntu@ip_address 'touch a.txt; touch b.txt; sudo systemctl status tomcat.service'
回答by Skanda Shastry
There is are multiple ways to execute the commands or script in the multiple remote Linux machines.
One simple & easiest way is via pssh (parallel ssh program)
pssh: is a program for executing ssh in parallel on a number of hosts. It provides features such as sending input to all of the processes, passing a password to ssh, saving the output to files, and timing out.
有多种方式可以在多台远程 Linux 机器上执行命令或脚本。一种简单且最简单的方法是通过pssh(并行 ssh 程序)
pssh:是一种用于在多个主机上并行执行 ssh 的程序。它提供了诸如向所有进程发送输入、将密码传递给 ssh、将输出保存到文件和超时等功能。
Example & Usage:
Connect to host1 and host2, and print "hello, world" from each:
示例和用法:
连接到 host1 和 host2,并从每个打印“hello, world”:
pssh -i -H "host1 host2" echo "hello, world"
Run commands via a script on multiple servers:
在多个服务器上通过脚本运行命令:
pssh -h hosts.txt -P -I<./commands.sh
Usage & run a command without checking or saving host keys:
使用和运行命令而不检查或保存主机密钥:
pssh -h hostname_ip.txt -x '-q -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes' -i 'uptime; hostname -f'
If the file hosts.txt has a large number of entries, say 100, then the parallelism option may also be set to 100 to ensure that the commands are run concurrently:
如果文件 hosts.txt 有大量条目,比如 100,那么并行度选项也可以设置为 100 以确保命令并发运行:
pssh -i -h hosts.txt -p 100 -t 0 sleep 10000
Options:
-I:Read input and sends to each ssh process.
-P:Tells pssh to display output as it arrives.
-h:Reads the host's file.
-H :[user@]host[:port] for single-host.
-i:Display standard output and standard error as each host completes
-x args:Passes extra SSH command-line arguments
-o option:Can be used to give options in the format used in the configuration file.(/etc/ssh/ssh_config) (~/.ssh/config)
-p parallelism:Use the given number as the maximum number of concurrent connections
-q Quiet mode:Causes most warning and diagnostic messages to be suppressed.
-t:Make connections time out after the given number of seconds. 0 means pssh will not timeout any connections
选项:
-I:读取输入并发送到每个 ssh 进程。
-P:告诉 pssh 在它到达时显示输出。
-h:读取主机的文件。
-H :[user@]host[:port] 用于单主机。
-i:在每个主机完成时显示标准输出和标准错误
-x args:传递额外的 SSH 命令行参数
-o 选项:可用于以配置文件中使用的格式提供选项。(/etc/ssh/ssh_config ) (~/.ssh/config)
-p 并行度:使用给定的数量作为最大并发连接数
-q 安静模式:导致大多数警告和诊断消息被抑制。
-t:在给定的秒数后使连接超时。0 表示 pssh 不会超时任何连接
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
ssh到远程机器时,提示RSA指纹认证时如何处理。
Disable the StrictHostKeyChecking to handle the RSA authentication prompt.
-o StrictHostKeyChecking=no
禁用 StrictHostKeyChecking 以处理 RSA 身份验证提示。
-o StrictHostKeyChecking=no
Source: man pssh
来源:人 pssh