Skip to content

Instantly share code, notes, and snippets.

@ksred
Created January 23, 2014 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksred/8577117 to your computer and use it in GitHub Desktop.
Save ksred/8577117 to your computer and use it in GitHub Desktop.
An intermediate example of sending a file to another server using SSH. In this example, we also import a database on remote server.
#! /bin/bash
echo "It is suggested that you add this server's public key to the remote server. Copy the following into ~/.ssh/authorized_keys on remote server under root user"
cat ~/.ssh/id_rsa.pub
echo "Enter in file name, must be tar.gz file for this example"
read FILENAME
echo "Enter in local directory where file is currently"
read BASE
echo "Where is this being copied to?"
echo "User name, eg root:"
read SSHUSER
echo "Host, eg staging.ksred.co:"
read SSHHOST
echo "Port, eg 22:"
read SSHPORT
echo "Directory to copy to, eg /var/www/html/[site]"
read SSHDIR
#Check if there is enough space on target
echo "Checking space on remote server ..."
ssh -p $SSHPORT $SSHUSER@$SSHHOST 'df -h'
echo "Local file size:"
ls -ahs $BASE | grep $FILENAME
echo "Is there enough free space for $FILENAME? y/n"
read SPACE
if [ "$SPACE" == "n" ]
then
echo "Free up some space on remote server or choose another remote server"
exit
fi
echo "Creating directory ..."
ssh -p $SSHPORT $SSHUSER@$SSHHOST exec "mkdir $SSHDIR"
echo "Copying files across ..."
rsync -avrz -e "ssh -p $SSHPORT" --progress $BASE/$FILENAME $SSHUSER@$SSHHOST:$SSHDIR
echo "Extracting files on remote server ..."
ssh -p $SSHPORT $SSHUSER@$SSHHOST exec "tar -zxvf $SSHDIR/$FILENAME -C $SSHDIR/"
echo "Local database username:"
read DBUSER
echo "Local database password:"
read DBPASS
echo "Local mysql host:"
read DBHOST
echo "Local database name:"
read DBNAME
echo "Creating remote database with above username and password"
echo "Remote database root username:"
read REMOTEMYSQLUSER
echo "Remote database root password:"
read REMOTEMYSQLPASS
echo "Remote mysql host:"
read REMOTEMYSQLHOST
CREATE_MYSQL="mysql -u $REMOTEMYSQLUSER -p$REMOTEMYSQLPASS -h $REMOTEMYSQLHOST --execute=\"create database $DBNAME; create user $DBUSER@'%' identified by '$DBPASS'; grant all privileges on $DBNAME.* to $DBUSER@'%'; flush privileges; \" && exit;"
echo "Creating database on remote server ..."
ssh -p $SSHPORT $SSHUSER@$SSHHOST exec $CREATE_MYSQL
#Here it is assumed that there is a database file named "database.sql" in root of the tar.gz
IMPORT_MYSQL="mysql -u $REMOTEMYSQLUSER -p$REMOTEMYSQLPASS -h $REMOTEMYSQLHOST < $SSHDIR/database.sql"
echo "Importing database on remote server ..."
ssh -p $SSHPORT $SSHUSER@$SSHHOST exec $IMPORT_MYSQL
echo "Tar file copied across, database with user created, database imported."
echo "All done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment