Showing posts with label Script. Show all posts
Showing posts with label Script. Show all posts

August 25, 2016

MYSQL BAKUP USING SHELLS SCRIPTS



Kindly find the MYSQL shells scripts in given below.

-------------------------------------------------------------------------------------------------------

#! /bin/bash

# You are free to modify and distribute this code,
# so long as you keep my name and URL in it.

# your MySQL server's name
SERVER=10.0.0.125

# directory to backup to
BACKDIR=/root/mysqlbackup/

# date format that is appended to filename
DATE=`date +'%m-%d-%Y'`

#----------------------MySQL Settings--------------------#

# your MySQL server's location (IP address is best)
HOST="10.0.0.125"

# MySQL username
USER="root"

# MySQL password
PASS="xxxxx"

# List all of the MySQL databases that you want to backup in here, 
# each separated by a space
DBS="XXXX"

# set to 'y' if you want to backup all your databases. this will override
# the database selection above.
DUMPALL="n"


#----------------------Mail Settings--------------------#

# set to 'y' if you'd like to be emailed the backup (requires mutt)
MAIL=y

# email addresses to send backups to, separated by a space
EMAILS="suppport@magicalbinary.com"

SUBJECT="MySQL backup on $SERVER ($DATE)"

#----------------------FTP Settings--------------------#

# set "FTP=y" if you want to enable FTP backups
FTP=n

# FTP server settings; should be self-explanatory
FTPHOST="10.0.0.127"
FTPUSER="XXX"
FTPPASS="XXX"

# directory to backup to. if it doesn't exist, file will be uploaded to 
# first logged-in directory
FTPDIR="/home/value"

#-------------------Deletion Settings-------------------#

# delete old files?
DELETE=y

# how many days of backups do you want to keep?
DAYS=6

#----------------------End of Settings------------------#
# check of the backup directory exists
# if not, create it
if  [ -e $BACKDIR ]
then
    echo Backups directory already exists
else
    mkdir $BACKDIR
fi

if  [ $DUMPALL = "y" ]
then
    echo "Creating list of all your databases..."

    mysql -h$HOST -u$USER -p$PASS "dlr" "dlr"  > dbs_on_$SERVER.txt

    # redefine list of databases to be backed up
    DBS=`sed -e ':a;N;$!ba;s/\n/ /g' -e 's/Database //g' dbs_on_$SERVER.txt`
fi

echo "Backing up MySQL databases...$DBS"
read p1
for database in $DBS
do
    mysqldump -h$HOST -u$USER -p$PASS $database dlr > "$BACKDIR/$SERVER-mysqlbackup-$database-$DATE.sql"
    gzip -f -9 "$BACKDIR/$SERVER-mysqlbackup-$database-$DATE.sql"

# if you have the mail program 'mutt' installed on
done
# your server, this script will have mutt attach the backup
# and send it to the email addresses in $EMAILS

if  [ $MAIL = "y" ]
then
BODY="Your backup is ready, please check"
ATTACH=`for file in $BACKDIR/*$DATE.sql.gz; do echo -n "-a ${file} ";  done`

    echo "$BODY" | mutt -s "$SUBJECT" $ATTACH $EMAILS
        
    echo -e "Your backup has been emailed to you! \n"
fi

if  [ $FTP = "y" ]
then
echo "Initiating FTP connection..."
cd $BACKDIR
ATTACH=`for file in *$DATE.sql.gz; do echo -n -e "put ${file}\n"; done`

    ftp -nv <<EOF
    open $FTPHOST
    user $FTPUSER $FTPPASS
    cd $FTPDIR
    $ATTACH
    quit
EOF
echo -e  "FTP transfer complete! \n"
fi

if  [ $DELETE = "y" ]
then
    find $BACKDIR -name "*.sql.gz" -mtime $DAYS -exec rm {} \;

    if  [ $DAYS = "1" ]
    then
        echo "Yesterday's backup has been deleted."
    else
        echo "The backup from $DAYS days ago has been deleted."
    fi
fi

echo Your backup is complete!

August 13, 2016

using shell script to automate install VPS linux

Vì tính chất công việc, nên đôi khi mình phải setup khá nhiều VPS để dùng. Đặc biệt là các VPS linux, tuy nhiên chỉ cần setup Apache + PHP + mysql + phpMyAdmin là đủ cho 1 cuộc tình :smile:
Vì phải lặp đi lặp lại 1 mớ lệnh, mà mình thì cũng ko ưa terminal cho lắm :smile: nên đành viết cái bash để install. Tuy nhiên đời nó chả như mơ!

Chuẩn bị

VPS linux, mình toàn dùng CentOS 6 64bit
Bitvise tunnelier hoặc putty gì đấy tùy bạn

Viết bash

Đầu tiên cần liệt kê ra các câu lệnh sẽ phải dùng

yum update
echo y | yum install mysql mysql-devel mysql-server -y
/etc/init.d/mysqld start
/usr/bin/mysql_secure_installation
/etc/init.d/mysqld restart
echo y | yum install php-mbstring php-gd httpd-devel apxs php-mcrypt php-mysql pdo-mysql php-sqlite php-mcrypt php-soap
echo y | yum install php
service httpd restart
wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
echo y | yum install php-mcrypt

cd //var/www/html
wget https://files.phpmyadmin.net/phpMyAdmin/4.0.10.15/phpMyAdmin-4.0.10.15-all-languages.zip
echo y | yum install unzip
unzip phpMyAdmin-4.0.10.15-all-languages.zip
rm -rf phpMyAdmin-4.0.10.15-all-languages.zip
Để viết 1 file bash cực kì đơn giản, save mớ lệnh đó vào notepad rồi lưu dưới đuôi .sh là xong.

Khoan đã

Nếu bạn dùng trên linux thì có một chương trình/lệnh giúp convert line-ending từ Windows -> Linux đó là dos2unix, bạn chỉ cần dos2unix bash_script.sh là được, tuy nhiên mình dùng Windows. Vấn đề gặp phải đó là kí tự cuối mỗi dòng.
Với windows, với mỗi cuối dòng thì windows sẽ lưu thêm /r, vô tình làm cho các câu lệnh có cái thực hiện được, có cái không được!
Vì thế mình phải chuyển cách lưu lại, ở đây mình dùng Sublime Text, bạn chỉnh như sau:

Sau đó chịu khó xóa xuống dòng, và enter lại hoặc dùng cách nào đó để chuyển lại cái Line Endings thành Unix là xong :smile:
Để kiểm tra đã thành công chưa, khi chạy file bash bạn thêm -x vào là được.
dùng sublime mình set "default_line_ending" là "unix" thì không phải lo lắng cái ngắt dòng nữa.Ngoài ra mình ưa thích dùng editorconfig cho tất cả các project

Cách dùng

Chắc ai cũng biết nhỉ :smile: nhưng cũng nói sơ qua
B1: Upload file bash này lên vps
B2: Dùng SSH Shell cd đến nơi chứa file
B3: nhập lệnh
bash setup.sh
hoặc để kiểm tra xem có còn /r không thì gõ
bash -x setup.sh

Xong!
Mình note lại để sau này có quên thì có cái mà dùng :smile:

nguồn: http://kipalog.com/posts/Viet-bash-install-VPS

January 5, 2016

Script backup zimbra mail

##!/bin/bash
clear
echo Start time of the backup = $(date +%T)
before="$(date +%s)"
## Backup Format
FORMAT=tgz

## Backup location
ZBACKUP=/srv/backup/

## Folder name for backup and using date
DATE=`date +"%d%m%y"`

## Backup location separate by date
ZDUMPDIR=$ZBACKUP/$DATE

## zmmailbox location
ZMBOX=/opt/zimbra/bin/zmmailbox

### Backup Option ###

## Based on few day ago until today, example 7 days ago

#HARI=`date --date='7 days ago' +"%m/%d/%Y"`
#query="&query=after:$HARI"

if [ ! -d $ZDUMPDIR ]; then
        mkdir -p $ZDUMPDIR
fi

## Looping Account Zimbra
for account in `su - zimbra -c 'zmprov -l gaa | sort'`
do
echo "Processing mailbox $account backup..."
        $ZMBOX -z -m $account getRestURL "//?fmt=${FORMAT}$query" > $ZDUMPDIR/$account.${FORMAT}
done

echo "Zimbra Mailbox backup has been completed successfully."

echo "Sending files to backup all email accounts for Machine2 ..."
rsync -avH $ZBACKUP root@ipaddress:/backup/zimbra_backup_accounts
before2="$(date +%s)"
#
echo The process lasted = $(date +%T)
# Calculating time
after="$(date +%s)"
elapsed="$(expr $after - $before)"
hours=$(($elapsed / 3600))
elapsed=$(($elapsed - $hours * 3600))
minutes=$(($elapsed / 60))
seconds=$(($elapsed - $minutes * 60))
echo The complete backup lasted : "$hours hours $minutes minutes $seconds seconds"

December 23, 2015

Backup of Zimbra MailBox using zmmailbox

This is a short script I use to backup the Zimbra mailbox content for my users.
This has been used on a Zimbra Collaboration Server (ZCS Open Source Edition) 7.2 installation, but should work on earlier versions as well.
I use another script to backup the whole Zimbra installation, but that might be another blog post.

#!/bin/bash -x
# Backup of Zimbra mailboxes using zmmailbox
# Restore of mailbox should be performed using:
# /opt/zimbra/bin/zmmailbox -z -m user@host postRestURL -u https://HOST "//?fmt=tgz&resolve=skip" mailbox-name-date.tgz
BackupFolder="/backup/zimbra"
MailBox="user1 user2 user3 userN"
DateToday=`date -I`
for name in $MailBox
do
sudo -u zimbra /opt/zimbra/bin/zmmailbox -z -m $name@pario.no getRestURL "//?fmt=tgz" > mailbox-$name-$DateToday.tgz
done
The backup files are named mailbox-user1-20120802.tgz mailbox-user2-20120802.tgz …

Cold backup for the Open Source Edition of Zimbra

Today I’ve setup a cold backup routine to backup my Zimba installation running on my Debian (Etch) 4.0 server that is in full production now for my private domains. This is a slightly modified backup script for the Open Source Edition of Zimbra from the Zimbra Wiki. Please note that the script does a full backup every time it’s being run!
#!/bin/bash

# Zimbra Backup Script
# Requires sftp to run
# This script is intended to run from the crontab as root
# Free to use and free of any warranty!  Daniel W. Martin, 9 Sept 2007

# Live sync before stopping Zimbra to minimize sync time with the services down
# Comment out the following line if you want to try single cold-sync only
rsync -avHK --delete /opt/zimbra/ /backup/zimbra

# which is the same as: /opt/zimbra /backup
# Including --delete option gets rid of files in the dest folder that don't exist at the src
# this prevents logfile/extraneous bloat from building up overtime.

# Stop Zimbra Services
sudo -u zimbra /opt/zimbra/bin/zmcontrol stop
sleep 40

# Sync to backup directory
rsync -avHK --delete /opt/zimbra/ /backup/zimbra

# Restart Zimbra Services
sudo -u zimbra /opt/zimbra/bin/zmcontrol start

# Create a txt file in the backup directory that'll contain the current Zimbra
# server version. Handy for knowing what version of Zimbra a backup can be restored to.
sudo -u zimbra zmcontrol -v > /backup/zimbra/conf/zimbra_version.txt
# or examine your /opt/zimbra/.install_history

# Create archive of backed-up directory for offsite transfer
# cd /backup/zimbra
ZimbraVersion=zimbraBackup-zcs-5.0.1_GA_1902.DEBIAN4.0.20080109200914

tar -zcf /backup/$ZimbraVersion-$(date +"%Y-%m-%d").tgz -C /backup/zimbra .

# Transfer file to backup server using passwordless sftp
scp zimbraBackup-zcs-5.0.1_GA_1902.DEBIAN4.0.20080109200914-$(date +"%Y-%m-%d").tgz username@example.com:/path/to/backupfolder/
I’ve described passwordless ssh/sftp session in a earlier post so I won’t describe the last line of the backup script.

September 11, 2015

Scripts for backup website

#######################################################################
## AURELIEN HUSSON ##
## Script   and  ##
## Info : ##
## Exemple : website find in /home/www/website/public_html/ ##
## backup in /home/www/website/backup/ ##
## The script in /home/www/website/backup-site.sh ##
#######################################################################
#######################################################################
## AUTOMATIC CRON ##
## For automatiq backup ex : eveyday’s 00:01 AM ##
## 01 00 * * * /home/linuxtricks/backup-script.sh ##
#######################################################################
#! /bin/bash
echo We define the system variables
path=`dirname $0`
pathsav=”$path/backup”
site=”www.website.com”
wwwpath=”/home/website/”
wwwfolder=”public_html”
dbhost=”localhost”
dbuser=”user”
dbpasswd=”password”
dbname=”site”
dbrestohost=”$dbhost”
dbrestouser=”$dbuser”
dbrestopasswd=”$dbpasswd”
dbrestoname=”siterestore”
maxjourssauvegarde=”30″
echo Defined variables.
echo “”
echo Checking Programs
progtar=$(which tar)
progtar=$(echo $?)
progbzip2=$(which bzip2)
progbzip2=$(echo $?)
progbzcat=$(which bzcat)
progbzcat=$(echo $?)
progmysqdump=$(which mysqldump)
progmysqdump=$(echo $?)
progmysql=$(which )
progmysql=$(echo $?)
if [ $progtar -eq 0 ] && [ $progbzip2 -eq 0 ] && [ $progbzcat -eq 0 ] && [ $progmysqdump -eq 0 ] && [ $progmysql -eq 0 ]
then
echo All programs are available on the server
else
echo It lacks a program to run the backup script. Check tar, bzip2, bzcat, mysqldump and mysql
exit 1
fi
echo Checking Completed programs
echo “”
echo Installing the script
cd “$path”
mkdir “$pathsav” 2>/dev/null
echo Script initialising
echo “”
echo The backup date we define
dte=$(date +%Y-%m-%d–%H-%M-%S)
echo Backup date defined on $dte
echo “”
echo We launch Backup
echo “”
echo We launch archive website $site
cd “$wwwpath”
tar cf “$pathsav/$site-$dte.tar” “$wwwfolder”
cd “$path”
if [ $? -eq 0 ]
then
echo Archiving website ends : “$pathsav/$site-$dte.tar”
else
echo Failed archive website
exit 2
fi
echo “”
echo It will launch the backup database
mysqldump -u “$dbuser” -p”$dbpasswd” -h “$dbhost” “$dbname” > “$pathsav/$site-$dte.sql”
if [ $? -eq 0 ]
then
echo Backed up database.
else
echo Failed to backup the database
exit 3
fi
echo “”
echo We compress the archive website $site
bzip2 -z “$pathsav/$site-$dte.tar”
if [ $? -eq 0 ]
then
echo Compression archive of the finished website : “$pathsav/$site-$dte.tar.bz2”
else
echo Failed compression archive website
exit 4
fi
echo “”
echo We compress the database.
bzip2 -z “$pathsav/$site-$dte.sql”
if [ $? -eq 0 ]
then
echo Database compressed .
else
echo Failed compressing the database
exit 5
fi
echo “”
echo BACKUP ENDED
echo ———————
echo PURGE OLD BACKUP
find “$pathsav” -name “$site*” -mtime +”$maxjourssauvegarde” -exec echo ‘{}’ \;
find “$pathsav” -name “$site*” -mtime +”$maxjourssauvegarde” -exec rm ‘{}’ \;
if [ $? -eq 0 ]
then
echo Old backups deleted.
else
echo Failed to delete old backups.
exit 6
fi
echo ——————–
echo CHECKING THE BACKUP
echo We check archive “$pathsav/$site-$dte.tar.bz2”
tar tf “$pathsav/$site-$dte.tar.bz2” 2>/dev/null 1>/dev/null
if [ $? -eq 0 ]
then
echo Backup Site Files : OK
else
echo An error occurred during restore. The backup is probably damaged.
fi
echo “”
echo We check the backup database : “$pathsav/$site-$dte.sql.bz2”
bzcat “$pathsav/$site-$dte.sql.bz2” | mysql -u “$dbrestouser” -p”$dbrestopasswd” -h “$dbrestohost” $dbrestoname
if [ $? -eq 0 ]
then
echo Backing up the database : OK
else
echo An error occurred during restore. The backup is probably damaged.
fi
echo TEST COMPLETED RESTORATION

July 31, 2015

Script Tự động sao lưu toàn bộ website WordPress

Thông thường, khi mình muốn di chuyển hoặc sao lưu một website sử dụng WordPress thì sẽ sử dụng plugin Duplicator. Tuy nhiên, có một số trường hợp server bị lỗi, website không truy cập trực tiếp được hoặc bạn muốn sao lưu lại cả một loạt site đang hoạt động trên server thì sao?
Mình có theo dõi các comment trong bài giới thiệu HocVPS Script hoặc trong chuyên mục Hỏi đáp thì thấy nhu cầu này có thật và cũng khá cần thiết. Do đó, mình có viết một chương trình bash script ngắn, sẽ tự động sao lưu lại website WordPress bạn muốn (bao gồm cả files và database).

HocVPS Script Plugin – Backup All WordPress Sites

Để sử dụng bạn chỉ cần sử dụng dòng lệnh sau:
wget http://hocvps.com/scripts/plugin/backupallwp.sh && chmod +x backupallwp.sh && ./backupallwp.sh
Sau đó chương trình sẽ quét toàn bộ website đang hoạt động cùng với thông tin database MySQL để bạn có thể lựa chọn sao lưu. Cuối cùng toàn bộ dữ liệu sẽ được lưu trong thư mục /home/domain.com/private_html/backupallwp với đường link direct để tải về máy hoặc chuyển sang VPS khác.
Lưu ý: 
  1. Để download trực tiếp file về VPS, hãy sử dụng lệnh wget link
  2. Để giải nén bạn hãy sử dụng lệnh unzip file.zip
  3. Toàn bộ database được lưu lại thành 1 file *.SQL, để import bạn hãy sử dụng lệnh mysql -u username -ppassword databasename < database.sql. Lưu ý thay lại username, password, databasename và tên file database
Chương trình này thiết kế để hoạt động tốt với HocVPS Script và WordPress. Tuy nhiên bạn có thể điều chỉnh lại thoải mái cho phù hợp với control panel đang sử dụng.
Trước mắt mình cứ viết dạng plugin như thế này đã, sau này có tích hợp vào HocVPS Script hay không thì sẽ tính sau 😀
Code bash script
#!/bin/bash
# HocVPS Script Plugin - Backup All WordPress Sites
# -------------------------------------------------------------------------
# Description: Create a backup of your WordPress files and database.
# Copyright (c) 2015 Luan Tran <http://hocvps.com>
# -------------------------------------------------------------------------
# Run: wget http://hocvps.com/scripts/plugin/backupallwp.sh && chmod +x backupallwp.sh && ./backupallwp.sh
# -------------------------------------------------------------------------

clear
printf "=========================================================================\n"
printf "         HocVPS Script Plugin - Backup All WordPress Sites\n"
printf "=========================================================================\n"

#Server information
main_site=`cat /etc/hocvps/scripts.conf | grep mainsite | cut -d \" -f 2`
port=`cat /etc/hocvps/scripts.conf | grep priport | cut -d \" -f 2`
serverip=`cat /etc/hocvps/scripts.conf | grep serverip | cut -d \" -f 2`

#Backup path
backup_path=/home/$main_site/private_html/backupallwp
mkdir -p $backup_path

#Loop through /home directory
for D in /home/*; do
 if [ -d "${D}" ]; then #If a directory
  domain=${D##*/} #Domain name
  printf "\n***Found domain $domain\n"
  
  if [ -f "/home/$domain/public_html/wp-config.php" ]; then
   WPDBNAME=`cat /home/$domain/public_html/wp-config.php | grep DB_NAME | cut -d \' -f 4`
   WPDBUSER=`cat /home/$domain/public_html/wp-config.php | grep DB_USER | cut -d \' -f 4`
   WPDBPASS=`cat /home/$domain/public_html/wp-config.php | grep DB_PASSWORD | cut -d \' -f 4`
   
   echo "$domain is WordPress with database: $WPDBNAME"
   
   read -r -p "Do you want to backup $domain? [y/N] " response
   case $response in [yY][eE][sS]|[yY])
    echo "- Backup database: $WPDBNAME"
    mysqldump -u $WPDBUSER -p$WPDBPASS $WPDBNAME > /home/$domain/public_html/database-$(date +"%Y-%m-%d").sql
    echo "- Backup files: $domain"
    zip -r $backup_path/$domain-$(date +"%Y-%m-%d").zip /home/$domain/public_html/ -q -x /home/$domain/public_html/wp-content/cache/**\* #Exclude cache
    rm -rf /home/$domain/public_html/database-$(date +"%Y-%m-%d").sql #Remove database file
    echo "- Done, database and files are saved to $backup_path/$domain-$(date +"%Y-%m-%d").zip"
    echo "- Download link: http://$main_site:$port/backupallwp/$domain-$(date +"%Y-%m-%d").zip or http://$serverip:$port/backupallwp/$domain-$(date +"%Y-%m-%d").zip"
    ;;
       *)
           echo "Okay, don't backup"
           ;;
   esac
   
  else
   echo "$domain is not WordPress"
  fi
  
 fi
done

nguồn: http://hocvps.com/hocvps-script-plugin-backup-all-wordpress-sites/

June 16, 2015

A Shell Script to Monitor Network, Disk Usage, Uptime, Load Average and RAM Usage in Linux


The duty of System Administrator is really tough as he/she has to monitor the servers, users, logs, create backup and blah blah blah. For the most repetitive task most of the administrator write a script to automate their day-to-day repetitive task. Here we have written a shell Script that do not aims to automate the task of a typical system admin, but it may be helpful at places and specially for those newbies who can get most of the information they require about their System, Network, Users, Load, Ram, host, Internal IP, External IP, Uptime, etc.

How Do I Install and Run Script?

First, use following wget command to download the monitor script "tecmint_monitor.sh" and make it executable by setting appropriate permissions.
# wget http://tecmint.com/wp-content/scripts/tecmint_monitor.sh
# chmod 755 tecmint_monitor.sh
It is strongly advised to install the script as user and not as root. It will ask for root password and will install the necessary components at required places.
To install "tecmint_monitor.sh" script, simple use -i (install) option as shown below.
./tecmint_monitor.sh -i 
Enter root password when prompted. If everything goes well you will get a success message like shown below.
Password: 
Congratulations! Script Installed, now run monitor Command
After installation, you can run the script by calling command 'monitor' from any location or user. If you don’t like to install it, you need to include the location every-time you want to run it.
# ./Path/to/script/tecmint_monitor.sh
Now run monitor command from anywhere using any user account simply as:
$ monitor
TecMint Monitor Script in Action
As soon as you run the command you get various System related information which are:
  1. Internet Connectivity
  2. OS Type
  3. OS Name
  4. OS Version
  5. Architecture
  6. Kernel Release
  7. Hostname
  8. Internal IP
  9. External IP
  10. Name Servers
  11. Logged In users
  12. Ram Usages
  13. Swap Usages
  14. Disk Usages
  15. Load Average
  16. System Uptime
Check the installed version of script using -v (version) switch.
$ monitor -v

tecmint_monitor version 0.1
Designed by Tecmint.com
Released Under Apache 2.0 License