Remote ssh server in shell, execute script on server
Background : Execute pssh in shell script A, execute the script A, the process of the script A will always be stuck
Reason : pssh is a tool for executing commands on a Linux terminal in batches. After it is executed, it needs to occupy the input and output of the terminal to print the execution results. Script A itself is a process, and it also needs to occupy the input and output of the terminal to print the execution of pssh. As a result, a deadlock problem occurs, causing the process of script A to be stuck
Solution 1: Use of nohup
Use nohup将pssh挂到后台执行
, that is, form a subprocess, so that script A and pssh will not seize input and output at the same time. (allip is a file whose content is the server ip that requires remote access)
#脚本作用:去到每台服务器上打印“你的大爸爸”
#!/bin/bash
echo "我来了哦"
nohup pssh -h allip -i "echo '你的大爸爸'" > pssh.txt
cat pssh.txt
#执行结果将重定向到pssh.txt文件中,但为了能够即时显示出来,所以添加了cat pssh.txt
#"echo '你的大爸爸'"也可以替换为其他命令,只是执行后的返回信息还是会打印到pssh.txt中
#执行结果:
[root@24-78 ~]# ./pssh_shell.sh
我来了哦
nohup: ignoring input and redirecting stderr to stdout
[1] 14:22:24 [SUCCESS] 10.10.24.81
你的大爸爸
[2] 14:22:24 [SUCCESS] 10.10.24.80
你的大爸爸
[3] 14:22:24 [SUCCESS] 10.10.24.84
你的大爸爸
[4] 14:22:24 [SUCCESS] 10.10.24.82
你的大爸爸
[5] 14:22:24 [SUCCESS] 10.10.24.83
你的大爸爸
[6] 14:22:25 [SUCCESS] 10.10.24.78
你的大爸爸
[7] 14:22:25 [SUCCESS] 10.10.24.79
你的大爸爸
[root@24-78 ~]#
Workaround 2 : Output Redirection
The content of remote execution is between "<< EOF " and "EOF", and the operation on the remote machine is located in it. Points to note:
- << EOF, after ssh until the end of the content such as EOF, EOF can be modified to other characters at will.
- The purpose of redirection is not to display remote output, so that it does not preempt input and output
- Before the end, add exit to exit the remote node
#脚本作用:去到每台服务器,执行服务器上家目录下的test.sh脚本
#!/bin/bash
IPW=$1
for i in $(cat $IPW)
do
echo "${i}开始冲啊";
ssh root@${i} > /dev/null 2>&1 << EOF
./test.sh
exit
EOF
echo done!
done
#执行结果
[root@24-78 ~]# ./open_test.sh allip
10.10.24.78开始冲啊
done!
10.10.24.79开始冲啊
done!
10.10.24.80开始冲啊
done!
10.10.24.81开始冲啊
done!
10.10.24.82开始冲啊
done!
10.10.24.83开始冲啊
done!
10.10.24.84开始冲啊
done!
[root@24-78 ~]#
#检验是否执行
#去到24.79的服务器上查看,24.79服务器上的test.sh脚本的作用是生成以当前时间命名的文件夹;
#结果如下
[root@24-79 ~]# ls
2021-09-16_1309 2021-09-16_1409 anaconda-ks.cfg change_hostname.sh test.sh
References:
https://blog.csdn.net/w_y_x_y/article/details/109774463
https://blog.csdn.net/xiaoxiaoonvwu/article/details/70742115