Showing posts with label rsync. Show all posts
Showing posts with label rsync. Show all posts

Monday, May 16, 2011

How to use rsync for transferring files under Linux or UNIX

SkyHi @ Monday, May 16, 2011
How do you install and use rsync to synchronize files and directories from one location (or one server) to another location? - A common question asked by new sys admin.
rsync is a free software computer program for Unix and Linux like systems which synchronizes files and directories from one location to another while minimizing data transfer using delta encoding when appropriate. An important feature of rsync not found in most similar programs/protocols is that the mirroring takes place with only one transmission in each direction.

So what is unique about rsync?

It can perform differential uploads and downloads (synchronization) of files across the network, transferring only data that has changed. The rsync remote-update protocol allows rsync to transfer just the differences between two sets of files across the network connection.

How do I install rsync?

Use any one of the following commands to install rsync.

If you are using Debian or Ubuntu Linux, type the following command

# apt-get install rsync
OR
$ sudo apt-get install rsync

If you are using Red Hat Enterprise Linux (RHEL), type the following command

# up2date rsync

If you are using CentOS/Fedora Core Linux, type the following command

# yum install rsync

Always use rsync over ssh

Since rsync does not provide any security while transferring data it is recommended that you use rsync over ssh . This allows a secure remote connection. Now let us see some examples of rsync.

rsync command common options

  • --delete : delete files that don't exist on sender (system)
  • -v : Verbose (try -vv for more detailed information)
  • -e "ssh options" : specify the ssh as remote shell
  • -a : archive mode
  • -r : recurse into directories
  • -z : compress file data

Task : Copy file from a local computer to a remote server

Copy file from /www/backup.tar.gz to a remote server called openbsd.nixcraft.in
$ rsync -v -e ssh /www/backup.tar.gz jerry@openbsd.nixcraft.in:~Output:
Password:
sent 19099 bytes  received 36 bytes  1093.43 bytes/sec
total size is 19014  speedup is 0.99
Please note that symbol ~ indicate the users home directory (/home/jerry).

Task : Copy file from a remote server to a local computer

Copy file /home/jerry/webroot.txt from a remote server openbsd.nixcraft.in to a local computer /tmp directory:
$ rsync -v -e ssh jerry@openbsd.nixcraft.in:~/webroot.txt /tmp
Password

Task: Synchronize a local directory with a remote directory

$ rsync -r -a -v -e "ssh -l jerry" --delete openbsd.nixcraft.in:/webroot/ /local/webroot

Task: Synchronize a remote directory with a local directory

$ rsync -r -a -v -e "ssh -l jerry" --delete /local/webroot openbsd.nixcraft.in:/webroot

Task: Synchronize a local directory with a remote rsync server

$ rsync -r -a -v --delete rsync://rsync.nixcraft.in/cvs /home/cvs

Task: Mirror a directory between my "old" and "new" web server/ftp

You can mirror a directory between my "old" (my.old.server.com) and "new" web server with the command (assuming that ssh keys are set for password less authentication)
$ rsync -zavrR --delete --links --rsh="ssh -l vivek" my.old.server.com:/home/lighttpd /home/lighttpd

Read related previous articles

Other options - rdiff and rdiff-backup

There also exists a utility called rdiff, which uses the rsync algorithm to generate delta files Using rdiff. A utility called rdiff-backup has been created which is capable of maintaining a backup mirror of a file or directory over the network, on another server. rdiff-backup stores incremental rdiff deltas with the backup, with which it is possible to recreate any backup point. Next time I will write about these Utilities :)

rsync for Windows server/XP

Please note if you are using Windows, try any one of the program:
  1. DeltaCopy
  2. NasBackup

Further readings

=> Read rsync man page
=> Official rsync documentation

REFERENCES
http://www.cyberciti.biz/tips/linux-use-rsync-transfer-mirror-files-directories.html

Friday, November 26, 2010

rsync error: "IO error encountered -- skipping file deletion"

SkyHi @ Friday, November 26, 2010
IO error encountered -- skipping file deletion


Figured it out....



In hardy there is a hidden folder in /home/user/ called .gvfs...No idea what it is, but just exclude it from your rsync backup.

REFERENCES
http://ubuntuforums.org/showthread.php?t=290617

Saturday, November 13, 2010

keychain: Set Up Secure Passwordless SSH Access For Backup Scripts

SkyHi @ Saturday, November 13, 2010
We establish connections to remote systems without supplying a password, however I do not want to store my password less keys ( passphrase-free keys) on my servers. ssh-agent, takes care of keys with passphase, which allowing me to easily have ssh-agent process per system per login session. How do I dramatically reduces the number of times I've to punch my passphrase from once per new login session to once every time my local server is rebooted? How do I use keychain utility for all my backup scripts for secure passwordless login?

OpenSSH offers RSA and DSA authentication to remote systems without supplying a password. keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. It offers various security benefits over passphrase-free keys.

How Does Keychain Make It Better Than a Key Less Passphrase?

If attacker broken into server with passphrase-free keys, all other your servers / workstation on which keys are used are also security risk (they can be easily breached). With keychain or ssh-agent attacker won't able to touch your remote systems without breaking your passphrase. Another example, if your laptop or harddisk stolen, an attacker can simply copy your key and use it anywhere as it is not protected by a passphrase.
keychain is a manager for ssh-agent, typically run from ~/.bash_profile. It allows your shells and cron jobs to share a single ssh-agent process. By default, the ssh-agent started by keychain is long-running and will continue to run, even after you have logged out from the system. If you want to change this behavior, take a look at the --clear and --timeout options, described below. Our sample setup is as follows:
peerbox.nixcraft.net.in => Remote Backup Server. Works in pull only mode. It will backup server1.nixcraft.net.in and server2.nixcraft.net.in.
vivek-desktop.nixcraft.net.in => My desktop computer.
server1.nixcraft.net.in => General purpose remote server.
server2.nixcraft.net.in => General purpose remote web / mail / proxy server.
Install keychain software on peerbox.nixcraft.net.in so that it can login securely to other two servers for backup.

Install keychain on CentOS / RHEL / Fedora Linux

You need RPMForge repo enabled to install keychain package.
# yum install keychain

Install keychain on Debian / Ubuntu Linux

# apt-get update && apt-get install keychain

Install keychain on FreeBSD

# portsnap fetch update
# cd /usr/ports/security/keychain
# make install clean

How Do I Setup SSH Keys With passphrase?

Simply type the following commands:
$ ssh-keygen -t rsa
OR
$ ssh-keygen -t dsa
Assign the pass phrase when prompted. See the following step-by-step guide for detailed information:
  1. Howto Linux / UNIX setup SSH with DSA public key authentication (password less login)
  2. Howto use multiple SSH keys for password less login

How Do I Use Keychain?

Once OpenSSH keys are configured with a pass phrase, update your $HOME/.bash_profile file which is your personal initialization file, executed for login BASH shells:
$ vi $HOME/.bash_profile
Append the following code:
### START-Keychain ###
# Let  re-use ssh-agent and/or gpg-agent between logins
/usr/bin/keychain $HOME/.ssh/id_dsa
source $HOME/.keychain/$HOSTNAME-sh
### End-Keychain ###
Now you've keychanin configured to call keychain tool every login. Just log out and log back in to server from your desktop to test your setup:
$ ssh root@www03.nixcraft.net.in
Sample Output:
Fig.01 - Keychain in Action
Fig.01 - Keychain in Action
keyhcain is up and running. Now, all you have to do is append your servers key file $HOME/.ssh/id_dsa.pub to other UNIX / Linux / BSD boxes:
# scp $HOME/.ssh/id_dsa.pub server1.nixcraft.net.in:~/pubkey
# scp $HOME/.ssh/id_dsa.pub server2.nixcraft.net.in:~/pubkey
# ssh server1.nixcraft.net.in cat ~/pubkey >> ~/.ssh/authorized_keys2; rm ~/pubkey
# ssh server2.nixcraft.net.in cat ~/pubkey >> ~/.ssh/authorized_keys2; rm ~/pubkey
# ssh root@server1.nixcraft.net.in
# ssh user@server2.nixcraft.net.in

Task: Clear / Delete All Of Ssh-agent's Key

# keychain --clear

Security Task: Make Sure Intruder Cannot Use Your Existing SSH-Agent's Keys (only allow cron jobs to use password less login)

The idea is pretty simply only allow backup shell scripts and other cron job to do password less login but all users including an intruder must provide a passphrase-key for interactive login. This is done by deleting all of ssh-agent's keys. This option will increases security, it still allows your cron jobs to use your ssh keys when you're logged out. Update your ~/.bash_profile as follows:
/usr/bin/keychain --clear $HOME/.ssh/id_dsa
If you are using RSA, use:
/usr/bin/keychain --clear $HOME/.ssh/id_rsa
Now, just log in to remote server box once :
$ ssh root@peerbox.nixcraft.net.in
Log out (only grant access to cron jobs such as backup)
# logout

Task: Use Keychain With Backup Scripts for Passwordless login via cron

Add the following before your rsync, tar over ssh or any other network backup command:
source $HOME/.keychain/$HOSTNAME-sh
Here is a sample rsync script:

#!/bin/bash
# Remote Server Rsync backup Replication Shell Script
# Local dir location
LOCALBAKPOINT=/iscsi
LOCALBAKDIR=/backups/server1.nixcraft.net.in/wwwroot
# Remote ssh server setup
SSHUER=root
SSHSERVER=server1.nixcraft.net.in
SSHBACKUPROOT=/wwwroot
 
# Make sure you can log in to remote server without a password
source $HOME/.keychain/$HOSTNAME-sh 
 
# Make sure local backup dir exists
[ ! -d ${LOCALBAKPOINT}${LOCALBAKDIR} ] && mkdir -p ${LOCALBAKPOINT}${LOCALBAKDIR}
 
# Start backup
/usr/bin/rsync --exclude '*access.log*' --exclude '*error.log*' -avz -e 'ssh ' ${SSHUER}@${SSHSERVER}:${SSHBACKUPROOT} ${LOCALBAKPOINT}${LOCALBAKDIR}
 
# See if backup failed or not to /var/log/messages file
[ $? -eq 0 ] && logger 'RSYNC BACKUP : Done' || logger 'RSYNC BACKUP : FAILED!'


If you are using rsnaphot backup server (see how to setup RHEL / CentOS / Debian rsnapshot backup server) add the following to your /etc/rsnapshot.conf file
# Get ssh login info via keychain
cmd_preexec    source /root/.keychain/hostname.example.com-sh

Final Note About Keychain and Security

  • Cracker with an advanced attacking with deadly coding skills can still get key from memory. However, keychain makes it pretty difficult for normal users and attackers to steal your keys and use it.
  • OpenSSH sshd server offers two additional options to protect abuse of keys. First, make sure root login disabled (PermitRootLogin yes). Second, specify which user accounts on the server are allowed to be used for authentication by adding AuthorizedKeysFile %h/.ssh/authorized_keys_FileName. See sshd_config man page for further details.

Suggested Readings:

Rsync Change SSH Port Number While Making Backups

SkyHi @ Saturday, November 13, 2010
How do I change my rsync command port number while making backup to remote server at backup1.example.com port 10253 (my ssh server runs on port # 10253)?

The command to change port number is pretty simple:
sync -av -e 'ssh -p PORT-NUMBER-HERE' /path/to/source user@backup1.example.com
Backup /home/vivek to server1.nixcraft.net.in at port number 5000, enter:
 
rsync -av -e 'ssh -p 5000' /home/vivek backupop@server1.nixcraft.net.in
 

See also:

man rsync

REFERENCES
http://www.cyberciti.biz/faq/unix-linux-bsd-osx-change-rsync-port-number/

Friday, November 12, 2010

Replicating Content Between USA, Japan (Asia) and UK (Europe) Webservers

SkyHi @ Friday, November 12, 2010
We have corporate intranet network for our web site as us.example.com, jp.example.com (asia.example.com), uk.example.com (eu.example.com). How do I replicate static content stored at /var/www/corporate_lan/ such as javascript files, css files, and images between our USA, Japan and UK web servers running under UNIX or CentOS or Redhat Enterprise Linux based Apache servers?

There are various solutions exists to replicate static files and dynamic web site across the globe. Replicating set of static files is pretty easy.

Sample Setup

eth1:67.1.2.3
                                                +-----------------+
                                                | us.example.com  |
 eth1:202.54.1.2                                +-----------------+
+----------------------+                        |
|  content.example.com |------------------------+
+----------------------+       VPN/intranet     | eth1:87.1.2.3
   /                                            +-----------------+
   /                                            | uk.example.com  |
   |                                            +-----------------+
   +/var/www/corporate_lan/                     |
                          /css/                 | eth1:123.1.2.3
                          /images/              +-----------------+
                          /js/                  | jp.example.com  |
                          /php_cgi/             +-----------------+
                          /perl_cgi/
                          /java_app/
                          /python_app1/
Where,
  1. All server runs same version of UNIX or Linux and Apache.
  2. DocumentRoot is same for all servers.
  3. content.example.com - Your main file server. You need to update or upload all static files here only. Do not upload or create files in other servers. You can now push updates or mirror directories from this server to rest of the nodes.
  4. us.example.com - Your USA based web server. This server will sync to (or mirror directories from) upstream server called content.example.com.
  5. jp.example.com - Your Japan based web server. This server will sync to (or mirror directories from) upstream server called content.example.com.
  6. uk.example.com - Your UK web server. This server will sync to (or mirror directories from) upstream server called content.example.com.
  7. All offices are connected using secure vpn or an an intranet - a private computer network that uses Internet Protocol technologies to securely share any part of an organization's network operating system.

Solution # 1: Mirroring Using rsync

You can use rsync application to synchronizes files and directories from content.example.com to another locations such as us.example.com while minimizing data transfer using delta encoding when appropriate. rsync can copy directory contents and files using compression and recursion. You must install rsync on all servers. Type the following command on content.example.com to replicate /var/www/corporate_lan/ to all three servers as follows:
 
rsync -av /var/www/corporate_lan root@us.example.com:/var/www/
rsync -av /var/www/corporate_lan root@uk.example.com:/var/www/
rsync -av /var/www/corporate_lan root@jp.example.com:/var/www/
 
To replicate only /var/www/corporate_lan/css directory, enter:
 
rsync -av /var/www/corporate_lan/css root@us.example.com:/var/www/
rsync -av /var/www/corporate_lan/css root@uk.example.com:/var/www/
rsync -av /var/www/corporate_lan/css root@jp.example.com:/var/www/
 

--delete option

You can delete files that don't exist on /var/www/corporate_lan using the following syntax. So if you type on content.example.com:
# rm /var/www/corporate_lan/images/new_logo.png
Remove all deleted files from the rest of the all servers i.e. keep exact mirror of content.example.com, enter:
 
rsync -av --delete /var/www/corporate_lan root@us.example.com:/var/www/
rsync -av --delete /var/www/corporate_lan root@uk.example.com:/var/www/
rsync -av --delete /var/www/corporate_lan root@jp.example.com:/var/www/
 
The -a option works as follows:
  • Recurse into directories
  • Copy symlinks as symlinks
  • Preserve all file permissions (so make sure you use same usernames on all servers)
  • Preserve group file permissions
  • Preserve owner file permissions (you need to run rsync as root)
  • Preserve times
You can compress file data during the transfer using -z or --compress option
 
rsync -z -av --delete /var/www/corporate_lan root@us.example.com:/var/www/
 
The --compress-level=NUM with explicitly set compression level:
rsync -z --compress-level=5 -av --delete /var/www/corporate_lan root@us.example.com:/var/www/

Excluding files

You can exclude files as follows:
rsync -z --compress-level=5 -av --delete --exclude='cache/*' --exclude='*~'  /var/www/corporate_lan root@us.example.com:/var/www/
You can create a pattern file as follows (/root/mirror.exclude)
cache/*
/dev/
/.conf/
*~
The --exclude-from=/root/mirror.exclude option read exclude patterns from /root/mirror.exclude:
rsync -z --compress-level=5 -av --delete --exclude-from=/root/mirror.exclude  /var/www/corporate_lan root@us.example.com:/var/www/

Sample rsync server mirroring shell script

You can create a shell script (say /root/mirror.dirs) to sync every 30 minutes or as per your requirements to mirror the directories and files:
#!/bin/bash
# Usage: Mirror directories and files to our US, UK and Japan based server.
# --------------------------------------------------------------------------
_upstream="/var/www/corporate_lan"
_servers="root@us.example.com:/var/www/ root@uk.example.com:/var/www/ root@jp.example.com:/var/www/"
_rsync="/usr/bin/rsync"
_exclude="/root/mirror.exclude"
_log="/var/log/rsync_mirror.log"
_opts=""
for e in $_servers
do
        [ -f "${_exclude}" ] && _opts="--exclude-from=$_exclude"
        $_rsync -z -a --delete $_opts  "$_upstream" "$e"
done &>$_log
 


Run once an hour using cron i.e. mirror server once an hour:
@hourly /root/mirror.dirs

How Do I Call /root/mirror.dir As Soon As New Static File Uploaded In /var/www/corporate_lan?

You can use the inotify cron daemon to monitors filesystem events and executes /root/mirror.dirs script:
/var/www/corporate_lan/css/ IN_CLOSE_WRITE,IN_CREATE,IN_DELETE /root/mirror.dirs
/var/www/corporate_lan/images/ IN_CLOSE_WRITE,IN_CREATE,IN_DELETE /root/mirror.dirs
/var/www/corporate_lan/js/ IN_CLOSE_WRITE,IN_CREATE,IN_DELETE /root/mirror.dirs
See how to configure and install inotify under Linux based systems.

Solution # 2: Mirroring Using unison

You synchronizing files between a server called content.example.com and another server called us.example.com while keeping the same version of files on multiple servers. Unison allows two replicas of a collection of files and directories to be stored on different servers, modified separately, and then brought up to date by propagating the changes in each replica to the other. In this example, your webmaster can upload new_logo.png to us.example.com and it will get replicated to rest of all servers. Similarly if new_logo.png deleted from content.example.com, it will get deleted from rest of all servers. You can use it as follows:
# unison -batch /var/www/corporate_lan ssh://us.example.com//var/www/corporate_lan
To just replicate /css/ part, enter
# unison -batch /var/www/corporate_lan/css ssh://us.example.com//var/www/corporate_lan/css

Sample unison server mirroring shell script

Create a shell script called /root/unison.mirror.sh:
#!/bin/bash
_paths="/var/www/corporate_lan/css \
/var/www/corporate_lan/images \
/var/www/corporate_lan/js"
_unison=/usr/bin/unison
_rserver="us.example.com uk.example.com jp.example.com"
for p in ${_paths}
do
 ${_unison} -batch "${p}"  "ssh://${_rserver}/${p}"
done

Run once an hour using cron i.e. mirror server once an hour:
@hourly /root/unison.mirror.sh
As explained earlier, you can call this script on demand too using inotify cron daemon
/var/www/corporate_lan/css/ IN_CLOSE_WRITE,IN_CREATE,IN_DELETE /root/unison.mirror.sh
/var/www/corporate_lan/images/ IN_CLOSE_WRITE,IN_CREATE,IN_DELETE /root/unison.mirror.sh
/var/www/corporate_lan/js/ IN_CLOSE_WRITE,IN_CREATE,IN_DELETE /root/unison.mirror.sh

Solution #3: Use 3rd Party Cloud Based Solution

You can use 3rd party cloud computing infrastructure (such as Amazon S3, and your data is automatically replicated across multiple Availability Zones) to sync all your data in three different data centers. The discussion regarding cloud computing is beyond the scope of this FAQ, I recommend reading AWS or similar 3rd party cloud services.

Solution # 4: Replicate Content Using 3rd Party Content Delivery Networks (CDN)

A content delivery network or content distribution network (CDN) is a system of computers containing copies of data, placed at various points in a network so as to maximize bandwidth for access to the data from clients throughout the network. A client accesses a copy of the data near to the client, as opposed to all clients accessing the same central server, so as to avoid bottleneck near that server. However, cdn may not offer speed as intranet is closer to user. If you got lots of home workers or remote clients or user are all spread around the globe it might be good idea use a cdn. Please note that you put your static files into someone else's network and if files are important (not for public view) do not host them using a cdn.

Solution #5: Content Replication Using Data Deduplication

Data deduplication is a specialized data compression technique for eliminating coarse-grained redundant data, typically to improve storage utilization. In the deduplication process, duplicate data is deleted, leaving only one copy of the data to be stored, along with references to the unique copy of data. Deduplication is able to reduce the required storage capacity since only the unique data is stored. You can use open source project such as opendedup and lessfs. Data Deduplication solutions has been designed as a filesystem for backup purposes. However it can be used as storage for virtual machine images and replicating your data too.

Data deduplication
Fig.01: Data deduplication using opendedup

Conclusion

  1. Almost all replication schema may requires low latency. So I recommend that you test all of the above methods and see what works out for you.
  2. Usually, open source tools are good when static files are not updated, uploaded and deleted at rapid rates (e.g. 1000 of files per second).
  3. I've also avoided discussion about commercial enterprise grade solution such as NFS over WAN using WAN accelerator such as Riverbed, HP EFS WAN accelerator and others due to cost issues.


REFERENCES
http://www.cyberciti.biz/faq/linux-unix-server-replicating-content-us-europe-asia-webservers/

Sunday, May 23, 2010

Rsync and SSH on Windows Server

SkyHi @ Sunday, May 23, 2010
Wednesday, January 07, 2009
Very basic rsync / cp backup rotation with hardlinks
Here's a very basic script that I use with RSync that makes use of hard links to reduce the overall size of the backup folder. The limitations are:

- Every morning, a server copies the current version of all files across SSH (using scp) into a "current" folder. There are two folders on the source server that get backed up daily (/home and /local).

- Later on that day, we run the following script to rsync any new files into a daily folder (daily.0 through daily.6).

- In order to bootstrap those daily.# folders, you have to use "cp -al current/* daily.2/" on each, which fills out the seven daily backup folders with hardlinks. Change the number in "daily.2" to 0-6 and run the command once for each of the seven days. Do this after the "current" folder has been populated with data pushed by the source server.

- Ideally, the source server should be pushing changes to the "current" folder using rsync. But in our case, the current server is an old Solaris 9 server without rsync. Which means that our backups are likely to be about 2x to 3x larger then they should be.

- RDiff-Backup may have been a better solution for this particular problem (and we may switch).

- This shows a good example of how to calculate the current day of week number (0-6) as well as calculating what the previous day number was (using modulus arithmetic).

- I make no guarantees that permissions or ownership will be preserved. But since the source server strips all of that information in the process of sending the files over the wire with scp, it's a moot point for our current situation. (rdiff-backup is probably a better choice for that.)

#!/bin/bash
# DAILY BACKUPS (writes to a daily folder each day)
DAYNR=`date +%w`
echo DAYNR=${DAYNR}
let "PREVDAYNR = ((DAYNR + 6) % 7)"
echo PREVDAYNR=${PREVDAYNR}
DIRS="home local"

for DIR in ${DIRS}
do
echo "----- ----- ----- -----"
echo "Backup:" ${DIR}
SRCDIR=/backup/cfmc1/$DIR/current/
DESTDIR=/backup/cfmc1/$DIR/daily.${DAYNR}/
PREVDIR=/backup/cfmc1/$DIR/daily.${PREVDAYNR}/
echo SRCDIR=${SRCDIR}
echo DESTDIR=${DESTDIR}
echo PREVDIR=${PREVDIR}

cp -al ${PREVDIR}* ${DESTDIR}
rsync -a --delete-after ${SRCDIR} ${DESTDIR}

echo "Done."
done


It's not pretty, but it will work better once the source server starts pushing the daily changes via rsync instead of completely overwriting the "current" directory every day.

The code should be pretty self explanatory but I'll explain the two key lines.

cp -al ${PREVDIR}* ${DESTDIR}

This overwrites all files in ${DESTDIR}, which is today, with the files from yesterday, but does it by creating hard links of all files. Old files which were deleted since last week will be left behind until the rsync step.

rsync -a --delete-after ${SRCDIR} ${DESTDIR}

This then brings today's folder up to date with any changes as compared to the source directory (a.k.a. "current"). It also deletes any file in today's folder that don't exist in the source directory.

References:

Easy Automated Snapshot-Style Backups with Linux and Rsync

Local incremental snap shots with rsync

Labels: , ,

Monday, August 21, 2006
Rsync and SSH on Windows 2003 Server
Taking another stab at setting up RSync and SSH on our Windows 2003 servers. The goal is that we can upload web files to a central server and then have it synchronize the other servers in the array. Once again, I'm going to use the cwRsync and copSSH packages (latest version is 2.0.9).

Installation on a Windows 2003 Domain Controller:

  1. Download cwRSync, open up the ZIP file, then extract/run cwRsync_Server_x.x.x_Installer.exe.
  2. Click "Next" to move past the splash screen
  3. Click "I Agree" to move past the license screen
  4. Select both the "Rsync Server" and "OpenSSH Server" (unless you have already installed and configured SSH) then click "Next"
  5. Choose your installation location, the default is "C:\Program Files\cwRsyncServer"
  6. Click "Install" to begin the installation process
  7. cwRsync will install and create a default service account with a randomly generated password.
  8. Write down the service account password.
  9. Click "Close" when the install has finished.


So now if you look in "Active Directory Users and Computers", there should be a newly created account called "SvcwRsync". Since we are installing this on a domain controller, you should rename this account to "SvcwRsync_SERVERNAME" so that it doesn't cause problems for other installations. You'll also need to change the login details for the "RsyncServer" and "OpenSSH SSHD" services.

Once you have things configured, make sure to go to the Services control and set the services to start up automatically. I also recommend configuring the Recovery tab so that the services are automatically restarted after 2 or 5 minutes.

...

Now to start locking things down. First, I'm going to restrict what interfaces (IP addresses) that the cwRSync service can listen on by adding an address line to rsyncd.conf.

address = 127.0.0.1

One the machine that you will be using to talk to the rsync daemon on the host server, you'll also need the cwRsync tools installed along with OpenSSH. Because the rsync daemon can only listen on 127.0.0.1 (localhost), we'll need to create an SSH tunnel from the client machine to the host server before we can talk to the rsync daemon.

One the client machine:

1. Create a new folder under "C:\Program Files\cwRsyncServer\home" for the new user. In my particular case, I'm calling my user "backuppull" because I am pulling backup files off of the rsync server and down to my local machine.

2. Create a ".ssh" folder under that new home folder.

3. Open up a command window (Start, Run, "cmd") and change directories to the home folder ("C:\Program Files\cwRsyncServer\home\backuppull")

4. Create ssh keys for this user. Since we want to do this sync in a batch file without user-interaction, they'll need to be created with null passwords. You may wish to use the "-b 2048" option to create stronger keys (recommended for RSA, DSA can only be up to 1024 bits).

mkdir .ssh
..\..\ssh-keygen -t rsa -N "" -b 2048 -f .ssh\id_rsa
..\..\ssh-keygen -t dsa -N "" -b 1024 -f .ssh\id_dsa

5. You will now need to transfer the public key files to the host server. Again, you will create a new home directory for the user in the "C:\Program Files\cwRsyncServer\home" folder tree along with creating a ".ssh" folder under that home folder. The two files that need to be copied are:

id_dsa.pub
id_rsa.pub

6. Now append the contents of these files to the ".ssh/authorized_keys" file on the host server.

type id_dsa.pub >> authorized_keys
type id_rsa.pub >> authorized_keys

7. Now to configure SSHD on the host server. You will need to find and edit the sshd_config file (probably in "C:\Program Files\cwRsyncServer\etc"). The following changes should be made in the current version default settings.

PermitRootLogin no
PasswordAuthentication no

Labels: ,

Tuesday, August 09, 2005
More rsync links for using rsync as a backup tool
Easy Automated Snapshot-Style Backups with Linux and Rsync

I'll need to come back and revisit this link, from a glance, it looks very well laid out and will be exactly what I want to pattern my backup systems after.

Labels: ,

Tuesday, May 03, 2005
cwRSync and copSSH
Note: These directions are works-in-progress... in fact, they might not even work at all. I got side-tracked before I could finish this and will re-visit it at some point in the future.

The folks who created cwRSync (www.itefix.no) have now released a package called copSSH which is basically SSH for windows and works with cwRSync. I'll be refering back to my old post about installing cwRSync. The latest version I have is from late April 2005 and includes bug fixes for Windows Server 2003.

Also see the rsyncd.conf file for configuring rsync.

These steps are for installing rsync in a server configuration (meaning that it will be listening on the listed ports). Since the install process needs to (optionally) create an user account and create a new service, you'll need administrative access to the machine that you are using. (I'm not sure whether members of the Power Users group have enough privileges.)


  1. Download cwRSync, open up the ZIP file, then extract/run cwRsync_x.x.x_Installer.exe.

  2. Click "Next" to begin the install.

  3. Read and agree to the licence.

  4. Make sure that both the client and server components are checked off and click "Next".

  5. Choose your installation location. I prefer to put mine in a custom location (C:\bin\cwRsync).

  6. Click "Install" to begin the installation.

  7. The default user account is "cwrsync" (with a random password) and it will be installed as a service. You will probably want to change the password to something stronger and adjust the properties of the service in Computer Management. Specifically, I changed the Recovery tab to auto-restart the service after 5 minutes if it dies. I've left the "auto-start" setting to "manual" until I've finished configuration and testing.

  8. By default, the newly created "cwRSync" folder grants permissions to the Administrators group (full control), the CWRSYNC user account (full control) and the Users account (read/execute).

  9. Now you should configure your rsyncd.conf file.


Now we need to install copSSH.


  1. Download copSSH, open up the ZIP file, then extract/run copSSH_x.x.x_Installer.exe.

  2. Click "Next" to begin the install.

  3. Read and agree to the licence.

  4. Change the install folder to match where you installed cwRSync (C:\bin\cwRsync). (This is according to the FAQ on the itefix.no web site.)

  5. This creates a new service called "OpenSSH SSHD" with a default users account of "SvcCOPSSH"

  6. You will probably want to change the password to something stronger and adjust the properties of the service in Computer Management. Specifically, I changed the Recovery tab to auto-restart the service after 5 minutes if it dies. I've changed the "auto-start" setting to "manual" until I've finished configuration and testing.

  7. Notice that the copSSH installation blows away existing permissions on the c:\bin\cwRSync folder. This may require fixing (I have to test first).

  8. Re-start the SSHD service in manual mode (if you stopped it earlier).

Labels: ,

Wednesday, July 21, 2004
Minimal Cygwin install for RSync and SSH
Source links:

How to setup the secure shell daemon on a Windows 2000 machine?
Windows Rsync Server Setup
CygwinInstallationGuide (a wiki topic about the cygwin installation)

Note: The following probably doesn't work (probably missing a package, or the fact that I have GNU's unix tools for Win32 installed is problematic), but I might come back and make it work later so I'm leaving it here for now. I ran into trouble when trying to configure SSH. Right now, I've gone back to my original plan of either hacking apart the Cygwin files and manually copying only the DLLs and EXEs that I need or using the OpenSSH for Windows project at SourceForge.

1. Run the Cygwin setup.exe file and start the instllation. I chose to install to "c:\bin\cygwin", but left the rest of the options "as-is". Pick your mirror (use the Cygwin public mirrors page to find one close to you).

2. On the "Select Packages" screen, select the "Curr" option and make sure it says "Category" next to the "View" button at the top. The installation dialog is (finally) re-sizeable, so stretch it out or maximize it so you can see all of the columns.

3. Beside the "+All" category, it will say "Install", "Uninstall", ... click on the word until all of the categories say "Uninstall". (Note: These steps assume that you're doing a new Cygwin install and that you don't already have Cygwin installed.) Now we can start picking the minimum number of packages required to setup SSH and RSync.

4a. Under the "+Admin" category, you'll need to install the "cygrunsrv" package (click once on the "Skip" indicator under the "New" column). This will turn on a few other packages that this package depends on (mostly under the "+Base", "+Libs", and "+Shells" categories).

4b. Open up the "+Net" category and select the "rsync" and "openssh" packages. You'll also end up with "openssl" which is required in order to use "openssh".

5. Click the "Next" button to start downloading and installing the packages. If the download fails, choose another mirror, double-check your package selections (my copy remembered which packages I had already selected), and try again. The base install size required around 7MB of downloads and expanded out to 24MB (34MB actual due to a 4KB cluster size).

6. Fire up the cygwin shell, you should see a command-line window open with a "$" prompt. Try out a few unix commands (pwd, ls, whoami) to see if things are working.

7. Further steps... (I'll cover these in future posts)

a) Setup your rsync.conf file (in the "etc" folder)
b) create a service account for use by the rsync service
c) create a Windows service using the "cygrunsvc" tool
d) setup OpenSSH and then re-configure rsync to use it

Labels: ,

Hacking together a minimal rsync for windows installation
Based on what I've read elsewhere (links in my previous posting), I think I can pull the relevant pieces out of the Cygwin package. I'll try to keep good notes as to what worked and what didn't, but let me know if you find any errors. Rsync wrapper for Win32 seems to be a good starting point for which DLLs and files I'll need to pull out of the standard Cygwin release.

You can download the files off of any of the Cygwin public mirrors. Grab the following archives and extract them to a temporary directory on your machine.

release/cygwin/cygwin-1.5.10-3.tar.bz2
- contains the DLL file (usr/bin/cygwin1.dll) and a lot of base utilities

release/popt/libpopt0/libpopt0-1.6.4-4.tar.bz2
- contains the usb/bin/cygpopt-0.dll file

release/rsync/rsync-2.6.2-1.tar.bz2
- RSync (rsync executable)

Create a folder where you're going to store the rsync files (I use C:\bin\rsync).

Copy the following files to your rsync folder:
cygwin1.dll

cygpopt-0.dll

rsync.exe


Create your rsync.conf file and put it in your rsync folder.

Test out whether you've gotten rsync working (thanks to "Aaron Johnson's page about rsync" for showing me what command line options to use). To do this, type the following commands:
c:

cd \bin\rsync

rsync --config="c:\bin\rsync\rsyncd.conf" --daemon

If you have a log file, there should now be an entry indicating that rsync has started up and is listening on the default port (tcp/873). Looking at the processes in Windows Task Manager, you should see the "rsync.exe" process. You should also now test out some rsync transfers from another workstation to verify that your security settings and module settings are correct.

To do:
- create the user account to use for the rsync service
- setup rsync to run as a service (need the SRVANY.EXE file, I think)
- figure out how to get rsync talking through an SSHD server

Labels: ,

RSync and Windows
This is a follow-up to my previous post about Securing cwRSync. We were using the "cwRSync package", but when running in server mode it doesn't know how to talk to clients over an SSH-encrypted connection. Which isn't a big deal if you're only talking to other servers on the local network, but is problematic in cases where you have to be wary of eavesdropping (across WiFi links or untrusted networks like the internet). So I've been looking off-and-on over the past month at figuring out how to get an rsync service running using SSH on a Windows server.

One option is to install the full Cygwin package. Which is a bit much for a server (or rather, I'm not comfortable installing Cygwin on a server... yet).

Another option seems to be the OpenSSH for Windows project at SourceForge. That doesn't include rsync though, just scp. So I might look at "Installing ssh and rsync on a Windows machine: minimalist approach" which requires an absolute bare minimum of files to be installed. However, the files at that location are from Jan 2002, which is a bit old and the latest version as of July 2004 for the Cygwin DLL is cygwin-1.5.10-2.

Labels: ,

Friday, June 18, 2004
Securing cwRSync
At the office we're working on setting up cwRSync on the web server array to push the daily web/ftp/smtp log files back to a central point for archiving. Right now, since all of the web servers are on the same LAN segment at the hosting facility, we're just sending the plain text data across the wire to the rsync port (tcp/873). Since the previous solution was to use FTP to move the log files around, it's no worse then the old solution from a security standpoint. (It is, however, much faster and more efficient.) Security is handled solely thorugh the rsyncd.conf "hosts allow" setting (only the internal IP addresses are allowed to be used to transfer the data) with no passwords or shared keys.

However, since the next step is that we want to setup pulling those log files automatically back to the main office, we need to look into locking it down further and putting encryption in place (e.g. routing rsync traffic over an ssh tunnel).

After digging around a bit here's what I've found:

The cwRSync Service does not support SSH, so there's no way to connect securely to a rsync server that is using cwRSync as its daemon. Future releases are expected to add ssh support for cwRSync servers. Locking down through IP address and username/password is the limit of what you can do for security, all traffic is in the clear (unless you have IPSec between the two machines).

However, you can use cwRSync in a client-configuration and route the traffic over SSH to a SSH-capable rsync server.

That being said, I'm going to explore some other packages. All of which will either require that cygwin be installed, or at least that certain cygwin DLLs be installed.

Links:

Rsync wrapper for Win32 - Uses the cygwin DLLs, but doesn't require a full cygwin install, includes SSH.

Labels: ,

Thursday, June 10, 2004
Installing cwRSync on Windows 2000
The instructions over at cwRSync's install page are a bit vague, so I'm going to jot down the steps that I use. These steps are for installing rsync in a server configuration. Since the install process needs to (optionally) create an user account and create a new service, you'll need administrative access to the machine that you are using. (I'm not sure whether members of the Power Users group have enough privileges.)

  1. Download cwRSync, open up the ZIP file, then extract/run cwRsync_x.x.x_Installer.exe.
  2. Answer "Yes" when asked if you want to continue with the install.
  3. Answer "Yes" when asked if you want to install cwRSync as a Windows Service.
  4. Specify the installation folder where you want to install cwRSync. My personal preference is "c:\bin\cwrsync" instead of the default since our servers already have various command line tools installed under c:\bin.
  5. Enter the account name and password of the local user account that you are going to use for the cwRSync service. It's a good idea to use a seperate account for the cwRSync service, but you may also specify an existing account name.
  6. The upload area can be set to anything. In fact, you'll probably be removing whatever you set here when you configure your rsyncd.conf file. For now, set it to be a sub-folder under where you installed the cwRSync executables to.
  7. Click the "Install" button. The installer will then create the folder where cwRSync is being installed to, (optionally) create the user account for the cwRSync service, and it will set restrictive permissions on the install folder so that only the service's user account has rights.
  8. That takes care of the basics. If you want, view the installation details prior to exiting the install program and cleaning up. Read the instructions on the popup dialog.

Next, we need to finish setting up the RSync service in Windows.

  1. Right-click on My Computer, pick "Manage".
  2. In the left panel, scroll down and open up the "Services and Applications" tree, then select "Services".
  3. Locate the "RsyncServer" service and double-click to open up the properties dialog.
  4. "General" tab: Change the "Startup type" setting to "Automatic".
  5. "Log On" tab: Re-type the password for the user account that you're using. Click the "Apply" button to save your changes and Windows will popup a notification that the user account has been granted the rights to logon as a service.
  6. "Recovery" tab: Change these to match your preferences. My personal preference is to restart the service on the first two failures, do nothing on subsequent failures, reseting the fail count after 1 day and restarting the service after a delay of 30 minutes.
  7. Click "OK" to save and exit.
  8. Don't start the service yet, the rsyncd.conf file needs to be configured first.

You need to configure the rsyncd.conf file and set up your first "module" (a.k.a. a share path). Find your rsyncd.conf file (it's in the folder where you installed cwRSync to) and open it up in a text editor (NotePad works). Now, go read the official rsyncd.conf help page. Read it twice if it's your first time, because it's possible to put a very large gaping security hole into your setup if you're not careful. The default settings at the top of the file are fine, but you may wish to change the "hosts allow = *" to "hosts allow = (your client machine IPs)" as a preventative first step. Then, even if you screw up the other security mechanisms, you've at least limited which IP addresses an attacker can base an attack from. (You can test this by telnet'ing to port 873 and seeing whether the rsync service drops your connection.)

Next, we need to start setting up "modules" in the rsyncd.conf file. "Modules" are basically the same concept as a Windows share, except that you have to use rsync to access the files within the "module". Ignore what it says on the cwRSync install page about rsync modules having to be sub-directories under the cwrsync folder. If you grant correct directory permissions to the cwRSync service account, then the service daemon will be able to read or read/write to the target folders without problems.

The default module installed is called "test". Go ahead and comment it out with '#' symbols and save the file. From my (limited) testing, it does not appear to be necessary to restart the rsync service in order for it to see changes in the rsyncd.conf file.

[test]

path = /cygdrive/c/cwrsync/data

read only = false

transfer logging = yes



There are two basic ways to use rsync and this will affect how you grant permissions to the rsync service account.

The first is a read-only ("pull") setup, where the clients can only pull files from the rsync server. The rsync service account should only have Read & Execute / List Folder Contents / Read permissions for the folder tree that you are going to publish. In addition, when you setup your module in the configuration file, you should specify "read only = true" as a setting.

The second is a "push" setup where clients are writing changes to the rsync server. The rsync service account will require "modify" permissions for the shared directory tree. Under your module configuration section in the rsyncd.conf file, a "push" setup must have "read only = false".

Now, for every directory tree on the rsync server that you wish to share, create a new module section (e.g. "[logs]" or "[web]" or "[joes_backup]"). Verify that the cwRSync service account has proper permissions to the file system tree. Then add the following options (at a minimum) below the module section name:

[joes_backup]

path = /cygdrive/e/backup/joe

read only = false



That allows any client who manages to authenticate with the rsync service to write the E:\Backup\Joe on the rsync server. That is not exactly secure and you should take additional steps to lock it down through the use of "hosts allow", "auth users", "secrets file" and perhaps ssh. Securing your box is a bit beyond the scope of this post. It's also a bit beyond my experience level since I'm just getting started with rsync.

(Update: See Securing cwRSync.)

Labels: ,


Wednesday, September 9, 2009

rsync

SkyHi @ Wednesday, September 09, 2009
#!/bin/sh
backupSystemName=backupserver
backupSystemUser=backupuser
# rsync
echo "[backup/thedump] $HOSTNAME - `date` " > /tmpdirectory/.output
echo "------------------------------------" >> /tmpdirectory/.output
echo "directory: /etc" >> /tmpdirectory/.output
rsync -v -r -u -L --bwlimit=200 --delete --delete-excluded -e ssh -z /etc $backupSystemUser@$backupSystemName:/backupdirectory/$HOSTNAME >> /tmpdirectory/.output
echo "------------------------------------" >> /tmpdirectory/.output
echo "directory: /home" >> /tmpdirectory/.output
rsync -v -r -u -L --bwlimit=200 --delete --delete-excluded -e ssh -z /home $backupSystemUser@$backupSystemName:/backupdirectory/$HOSTNAME >> /tmpdirectory/.output
echo "------------------------------------" >> /tmpdirectory/.output
echo "directory: /usr/local" >> /tmpdirectory/.output
rsync -v -r -u -L --bwlimit=200 --delete --delete-excluded -e ssh -z --exclude apache/logs/ /usr/local $backupSystemUser@$backupSystemName:/backupdirectory/$HOSTNAME >> /tmpdirectory/.output
echo "------------------------------------" >> /tmpdirectory/.output
echo "directory: /root" >> /tmpdirectory/.output
rsync -v -r -u -L --bwlimit=200 --delete --delete-excluded -e ssh -z /root $backupSystemUser@$backupSystemName:/backupdirectory/$HOSTNAME >> /tmpdirectory/.output
echo "------------------------------------" >> /tmpdirectory/.output
echo "directory: /var" >> /tmpdirectory/.output
rsync -v -r -u -L --bwlimit=200 --delete --delete-excluded -e ssh -z --exclude /var/mail/ --exclude /var/log/ --exclude /var/spool/ /var $backupSystemUser@$backupSystemName:/backupdirectory/$HOSTNAME >> /tmpdirectory/.output
echo "------------------------------------" >> /tmpdirectory/.output
echo "complete." >> /tmpdirectory/.output
mail -s "[backup/thedump] $HOSTNAME - `date`" sysadmin@server < /tmpdirectory/.output

Wednesday, August 26, 2009

How To Set Red hat / CentOS Linux Remote Backup / Snapshot ServerHow To Set Red hat / CentOS Linux Remote Backup / Snapshot Server

SkyHi @ Wednesday, August 26, 2009
Q. I've HP RAID 6 server running RHEL 5.x. I'd like to act this box as a backup server for my other Red Hat DNS and Web server. The server must keep backup in hourly, daily and monthly format. How do I configure my Red Hat / CentOS Linux server as remote backup or snapshot server?

A. rsnapshot is easy, reliable and disaster recovery backup solution. It is a remote backup program that uses rsync to take backup snapshots of filesystems. It uses hard links to save space on disk and offers following features:

* Filesystem snapshot - for local or remote systems.
* Database backup - MySQL backup
* Secure - Traffic between remote backup server is always encrypted using openssh
* Full backup - plus incrementals
* Easy to restore - Files can restored by the users who own them, without the root user getting involved.
* Automated backup - Runs in background via cron.
* Bandwidth friendly - rsync used to save bandwidth

Sample setup

* snapshot.example.com - HP box with RAID 6 configured with Red Hat / CentOS Linux act as backup server for other clients.
* DNS ns1.example.com - Red Hat server act as primary name server.
* DNS ns2.example.com - Red Hat server act as secondary name server.
* www.example.com - Red Hat running Apache web server.
* mysql.example.com - Red Hat mysql server.

Install rsnapshot

Login to snapshot.example.com. Download rsnapshot rpm file, enter:
[Warning examples only works on Red Hat / CentOS / Fedora Linux] WARNING! These examples only works on Red hat / CentOS / Suse / RHEL / Fedora Linux. See Debian / Ubuntu Linux backup server instructions here.

# cd /tmp
# wget http://www.rsnapshot.org/downloads/rsnapshot-1.3.0-1.noarch.rpm
# wget http://www.rsnapshot.org/downloads/rsnapshot-1.3.0-1.noarch.rpm.md5
Verify rpm file for integrity, enter
# md5sum -c rsnapshot-1.3.0-1.noarch.rpm.md5
Sample output:

rsnapshot-1.3.0-1.noarch.rpm: OK

Install rsnapshot, enter:
# rpm -ivh rsnapshot-1.3.0-1.noarch.rpm
Sample output:

Preparing... ########################################### [100%]
1:rsnapshot ########################################### [100%]

Configure rsnapshot

You need to perform following steps
Step # 1: Configure password less login

To perform remote backup you need to setup password less login using openssh. Create ssh rsa key and upload they to all servers using scp (note you are overwriting ~/ssh/authorized_keys2 files). You need to type following commands on snapshot.example.com server:
# ssh-keygen -t rsa
# scp .ssh/id_rsa.pub root@ns1.example.com:.ssh/authorized_keys2
# scp .ssh/id_rsa.pub root@ns2.example.com:.ssh/authorized_keys2
# scp .ssh/id_rsa.pub root@www.example.com:.ssh/authorized_keys2
# scp .ssh/id_rsa.pub root@mysql.example.com:.ssh/authorized_keys2
Step # 2: Configure rsnapshot

The default configuration file is located at /etc/rsnapshot.conf. Open configuration file using a text editor, enter:
# vi /etc/rsnapshot.conf
Configuration rules

You must follow two configuration rules:

* rsnapshot config file requires tabs between elements.
* All directories require a trailing slash. For example, /home/ is correct way to specify directory, but /home is wrong.

First, specify root directory to store all snapshots such as /snapshots/ or /dynvol/snapshot/ as per your RAID setup, enter:

snapshot_root /raiddisk/snapshots/

You must separate snapshot_root and /raiddisk/snapshots/ by a [tab] key i.e. type snapshot_root hit [tab] key once and type /raiddisk/snapshots/.
Define snapshot intervals

You need to specify backup intervals i.e. specify hourly, daily, weekly and monthly intervals:

interval hourly 6
interval daily 7
interval weekly 4
interval monthly 3

The line "interval hourly 6" means 6 hourly backups a day. Feel free to adapt configuration as per your backup requirements and snapshot frequency .
Remote backup directories

To backup /var/named/ and /etc/ directory from ns1.example.com and ns2.example.com, enter:

backup root@ns1.example.com:/etc/ ns1.example.com/
backup root@ns1.example.com:/var/named/ ns1.example.com/
backup root@ns2.example.com:/etc/ ns2.example.com/
backup root@ns2.example.com:/var/named/ ns2.example.com/

To backup /var/www/, /var/log/httpd/ and /etc/ directory from www.example.com, enter

backup root@www.example.com:/var/www/ www.example.com/
backup root@www.example.com:/etc/ www.example.com/
backup root@www.example.com:/var/log/httpd/ www.example.com/

To backup mysql database files stored at /var/lib/mysql/, enter:

backup root@mysql.example.com:/var/lib/mysql/ mysql.example.com/dbdump/

Save and close the file. To test your configuration, enter:
# rsnapshot configtest
Sample output:

Syntax OK

Schedule cron job

Create /etc/cron.d/rsnapshot cron file. Following values used correspond to the examples in /etc/rsnapshot.conf.

0 */4 * * * /usr/bin/rsnapshot hourly
50 23 * * * /usr/bin/rsnapshot daily
40 23 * * 6 /usr/bin/rsnapshot weekly
30 23 1 * * /usr/bin/rsnapshot monthly

Save and close the file. Now rsnapshot will work as follows to backup files from remote boxes:

1. 6 hourly backups a day (once every 4 hours, at 0,4,8,12,16,20)
2. 1 daily backup every day, at 11:50PM
3. 1 weekly backup every week, at 11:40PM, on Saturdays (6th day of week)
4. 1 monthly backup every month, at 11:30PM on the 1st day of the month

How do I see backups?

To see backup change directory to
# cd /raiddisk/snapshots/
# ls -l
Sample output:

drwxr-xr-x 4 root root 4096 2008-07-04 06:04 daily.0
drwxr-xr-x 4 root root 4096 2008-07-03 06:04 daily.1
drwxr-xr-x 4 root root 4096 2008-07-02 06:03 daily.2
drwxr-xr-x 4 root root 4096 2008-07-01 06:02 daily.3
drwxr-xr-x 4 root root 4096 2008-06-30 06:02 daily.4
drwxr-xr-x 4 root root 4096 2008-06-29 06:05 daily.5
drwxr-xr-x 4 root root 4096 2008-06-28 06:04 daily.6
drwxr-xr-x 4 root root 4096 2008-07-05 18:05 hourly.0
drwxr-xr-x 4 root root 4096 2008-07-05 15:06 hourly.1
drwxr-xr-x 4 root root 4096 2008-07-05 12:06 hourly.2
drwxr-xr-x 4 root root 4096 2008-07-05 09:05 hourly.3
drwxr-xr-x 4 root root 4096 2008-07-05 06:04 hourly.4
drwxr-xr-x 4 root root 4096 2008-07-05 03:04 hourly.5
drwxr-xr-x 4 root root 4096 2008-07-05 00:05 hourly.6
drwxr-xr-x 4 root root 4096 2008-07-04 21:05 hourly.7
drwxr-xr-x 4 root root 4096 2008-06-22 06:04 weekly.0
drwxr-xr-x 4 root root 4096 2008-06-15 09:05 weekly.1
drwxr-xr-x 4 root root 4096 2008-06-08 06:04 weekly.2

How do I restore backup?

Let us say you would like to restore a backup for www.example.com. Type the command as follows (select day and date from ls -l output):
# cd /raiddisk/snapshots/
# ls -l
# cd hourly.0/www.example.com/
# scp -r var/www/ root@www.example.com:/var/www/
# scp -r etc/httpd/ root@www.example.com:/etc/httpd/
How do I exclude files from backup?

To exclude files from backup, open rsnapshot.conf file and add following line:

exclude_file /etc/rsnapshot.exclude.www.example.com

Create /etc/rsnapshot.exclude.www.example.com as follows:

/var/www/tmp/
/var/www/*.cache

Reference: http://www.cyberciti.biz/faq/redhat-cetos-linux-remote-backup-snapshot-server/

Friday, August 21, 2009

rsync test tutorial

SkyHi @ Friday, August 21, 2009
###initialize this script on the destination host
#rsync -u -v -r --bwlimit=2000 root@backupserver:/backup2/ns1.home.com /mnt/sda/ns1.home.com

##Archive 2 directories(html and test1) to /mnt/sda
#cd /mnt/sda
#tar cvf /mnt/sda/backup2009.rar /var/www/html /var/www/test1


Test 2: LOCAL MACHINE SYNC

[root@jud sda]# mkdir -p home/ftp

[root@jud ftp]# pwd
/mnt/sda/home/ftp


###source
root@jud vista_temp]# touch derek.test
[root@jud vista_temp]# ll
total 0
-rw-r--r-- 1 root root 0 Jan 29 11:23 derek.test


###vista_temp will be created in destination /mnt/sda/home/ftp/vista_temp
[root@jud sda]# cat rsyncvista_temp.sh
rsync --bwlimit=200 -v -z -r -L -t /home/ftp/vista_temp /mnt/sda/home/ftp >> /mnt/sda/vista_temp.log


###destination
[root@jud ftp]# cd vista_temp/
[root@jud vista_temp]# ll
total 0
-rw-r--r-- 1 root root 0 Jan 29 11:19 derek.test



Test 3: add --delete //delete extraneous files from dest dirs

[root@jud vista_temp]# touch derek.new
[root@jud vista_temp]# rm derek.test
rm: remove regular empty file `derek.test'? y
[root@jud vista_temp]# ll
total 0
-rw-r--r-- 1 root root 0 Jan 29 11:19 derek.new



[root@jud sda]# cat rsyncvista_tempdelete.sh
rsync --bwlimit=200 -v -z -r -L -t --delete /home/ftp/vista_temp /mnt/sda/home/ftp >> /mnt/sda/vista_temp.log


###Source intact
[root@jud vista_temp]# pwd
/home/ftp/vista_temp
[root@jud vista_temp]# ll
total 0
-rw-r--r-- 1 root root 0 Jan 29 11:19 derek.new
-rw-r--r-- 1 root root 0 Jan 29 11:23 derek.test


###destination updated
[root@jud vista_temp]# pwd
/mnt/sda/home/ftp/vista_temp
[root@jud vista_temp]# ll
total 0
-rw-r--r-- 1 root root 0 Jan 29 11:19 derek.new


##check log
[root@jud sda]# cat vista_temp.log
building file list ... done
building file list ... done
vista_temp/
vista_temp/derek.test

sent 112 bytes received 48 bytes 320.00 bytes/sec
total size is 0 speedup is 0.00
building file list ... done
deleting vista_temp/derek.test
vista_temp/
vista_temp/derek.new

sent 115 bytes received 48 bytes 326.00 bytes/sec
total size is 0 speedup is 0.00









# man rsync

EXAMPLES
Here are some examples of how I use rsync.

To backup my wifeâs home directory, which consists of large MS Word files and mail
folders, I use a cron job that runs

rsync -Cavz . arvidsjaur:backup

each night over a PPP connection to a duplicate directory on my machine "arvidsjaur".

To synchronize my samba source trees I use the following Makefile targets:

get:
rsync -avuzb --exclude â*~â samba:samba/ .
put:
rsync -Cavuzb . samba:samba/
sync: get put

this allows me to sync with a CVS directory at the other end of the connection. I
then do CVS operations on the remote machine, which saves a lot of time as the remote
CVS protocol isnât very efficient.

I mirror a directory between my "old" and "new" ftp sites with the command:

rsync -az -e ssh --delete ~ftp/pub/samba nimbus:"~ftp/pub/tridge"

This is launched from cron every few hours.


OPTIONS SUMMARY
Here is a short summary of the options available in rsync. Please refer to the
detailed description below for a complete description.

-v, --verbose increase verbosity
-q, --quiet suppress non-error messages
--no-motd suppress daemon-mode MOTD (see caveat)
-c, --checksum skip based on checksum, not mod-time & size
-a, --archive archive mode; equals -rlptgoD (no -H,-A,-X)
--no-OPTION turn off an implied OPTION (e.g. --no-D)
-r, --recursive recurse into directories
-R, --relative use relative path names
--no-implied-dirs donât send implied dirs with --relative
-b, --backup make backups (see --suffix & --backup-dir)
--backup-dir=DIR make backups into hierarchy based in DIR
--suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)
-u, --update skip files that are newer on the receiver
--inplace update destination files in-place
--append append data onto shorter files
-d, --dirs transfer directories without recursing
-l, --links copy symlinks as symlinks
-L, --copy-links transform symlink into referent file/dir
--copy-unsafe-links only "unsafe" symlinks are transformed
--safe-links ignore symlinks that point outside the tree
-k, --copy-dirlinks transform symlink to dir into referent dir
-K, --keep-dirlinks treat symlinked dir on receiver as dir
-H, --hard-links preserve hard links
-p, --perms preserve permissions
-E, --executability preserve executability
--chmod=CHMOD affect file and/or directory permissions
-A, --acls preserve ACLs (implies -p) [non-standard]
-X, --xattrs preserve extended attrs (implies -p) [n.s.]
-o, --owner preserve owner (super-user only)
-g, --group preserve group
--devices preserve device files (super-user only)
--specials preserve special files
-D same as --devices --specials
-t, --times preserve times
-O, --omit-dir-times omit directories when preserving times
--super receiver attempts super-user activities
-S, --sparse handle sparse files efficiently
-n, --dry-run show what would have been transferred
-W, --whole-file copy files whole (without rsync algorithm)
-x, --one-file-system donât cross filesystem boundaries
-B, --block-size=SIZE force a fixed checksum block-size
-e, --rsh=COMMAND specify the remote shell to use
--rsync-path=PROGRAM specify the rsync to run on remote machine
--existing skip creating new files on receiver
--ignore-existing skip updating files that exist on receiver
--remove-source-files sender removes synchronized files (non-dir)
--del an alias for --delete-during
--delete delete extraneous files from dest dirs
--delete-before receiver deletes before transfer (default)
--delete-during receiver deletes during xfer, not before
--delete-after receiver deletes after transfer, not before
--delete-excluded also delete excluded files from dest dirs
--ignore-errors delete even if there are I/O errors
--force force deletion of dirs even if not empty
--max-delete=NUM donât delete more than NUM files
--max-size=SIZE donât transfer any file larger than SIZE
--min-size=SIZE donât transfer any file smaller than SIZE
--partial keep partially transferred files
--partial-dir=DIR put a partially transferred file into DIR
--delay-updates put all updated files into place at end
-m, --prune-empty-dirs prune empty directory chains from file-list
--numeric-ids donât map uid/gid values by user/group name
--timeout=TIME set I/O timeout in seconds
-I, --ignore-times donât skip files that match size and time
--size-only skip files that match in size
--modify-window=NUM compare mod-times with reduced accuracy
-T, --temp-dir=DIR create temporary files in directory DIR
-y, --fuzzy find similar file for basis if no dest file
--compare-dest=DIR also compare received files relative to DIR
--copy-dest=DIR ... and include copies of unchanged files
--link-dest=DIR hardlink to files in DIR when unchanged
-z, --compress compress file data during the transfer
--compress-level=NUM explicitly set compression level
-C, --cvs-exclude auto-ignore files in the same way CVS does
-f, --filter=RULE add a file-filtering RULE
-F same as --filter=âdir-merge /.rsync-filterâ
repeated: --filter=â- .rsync-filterâ
--exclude=PATTERN exclude files matching PATTERN
--exclude-from=FILE read exclude patterns from FILE
--include=PATTERN donât exclude files matching PATTERN
--include-from=FILE read include patterns from FILE
--files-from=FILE read list of source-file names from FILE
-0, --from0 all *from/filter files are delimited by 0s
--address=ADDRESS bind address for outgoing socket to daemon
--port=PORT specify double-colon alternate port number
--sockopts=OPTIONS specify custom TCP options
--blocking-io use blocking I/O for the remote shell
--stats give some file-transfer stats
-8, --8-bit-output leave high-bit chars unescaped in output
-h, --human-readable output numbers in a human-readable format
--progress show progress during transfer
-P same as --partial --progress
-i, --itemize-changes output a change-summary for all updates
--out-format=FORMAT output updates using the specified FORMAT
--log-file=FILE log what weâre doing to the specified FILE
--log-file-format=FMT log updates using the specified FMT
--password-file=FILE read password from FILE
--list-only list the files instead of copying them
--bwlimit=KBPS limit I/O bandwidth; KBytes per second
--write-batch=FILE write a batched update to FILE
--only-write-batch=FILE like --write-batch but w/o updating dest
--read-batch=FILE read a batched update from FILE
--protocol=NUM force an older protocol version to be used
--checksum-seed=NUM set block/file checksum seed (advanced)
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
--version print version number
(-h) --help show this help (see below for -h comment)

Rsync can also be run as a daemon, in which case the following options are accepted:

--daemon run as an rsync daemon
--address=ADDRESS bind to the specified address
--bwlimit=KBPS limit I/O bandwidth; KBytes per second
--config=FILE specify alternate rsyncd.conf file
--no-detach do not detach from the parent
--port=PORT listen on alternate port number
--log-file=FILE override the "log file" setting
--log-file-format=FMT override the "log format" setting
--sockopts=OPTIONS specify custom TCP options
-v, --verbose increase verbosity
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
-h, --help show this help (if used after --daemon)

Tuesday, August 18, 2009

rsync, root and sudo

SkyHi @ Tuesday, August 18, 2009
Here is the thing, the other day I wanted to copy one subdirectory from one computer to another, I can not rely on scp because I needed root permissions, neither tar worked because there was symlinks, different file permissions and owners, and there wasn’t space enough to do it (of course, you can send the tar using netcat…). The perfect solution to do such a copy is use rsync, it works nice, and can be used to reupdate a backup, and so on.

The problem is I need both root permissions on both machines, on the local machine having root permissions is the easy part but how should we proceed to get root permissions at the other end ?

You can do several things, like creating the root user, disable sudo asking for password, … but I won’t recommend them. The solution I came across ( I don’t remember from where ) is simple, but quite forgivable (that’s why I’m writing a post-to-myself). Here it is:
view plaincopy to clipboardprint?

1. stty -echo; ssh myUser@REMOTE_SERVER "sudo -v"; stty echo
2. rsync -avze ssh --rsync-path='sudo rsync' myUser@REMOTE_SERVER:/REMOTE_PATH/ LOCAL_PATH

stty -echo; ssh myUser@REMOTE_SERVER "sudo -v"; stty echo
rsync -avze ssh --rsync-path='sudo rsync' myUser@REMOTE_SERVER:/REMOTE_PATH/ LOCAL_PATH

The second line tells sudo to execute “sudo rsync” instead of “rsync” on the remote host. Without the first line sudo will prompt for a password (and we won’t be able to input it), the “sudo -v” is the one which does the trick. It simply touches the timestamp sudo has to avoid asking the password on each call.

The “stty [-]echo” avoid others to have a look at our passwords while we type them


Reference: http://www.pplux.com/2009/02/07/rsync-root-and-sudo/

Monday, August 10, 2009

rsync --delete --delete-excluded

SkyHi @ Monday, August 10, 2009
[root@web20 home]# ls -tlrh
total 12K
drwx------ 4 derek derek 4.0K Aug 6 09:26 derek
drwxr-xr-x 2 root root 4.0K Aug 10 11:13 derek2
-rw-r--r-- 1 root root 0 Aug 10 11:21 file100
[root@web20 home]#


[root@web20 home]# pwd
/home1/home
[root@web20 home]# ls -tlrh
total 8.0K
drwx------ 4 root root 4.0K Aug 10 11:11 derek
drwxr-xr-x 2 root root 4.0K Aug 10 11:14 derek2
-rw-r--r-- 1 root root 0 Aug 10 11:21 file100


root@web20 home]# rsync -v -r -u -L --bwlimit=200 -delete --delete-excluded /home /home1 >> /tmp/.report

--del an alias for --delete-during
--delete delete files that don’t exist on sender
--delete-before receiver deletes before transfer (default)
--delete-during receiver deletes during xfer, not before
--delete-after receiver deletes after transfer, not before
--delete-excluded also delete excluded files on receiver

#from web10
#rsync -e ssh -avz --bwlimit=200 --delete root@web1.sample.com:/var/www/html /var/www >> web11.rsync.report