vis*_*hnu 4 ssh shell-script parallelism gnu-parallel
我需要在远程服务器上运行本地脚本。运行脚本以并行运行很重要。
[ec2-user@ip-172-31-43-140 ~]$ cat hosts.txt
ec2-user@18.218.191.143
ec2-user@18.220.183.27
ec2-user@18.222.199.72
ec2-user@13.58.207.76
ec2-user@18.191.231.120
[ec2-user@ip-172-31-43-140 ~]$ cat hosts.txt | xargs -I {} ssh {} -T 'bash -s' < ./file.sh
ssh: Could not resolve hostname #!/bin/sh: Name or service not known
xargs: ssh: exited with status 255; aborting
[ec2-user@ip-172-31-43-140 ~]$
Run Code Online (Sandbox Code Playgroud)
这样做时我喜欢这种形式:
$ cat hosts.txt | xargs -n1 -P8 sh -c 'ssh -T "$1" bash -s < ./hello.bash' sh
Run Code Online (Sandbox Code Playgroud)
或者,{}
如果您需要它们:
$ cat hosts.txt | xargs -n1 -P8 -I{} sh -c 'ssh -T "$1" bash -s < ./hello.bash' sh {}
Run Code Online (Sandbox Code Playgroud)
$ cat hello.bash
#!/bin/bash
echo "hi from server: $(hostname)"
Run Code Online (Sandbox Code Playgroud)
ssh xargs
$ cat hosts.txt | xargs -n1 -P8 sh -c 'ssh -T "$1" bash -s < ./hello.bash' sh
hi from server: mulder.mydom.com
hi from server: skinner.mydom.com
hi from server: manny.mydom.com
Run Code Online (Sandbox Code Playgroud)
细节:
-n1 -P8
- 告诉xargs
将 1 个参数作为输入并运行 8 个实例ssh
sh -c 'ssh -T "$1"
-c "..."
$1
在这里传入,这是为了避免注入攻击。-T
禁用伪终端。$1
是正在输入的文件的内容cat
。bash -s < ./hello.bash'
- 将传递给的命令 ssh
sh
- 尾随sh
是传递给xargs
shell 以调用参数 #0 ( $0
) 的内容。