如何通过脚本将一组文件/文件夹从linux服务器传输到另一个?
I'm creating a php script to backup my website everyday, backup goes to another linux server of mine but how can i compress all files and send to another linux server via a script?
我正在创建一个PHP脚本来每天备份我的网站,备份转到我的另一个linux服务器但是怎么能 我压缩所有文件并通过脚本发送到另一个Linux服务器? p> div>
One possible solution (in bash).
BACKUP_SERVER_PATH=remote_user@remote_server:/remote/backup/path/
SITE_ROOT=/path/to/your/site/
cd "$SITE_ROOT"
now=$(date +%Y%m%d%H%M)
tar -cvzf /tmp/yoursite.$now.tar.gz .
scp /tmp/yoursite.$now.tar.gz "$BACKUP_SERVER_PATH"
Some extra stuff to take into account for permission (read access to docroot) and ssh access to the remote server (for scp).
Note that there are really many ways to do this. Another one, if you don't mind storing an uncompressed version of your site is to use rsync.
The answer provided by Timothée Groleau should work, but I prefer doing it the other way around: from my backups machine (a server with a lot of storage available) launch a process to backup all other servers.
In my environment, I use a configuration file that lists all servers, valid user for each server and the path to backup:
/usr/local/etc/backupservers.conf
192.168.44.34 userfoo /var/www/foosites
192.168.44.35 userbar /var/www/barsites
/usr/local/sbin/backupservers
#!/bin/sh
CONFFILE=/usr/local/etc/backupservers.conf
SSH=`which ssh`
if [ ! -r "$CONFFILE" ]
then
echo "$CONFFILE not readable" >&2
exit 1
fi
if [ ! -w "/var/backups" ]
then
echo "/var/backups is not writable" >&2
exit 1
fi
while read host user path
do
file="/var/backups/`date +%Y-%m-%d`.$host.$user.tar.bz2"
touch $file
chmod 600 $file
ssh $user@$host tar jc $path > $file
done
For this to work correctly and without need to enter passwords for every server to backup you need to exchange SSH keys (there are lots of questions/answers on stackoverflow on how to do this).
And last step would be to add this to cron to launch the process each night:
/etc/crontab
0 2 * * * backupuser /usr/local/sbin/backupservers