我通过bash脚本维护了多个具有相同Web应用程序的服务器。命令基本上包括 ssh 和 scp ,并且每个服务器的命令都相同,只是服务器之间的IP,用户和端口不同。到目前为止,我编写了与服务器一样多的命令来维护同一脚本。这很好用,但是随着我开始要维护许多服务器,我宁愿在MySQL表中列出这些服务器,然后在我的bash脚本中使用此列表,因此II不需要在维护时更新所有这些服务器。新服务器进行维护。
目前,我无法以适当的方式从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表的数据批量执行 ssh 和 scp 命令?
答案 0 :(得分:1)
最后,我成功地对MySQL数据执行了批处理命令。根据从MySQL提取的行号,我构建了使用串联功能执行的命令。下面是我的脚本
#!/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;
答案 1 :(得分:0)
因为我是新来的所以我不能发表评论。
您是否尝试过在MySQL级联末尾放置\n
或&&
?
您还可以更改方法,将服务器和端口分配给变量,并循环这些变量以执行ssh
和scp
命令。例如
ips_and_ports=$($MYSQL -u"$USER" --batch -p"$PASSWORD" --skip-column-names -h"$HOST" -e "SELECT server_port, server_ip FROM extranet.server_ssh;" $DBNAME)
for $line in $ips_and_ports
do
OLDIFS=$IFS;
IFS=" "; # set the separator to the tab character (PS: this is 4 spaces, change accordingly )
for $el in $line
do
set -- $el; # separate each line by tab and assign the variables to $1, $2 ..
port=$1;
ip=$2;
scp -P 22 text.php user1@$ip:/var/www/html/site/ scp -P $port
done;
IFS=$OLDIFS; # put the separator back to it's original value
done;
我还没有测试代码,但我希望你能理解我的想法!
祝你好运
有关link中IFS和OLDIFS的更多信息