首页 > 解决方案 > 使用mysql结果批量执行bash命令

问题描述

我通过 bash 脚本维护了几台具有相同 Web 应用程序的服务器。命令基本上包括sshscp,它们对于每个服务器都是相同的,只是服务器之间的 IP、用户和端口不同。到目前为止,我编写了与服务器一样多的命令以在同一脚本中维护。这很好用,但是当我开始有许多服务器要维护时,我更愿意在 MySQL 表中列出这些服务器,然后在我的 bash 脚本中使用这个列表,因此当我有时我不需要保持所有服务器更新要维护的新服务器。

目前,我无法以适当的方式从 MySQL 中提取数据,然后可以在 bash 脚本中执行这些数据。

我目前的方法是在查询中使用 CONCAT 函数,如下所示:

outputofquery=$($MYSQL -u"$USER" --batch -p"$PASSWORD" --skip-column-names -h"$HOST" -e "SELECT CONCAT('scp -P ', server_port, ' $file ', server_user, '@', server_ip, ':/var/www/html/site/') FROM server_ssh;" $DBNAME)
echo ${outputofquery%$'\t;'*}

给出以下结果:

scp -P 22 text.php user1@1.1.1.1:/var/www/html/site/ scp -P 12345 text.php user2@2.2.2.2:/var/www/html/site/

MySQL 查询产生的每个命令都放在同一行,这意味着无法执行。

我想在查询中的site/之后添加一个分号,这样即使每个命令都在同一行上,它们也可以独立执行,但碰巧只有最后一个scp命令被执行,而之前的命令被忽略。

您能否告诉我如何使用来自 MySQL 表的数据批量执行sshscp命令?

标签: mysqlbash

解决方案


最后,我成功地使用 MySQL 数据执行批处理命令。根据从 MySQL 中提取的行号,我构建了使用 concatenate 函数执行的命令。下面是我的脚本

#!/bin/sh

HOST="localhost"
USER="root"
DBNAME="mydb"
PASSWORD="mypassord"
MYSQL="/Applications/XAMPP/bin/mysql"

file='text.php'
i=0;
command='';

ips_and_ports=$($MYSQL -u"$USER" -p"$PASSWORD" -h"$HOST" -BNe "SELECT server_port,server_user,server_ip FROM server_ssh;" $DBNAME)
for line in $ips_and_ports
do
    (( i++ )); #increment the line number

    if [ $(($i % 3)) -eq 1 ] #check if it is the first element of a line extracted from MySQL (server_port)
    then
        command="scp -P $line"; #initialize a new command to execute
    elif [ $(($i % 3)) -eq 2 ] #check if it is the second element of a line extracted from MySQL (server_user)
    then
        command+=" $file $line@"; #concatenate
    elif [ $(($i % 3)) -eq 0 ] #check if it is the third element of a line extracted from MySQL (server_ip)
    then
        command+="$line:/var/www/html/my_web_app/;"; #concatenate
        eval $command; #execute the command 
    fi
done;

推荐阅读