mysql数据库的备份及免密码上传

主要利用了mysqldump和sshpass进行备份和免密上传

 

以下是代码实现:

#!/bin/bash

#该脚本放在主服务器运行

#从服务器账号密码ip
remotehost="xxxxxxxxxx"  #远程主机IP
passwd="xxxxxxxx"      #远程主机密码
user="root"                #远程主机账号

localbackdir=/root/backupdir
remotebackdir=/root/backupdir
curdate=`date +"%Y-%m-%d"`
django_sql=$curdate"-django.sql"
vpnmaintenance_sql=$curdate"-vpn-maintenance.sql

if [ ! -d $localbackdir ];then
echo "test"
echo "本地备份目录不存在,将创建!"
mkdir $localbackdir
docker exec -it mysql mysqldump -u root -p"_VPN3211" django >$localbackdir/$django_sql
docker exec -it mysql mysqldump -u root -p"_VPN3211" vpn-maintenance >$localbackdir/$vpnmaintenance_sql
echo -e "\033[31m 以下是备份内容 \033[0m"
ls -lh $localbackdir
else

echo "本地备份目录存在,即将备份!"
echo `date`

#备份数据库
docker exec -it mysql mysqldump -u root -p"_VPN3211" django >$localbackdir/$django_sql
docker exec -it mysql mysqldump -u root -p"_VPN3211" vpn-maintenance >$localbackdir/$vpnmaintenance_sql
echo -e "\033[31m 以下是备份内容 \033[0m"
ls -lh $localbackdir

#echo $?
fi

#判断远程主机目录是否存在
result=`sshpass -p $passwd ssh $user@$remotehost "[ -d $remotebackdir ]"`
if [ $? == 0 ];then
echo "远程备份目录存在,将直接备份!"
sshpass -p$passwd scp $localbackdir/$django_sql $user@$remotehost:$remotebackdir/$django_sql
sshpass -p$passwd scp $localbackdir/$vpnmaintenance_sql $user@$remotehost:$remotebackdir/$vpnmaintenance_sql
echo -e "\033[31m 以下是备份内容 \033[0m"
sshpass -p$passwd ssh $user@$remotehost ls -lh $remotebackdir
else
echo "$remotebackdir 远程备份目录不存在,将创建!"
sshpass -p$passwd ssh $user@$remotehost mkdir $remotebackdir
sshpass -p$passwd scp $localbackdir/$django_sql $user@$remotehost:$remotebackdir/$django_sql
sshpass -p$passwd scp $localbackdir/$vpnmaintenance_sql $user@$remotehost:$remotebackdir/$vpnmaintenance_sql
sshpass -p$passwd ssh $user@$remotehost ls -lh $remotebackdir
fi

 

posted @ 2019-04-16 18:02  菜鸟的日记  阅读(854)  评论(0编辑  收藏  举报