我需要在服务器列表上执行命令。例如,我想在所有负载均衡的应用程序服务器上的应用程序日志中搜索应用程序重新启动:
cd /var/logs/rest-cli-io/
xcmd grep restart '*log'
其中
xcmd
bash 函数是在多个服务器上执行 grep
命令。
我找到了一个解决方案,并且想知道其他人做了什么来解决这个需求。
这是我想出的
xcmd
bash 函数,我将其添加到 ~/.bashrc
:
xcmd() {
if [ "$2" == "" ]; then
echo "Usage: Specify command to execute on all app servers"
echo "Example: cd /var/log/rest-cli-io; xcmd egrep restart '*.log'"
else
#servers=(app-srv-01 app-srv-02 app-srv-03)
servers=($(cat /projects/app-servers/app-servers.txt | grep -v '#' | tr '\r\n' ' '))
host="$HOSTNAME"
command="$1"
args="${@:2}"
dir="$PWD"
for server in ${servers[@]}; do
echo "==========> $server: $command $args <=========="
if [[ $server == $host ]]; then
$command $args
else
ssh $server "cd $dir; $command $args"
fi
done
fi
}
说明:
servers
列表可以在函数中硬编码,或者从所有服务器可访问的文件中读取xcmd
在 servers
列表中的所有服务器上执行带参数的任意命令servers
列表中的计算机上,则在本地执行该命令,否则通过远程 ssh
命令执行运行ssh
执行,假设远程服务器配置为无密码登录示例:查找rest-cli-io应用程序的最新应用程序重启:
$ cd /var/log/rest-cli-io
$ xcmd grep restart 'access*.log' | sort | tail
access__2024-08-11_00.log:- 2024-08-10-03-55: rest-file-io app restart, listening on port 8070
access__2024-08-12_00.log:- 2024-08-11-03-54: rest-file-io app restart, listening on port 8070
access__2024-08-14_00.log:- 2024-08-13-03-55: rest-file-io app restart, listening on port 8070
access__2024-08-20_00.log:- 2024-08-19-03-55: rest-file-io app restart, listening on port 8070
access__2024-08-20_00.log:- 2024-08-19-11-15: rest-file-io app restart, listening on port 8070
access__2024-08-21_00.log:- 2024-08-20-03-55: rest-file-io app restart, listening on port 8070
access__2024-08-21_00.log:- 2024-08-20-18-07: rest-file-io app restart, listening on port 8070
==========> app-srv-01: grep restart access*.log <==========
==========> app-srv-02: grep restart access*.log <==========
==========> app-srv-03: grep restart access*.log <==========