Securely Transfer
Files Between Systems

Securely transfer files between systems

CIS126RH | RHEL System Administration 1
Mesa Community College

Moving files between Linux systems securely is a daily administration task — copying configuration files to remote servers, pulling log archives, synchronising directories, or deploying scripts. RHEL provides several tools built on SSH that encrypt both the authentication credentials and the transferred data: scp, sftp, and rsync. This module covers the syntax, use cases, and options for each tool. Secure file transfer is tested on the RHCSA exam.

Learning Objectives

  1. Transfer files with scp — Use scp to copy individual files and directory trees between local and remote systems in either direction
  2. Use sftp for interactive file transfer — Connect to a remote system with sftp, navigate directories, and upload and download files interactively
  3. Synchronise directories with rsync — Use rsync to efficiently copy and synchronise directory trees, transferring only changed files
  4. Use SSH key authentication for passwordless transfer — Understand how SSH keys enable automated and passwordless file transfer and configure ssh-copy-id for key distribution

Why Secure Transfer Matters

Legacy file transfer tools send data in plain text across the network — anyone who can capture the network traffic can read the contents and credentials.

Tool Encryption Status on RHEL 9
ftp None — credentials and data in plain text Not installed; use sftp instead
telnet None — all traffic including passwords visible Not installed; use ssh instead
rcp None — legacy remote copy Not installed; use scp instead
scp SSH encryption — full confidentiality and integrity Installed — part of openssh-clients
sftp SSH encryption — full confidentiality and integrity Installed — part of openssh-clients
rsync SSH encryption when used with -e ssh (default) Installed — part of rsync package

scp: Secure Copy Protocol

scp copies files between hosts using SSH for transport. It is the closest equivalent to cp for remote systems.

# General syntax
# scp [OPTIONS] SOURCE DESTINATION
# Remote path format:  user@host:/path/to/file

# Copy a file FROM local TO remote
$ scp /etc/hosts student@servera:/tmp/hosts.bak

# Copy a file FROM remote TO local
$ scp student@servera:/var/log/messages /tmp/servera-messages

# Copy between two remote hosts (via the local machine)
$ scp student@servera:/etc/hosts student@serverb:/tmp/

# Use a specific SSH port with -P (capital P)
$ scp -P 2222 myfile.txt student@servera:/tmp/
Remote path format: user@host:/path

The colon after the hostname separates the host from the path. A trailing slash on the destination copies the file into that directory using its original name. An absolute path starting with / is required for non-home-directory destinations.

scp Options and Directory Transfers

# Copy an entire directory recursively with -r
$ scp -r /etc/ssh/ student@servera:/tmp/ssh-backup/

# Preserve timestamps, permissions, and ownership with -p
$ scp -p /etc/hosts student@servera:/tmp/

# Compress data during transfer with -C (useful on slow links)
$ scp -C largefile.tar student@servera:/tmp/

# Copy multiple files to a remote directory
$ scp /etc/hosts /etc/resolv.conf student@servera:/tmp/

# Quiet mode — suppress progress output (useful in scripts)
$ scp -q report.txt student@servera:/tmp/

# Use a specific identity (private key) file
$ scp -i ~/.ssh/mykey file.txt admin@servera:/tmp/
Flag Meaning
-rRecursive — copy directories and their contents
-pPreserve timestamps, permissions, and ownership
-P PORTSpecify SSH port (capital P)
-CEnable compression during transfer
-qQuiet — suppress progress meter and warnings
-i FILEIdentity file — private key to use for authentication

sftp: Interactive Secure File Transfer

sftp opens an interactive session for browsing the remote filesystem and transferring files — useful when you need to explore before transferring.

# Open an sftp session to a remote host
$ sftp student@servera
Connected to servera.
sftp>

# Navigate and explore the remote filesystem
sftp> pwd            # remote current directory
sftp> ls             # list remote directory
sftp> cd /var/log    # change remote directory

# Navigate the LOCAL filesystem (prefix with l)
sftp> lpwd           # local current directory
sftp> lls            # list local directory
sftp> lcd /tmp      # change local directory

# Transfer files
sftp> get messages             # download from remote to local
sftp> put /tmp/config.txt     # upload from local to remote
sftp> get -r logs/            # download a directory
sftp> put -r /etc/ssh/       # upload a directory
sftp> quit                     # exit the sftp session

sftp Commands Reference

Command Action Local equivalent
pwdPrint remote working directorylpwd
ls [path]List remote directorylls [path]
cd pathChange remote directorylcd path
mkdir pathCreate remote directorylmkdir path
rm fileDelete a remote file
rmdir dirDelete a remote directory
rename old newRename a remote file
get file [local]Download remote file to local
get -r dirDownload remote directory recursively
put file [remote]Upload local file to remote
put -r dirUpload local directory recursively
helpShow all available sftp commands
quit / exit / byeEnd the session
RHCSA Exam: get downloads, put uploads

get = remote → local (you get something from the server). put = local → remote (you put something on the server). Always check: which end has the file and which end needs it?

rsync: Efficient File Synchronisation

rsync transfers only the differences between source and destination — making large directory synchronisation fast and bandwidth-efficient.

  • Compares files by size and modification time (or checksum with -c)
  • Transfers only the changed blocks within modified files
  • Can delete files from the destination that no longer exist in the source
  • Works locally or over SSH to remote hosts
  • Ideal for incremental backups, directory mirroring, and deployment
# Sync a local directory to a remote host
$ rsync -av /var/www/html/ student@servera:/var/www/html/

# Pull from remote to local
$ rsync -av student@servera:/etc/ /backup/servera-etc/

# Local-to-local sync (no SSH needed)
$ rsync -av /home/ /backup/home/
Trailing slash matters in rsync

rsync -av /src/ copies the contents of src into the destination.
rsync -av /src copies the directory src itself into the destination. The trailing slash on the source is the most important rsync syntax detail.

rsync Options

# -a (archive) = -rlptgoD: recursive, preserve links, permissions,
#                times, group, owner, and device files
$ rsync -a /src/ /dst/

# -v (verbose) — show each file being transferred
$ rsync -av /src/ /dst/

# --delete — remove files from destination not in source
$ rsync -av --delete /src/ /dst/

# -z (compress) — compress data during transfer (saves bandwidth)
$ rsync -avz /src/ student@servera:/dst/

# --dry-run / -n — show what would be transferred without doing it
$ rsync -av --dry-run --delete /src/ /dst/

# --exclude — skip matching files or directories
$ rsync -av --exclude='*.log' --exclude='.git/' /src/ /dst/

# --progress — show per-file transfer progress
$ rsync -av --progress /largefiles/ student@servera:/backup/

SSH Key Authentication

All three file transfer tools use SSH for authentication. SSH key pairs enable passwordless authentication — essential for automated scripts and cron jobs.

Generate an SSH key pair

# Generate a new RSA key pair (private + public)
$ ssh-keygen -t ed25519
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/student/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Your identification has been saved in /home/student/.ssh/id_ed25519
Your public key has been saved in /home/student/.ssh/id_ed25519.pub

# Copy the public key to a remote host
$ ssh-copy-id student@servera
Number of key(s) added: 1
Now try logging into the machine with: ssh student@servera
How it works

ssh-copy-id appends the public key to ~/.ssh/authorized_keys on the remote host. The private key never leaves the local machine. The remote sshd verifies the public key to authenticate without a password.

SSH Key Files and Required Permissions

SSH is strict about file permissions on key files and the .ssh directory. Incorrect permissions prevent authentication from working.

# Required permissions for SSH key files
$ ls -la ~/.ssh/
drwx------. 2 student student  80 May 25 07:00 .
-rw-------. 1 student student 411 May 25 07:00 id_ed25519       # private key
-rw-r--r--. 1 student student 100 May 25 07:00 id_ed25519.pub   # public key
-rw-------. 1 student student 800 May 25 07:00 authorized_keys  # allowed public keys

# Fix permissions if they are wrong
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_ed25519
$ chmod 644 ~/.ssh/id_ed25519.pub
$ chmod 600 ~/.ssh/authorized_keys
File or directory Required permission Reason
~/.ssh/700 (rwx------)Only owner may read, write, or list
~/.ssh/id_ed25519600 (rw-------)Private key — owner only
~/.ssh/id_ed25519.pub644 (rw-r--r--)Public key — can be world-readable
~/.ssh/authorized_keys600 (rw-------)SSH refuses to read if group/world writable

Choosing the Right Tool

Scenario Best tool Reason
Copy one or a few files to/from a remote host scp Simple one-line syntax; fastest for small jobs
Explore a remote filesystem and selectively download files sftp Interactive browsing before transferring
Keep a directory in sync with a remote copy rsync Only transfers changed files; efficient for large trees
Nightly incremental backup over SSH rsync --delete mirrors the source; only changed data is sent
Deploy a website to a web server rsync Fast incremental updates; --delete removes stale files
Copy a file while preserving all metadata (permissions, timestamps) scp -p or rsync -a Both can preserve metadata; rsync -a is more complete
Automated script requiring no password prompt SSH key + rsync or scp Key authentication enables unattended transfer

Practical Examples

Back up a configuration file before editing it

# Copy the current sshd_config to a backup server
$ scp /etc/ssh/sshd_config admin@backup:/backups/sshd_config.$(date +%F)

Retrieve a log file from a remote server

# Download /var/log/messages from servera for local analysis
$ scp root@servera:/var/log/messages /tmp/servera-$(date +%F).log

Mirror a web root to a backup location nightly

# In a cron job — sync /var/www/html to a remote backup
$ rsync -az --delete /var/www/html/ backup@storageserver:/webbackups/html/

Deploy updated scripts to multiple servers

# Push updated scripts to servera and serverb
for HOST in servera serverb; do
    rsync -av /usr/local/bin/ admin@${HOST}:/usr/local/bin/
done

sftp in Non-Interactive (Batch) Mode

sftp can run commands from a file without an interactive session — enabling it to be used in scripts when an interactive session is not available.

# Create a batch file of sftp commands
$ cat transfer.sftp
cd /var/log
get messages /tmp/remote-messages
put /etc/hosts /tmp/hosts-backup
quit

# Execute the batch file against a remote host
$ sftp -b transfer.sftp student@servera
Fetching /var/log/messages to /tmp/remote-messages
Uploading /etc/hosts to /tmp/hosts-backup

# Use a here-document for inline batch commands
$ sftp student@servera <<'EOF'
cd /var/log
get secure /tmp/secure.log
quit
EOF
Batch mode requires key authentication

The -b flag runs sftp non-interactively — there is no terminal for a password prompt. Ensure SSH key authentication is configured before using sftp in scripts or batch files.

Secure File Transfer Quick Reference

Task Command
Copy local file to remotescp localfile user@host:/remote/path/
Copy remote file to localscp user@host:/remote/file /local/path/
Copy directory recursively to remotescp -r localdir/ user@host:/remote/
Copy preserving metadatascp -p localfile user@host:/remote/
Copy using non-default portscp -P 2222 file user@host:/path/
Open interactive sftp sessionsftp user@host
Download file in sftpget remotefile [localfile]
Upload file in sftpput localfile [remotefile]
Exit sftpquit
Sync local directory to remotersync -av localdir/ user@host:/remotedir/
Mirror with deletion of stale filesrsync -av --delete src/ user@host:/dst/
Preview rsync without transferringrsync -av --dry-run src/ dst/
Generate SSH key pairssh-keygen -t ed25519
Copy public key to remote hostssh-copy-id user@host

Common Mistakes

Mistake What goes wrong Correct approach
Using lowercase -p for scp port scp -p preserves metadata; the port flag is capital -P scp -P 2222 file user@host:/path/
Forgetting the colon in the remote path scp file user@host/path — interprets as a local path named "user@host/path" scp file user@host:/path — the colon separates host from path
rsync trailing slash confusion rsync -av /src /dst/ creates /dst/src/ instead of copying contents Add trailing slash to source: rsync -av /src/ /dst/
Using rsync --delete with wrong source Destination files are deleted because the wrong (possibly empty) source is specified Always run --dry-run first when using --delete
Confusing sftp get and put direction get downloads; put uploads — opposite of what some expect "get = get from server to me; put = put from me to server"
Wrong permissions on ~/.ssh/ files SSH refuses to use key files with permissions too open — key auth fails silently chmod 700 ~/.ssh; chmod 600 ~/.ssh/id_ed25519 ~/.ssh/authorized_keys

Knowledge Check

Answer these before moving to the next slide.

  1. Write the scp command to copy the local file /etc/hosts to the remote host servera as user student, placing it in /tmp/.
  2. Write the scp command to copy the entire directory /var/log/httpd/ from servera to the local directory /tmp/logs/, preserving file metadata.
  3. In an sftp session connected to servera, write the commands to: navigate to /var/log/ on the remote, then download the file messages to the local /tmp/ directory.
  4. Write the rsync command to synchronise the local directory /var/www/html/ to the remote directory /var/www/html/ on servera as user student, showing verbose output and deleting stale files.
  5. What is the required permission on the ~/.ssh/ directory and on a private key file such as ~/.ssh/id_ed25519?
  6. What is the difference between get and put in an sftp session?

Knowledge Check — Answers

  1. scp /etc/hosts student@servera:/tmp/
    The colon after the hostname separates the host from the remote path.
  2. scp -rp student@servera:/var/log/httpd/ /tmp/logs/
    -r for recursive directory copy; -p to preserve permissions, timestamps, and ownership. (Note: capital -P is for port, lowercase -p preserves metadata.)
  3. Inside the sftp session:
    cd /var/log — navigate to the remote log directory
    lcd /tmp — navigate the local directory to /tmp
    get messages — download the file to the current local directory (/tmp)
  4. rsync -av --delete /var/www/html/ student@servera:/var/www/html/
    The trailing slash after the source directory copies its contents rather than the directory itself.
  5. The ~/.ssh/ directory must have permission 700 (rwx------). A private key file such as ~/.ssh/id_ed25519 must have permission 600 (rw-------). SSH refuses to use key files that are readable by group or world.
  6. get downloads a file from the remote server to the local machine — remote → local. put uploads a file from the local machine to the remote server — local → remote.

Key Takeaways

  1. All three tools use SSH — they share the same encryption and key auth. scp for single files, sftp for interactive browsing, rsync for directory synchronisation. Remote paths use the format user@host:/path — the colon is required.
  2. scp: simple, non-interactive file copy. Use -r for directories, -p for metadata, and capital -P for a non-default port. Direction is always source then destination, same as cp.
  3. sftp: interactive — get downloads, put uploads. Prefix commands with l to operate locally (lcd, lls, lpwd). Use -b batchfile for scripted non-interactive transfers.
  4. rsync: efficient synchronisation — only transfers what changed. Always use -a to preserve metadata. The trailing slash on the source copies contents; without it, the directory itself is copied. Use --dry-run before --delete.

Graded Lab

  • Generate an SSH key pair with ssh-keygen -t ed25519. Use ssh-copy-id student@servera to copy the public key to servera. Verify passwordless login works with ssh student@servera.
  • Use scp to copy /etc/hosts from your local system to /tmp/ on servera. Then use scp to retrieve /var/log/messages from servera to /tmp/ locally.
  • Open an sftp session to servera. Navigate to /var/log/ on the remote. Use lcd /tmp to set the local destination. Download the secure log with get secure. Exit the session.
  • Create a test directory /tmp/source/ with three files. Use rsync -av /tmp/source/ student@servera:/tmp/dest/ to sync it. Then add a file to source and run rsync again — observe that only the new file is transferred.
  • Add --delete to the rsync command. Remove one file from /tmp/source/. Run rsync -av --dry-run --delete first to preview, then run without --dry-run to confirm the file is removed from the destination.
  • Verify the permissions on ~/.ssh/ and ~/.ssh/id_ed25519 with ls -la ~/.ssh/. Confirm they are 700 and 600 respectively.
RHCSA Objective

"Securely transfer files between systems." The exam tests scp to/from remote hosts and sftp get/put operations. Know the remote path format user@host:/path and the scp -r and -P flags.