How to Back Up Data on Tapes in Linux

how to do backup on tapes in linux

In an era of cloud storage and solid-state drives, magnetic tape might sound like a relic of the past — something out of a 1970s data center. But tape is very much alive, and for good reason: it remains one of the cheapest, most durable, and most secure ways to store massive amounts of data for long-term archival, especially for compliance, disaster recovery, and “cold storage” purposes.

This article explains tape backups on Linux from the ground up — how tape drives work, the tools used to control them (mt and tar), how to build a rotation strategy, and how modern approaches like LTFS make tape almost as easy to browse as a regular hard drive.


Why Tape Still Matters

AdvantageExplanation
Extremely low cost per terabyteTape media is dramatically cheaper than SSD or even spinning disk at scale
Long shelf lifeQuality tape media can reliably store data for 15–30 years if stored properly
Air-gapped securityA tape sitting on a shelf, physically disconnected, cannot be touched by ransomware or remote attackers
High capacityModern LTO tape cartridges hold many terabytes per cartridge
Regulatory complianceMany industries require offline, immutable, long-term archival — tape fits this perfectly

The tradeoff, of course, is speed — tape is sequential-access media, meaning to read a file near the end of a tape, the drive must physically wind through everything before it. This makes tape unsuitable for frequently-accessed data, but ideal for long-term archives and disaster-recovery-of-last-resort backups.


How Tape Storage Works

Unlike a hard drive or SSD, which can jump instantly to any location on the media (random access), tape is a sequential access medium — data is written and read in a straight line, like an old cassette tape.

flowchart LR
    A[Tape Start] --> B[File 1] --> C[File 2] --> D[File 3] --> E[...] --> F[Tape End]

To read “File 3,” the drive must physically wind past File 1 and File 2 first (unless it uses an index, discussed later). This is the fundamental tradeoff of tape: incredible cost-efficiency and durability, at the cost of slow random access.


Linux Tape Devices

When a tape drive is connected to a Linux system (often via SAS, Fibre Channel, or USB for smaller autoloaders), it typically appears as a device like:

/dev/st0     # rewinding tape device
/dev/nst0    # non-rewinding tape device

Rewinding vs. Non-Rewinding Devices

DeviceBehavior After Each Operation
/dev/st0 (rewinding)Automatically rewinds to the beginning after every operation
/dev/nst0 (non-rewinding)Stays at its current position — essential for writing multiple archives to one tape

For backup work involving multiple files/archives on a single tape, you almost always want the non-rewinding device (/dev/nst0), so each write picks up where the last one left off instead of overwriting from the start.


Step 1: Install Tape Tools

sudo apt install mt-st tar -y        # Debian/Ubuntu
sudo dnf install mt-st tar -y        # RHEL/CentOS

mt (“magnetic tape control”) is the primary tool for controlling tape drive operations — rewinding, ejecting, seeking, and erasing.


Step 2: Basic Tape Operations with mt

# Check tape drive status
mt -f /dev/nst0 status

# Rewind the tape to the beginning
mt -f /dev/st0 rewind

# Eject the tape
mt -f /dev/st0 offline

# Erase a tape completely
mt -f /dev/st0 erase

# Move forward by 2 file marks (skip past 2 archives)
mt -f /dev/nst0 fsf 2

# Move backward by 1 file mark
mt -f /dev/nst0 bsf 1

Step 3: Writing a Backup to Tape with tar

tar was originally designed for exactly this purpose — its name literally stands for Tape ARchive.

Writing Data to Tape

sudo tar -cvf /dev/nst0 /var/www /etc

This writes an archive of /var/www and /etc directly to the tape device, without creating an intermediate file on disk.

Writing Multiple Archives to the Same Tape

Because we used the non-rewinding device, we can write a second archive right after the first without overwriting it:

sudo tar -cvf /dev/nst0 /var/www
sudo tar -cvf /dev/nst0 /home
sudo tar -cvf /dev/nst0 /etc

Each tar command writes one “file” onto the tape, separated by a file mark, one after another:

flowchart LR
    A[Tape Start] --> B["Archive 1: /var/www"] --> C["Archive 2: /home"] --> D["Archive 3: /etc"] --> E[Tape End]

Reading Data Back from Tape

First, rewind to the beginning:

sudo mt -f /dev/st0 rewind

Then extract the first archive:

sudo tar -xvf /dev/nst0

To get to the second archive (/home), skip forward past the first file mark, then extract:

sudo mt -f /dev/nst0 fsf 1
sudo tar -xvf /dev/nst0

Listing Contents Without Extracting

sudo tar -tvf /dev/nst0

Step 4: Compression Considerations

Unlike disk backups, it’s usually best to let the tape drive’s own hardware compression handle compression rather than software compression like gzip, because:

  • Hardware compression is extremely fast (built into the drive controller)
  • Pre-compressed data (e.g., via tar -z) doesn’t compress further and may even slightly increase in size when passed through the drive’s compression engine
  • LTO drives typically achieve roughly 2:1 compression ratios on typical data

If you do want software compression for portability reasons, use it consistently and be aware it may reduce the tape drive’s own compression efficiency.


LTFS: Making Tape Behave Like a Disk

LTFS (Linear Tape File System) is a modern standard that lets you mount a tape and browse it like a regular filesystem — with visible files and folders — instead of using raw sequential tar streams.

sudo apt install ltfs -y

# Format a tape with LTFS
sudo mkltfs -d /dev/nst0

# Mount it like a regular filesystem
sudo mkdir /mnt/tape
sudo ltfs -o devname=/dev/nst0 /mnt/tape

# Now you can use normal file commands!
cp -r /var/www /mnt/tape/
ls /mnt/tape/

# Unmount when finished
sudo umount /mnt/tape

LTFS trades away a small amount of the raw efficiency of tar streaming in exchange for dramatically improved usability — a huge win for organizations that need occasional random access to archived files without a full tape read-through.


Comparison Table: Tape Backup Approaches

MethodEase of UseRandom File AccessEfficiencyBest For
Raw tar to /dev/nst0Moderate (CLI-based)No (sequential only)HighestLarge sequential archival backups
LTFSHigh (mount like a drive)Yes (within reason)Slightly lower overheadOrganizations needing occasional file browsing
Enterprise backup software (Bacula, Amanda, Veeam)High (GUI/managed)Managed via catalog/indexHighLarge-scale, multi-tape, multi-server environments

Real-World Example: Compliance Archival for a Financial Company

Scenario: A financial services company is legally required to retain transaction records for 7 years, with data that must be stored offline (air-gapped) for security compliance.

Solution:

  1. Monthly, a full database export and document archive is created.
  2. The archive is written to two LTO tape cartridges (tar -cvf /dev/nst0 ...), one kept onsite in a fireproof safe, one sent to an offsite secure storage facility — following the 3-2-1 principle from general backup strategy.
  3. Each tape is labeled with the date and a checksum file is also written to the tape for later integrity verification.
  4. Tapes older than 7 years are securely destroyed per company data retention policy.

Because the tapes are physically disconnected from any network after writing, they are completely immune to ransomware, remote attacks, or accidental deletion — a property no purely online backup system can fully match.


Cisco Example: Network Bandwidth Planning for Tape Libraries

While Cisco hardware doesn’t interact with tape directly, tape backup systems (especially large tape libraries/autoloaders) often sit on a dedicated backup network segment to avoid saturating production bandwidth during large backup windows. A typical Cisco QoS configuration prioritizes production traffic over scheduled backup traffic:

class-map match-all BACKUP-TRAFFIC
 match access-group name BACKUP-ACL

policy-map WAN-QOS
 class BACKUP-TRAFFIC
  bandwidth percent 20
  set dscp af11
 class class-default
  bandwidth percent 80

This ensures that when a large backup job saturates the network transferring data to a tape library, it doesn’t starve critical production traffic like VoIP or customer-facing applications.


Python Example: Automating Tape Backup Verification

Verifying tape backups is critical — you don’t want to discover a tape is unreadable only when you desperately need to restore from it. Here’s a script that automates writing a checksum manifest alongside a tape backup:

import subprocess
import hashlib
import os
import datetime

SOURCE_DIRS = ["/var/www", "/etc"]
TAPE_DEVICE = "/dev/nst0"
REWIND_DEVICE = "/dev/st0"
LOG_FILE = "/var/log/tape-backup.log"

def calculate_checksums(directories):
    manifest = {}
    for directory in directories:
        for root, _, files in os.walk(directory):
            for name in files:
                path = os.path.join(root, name)
                try:
                    h = hashlib.sha256()
                    with open(path, 'rb') as f:
                        while chunk := f.read(8192):
                            h.update(chunk)
                    manifest[path] = h.hexdigest()
                except (PermissionError, FileNotFoundError):
                    continue
    return manifest

def write_to_tape(directories, device):
    cmd = ["tar", "-cvf", device] + directories
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.returncode == 0

def log(message):
    with open(LOG_FILE, "a") as f:
        f.write(f"[{datetime.datetime.now()}] {message}\n")

def run_tape_backup():
    subprocess.run(["mt", "-f", REWIND_DEVICE, "rewind"])

    log("Calculating pre-backup checksums...")
    manifest = calculate_checksums(SOURCE_DIRS)
    log(f"Checksummed {len(manifest)} files")

    log("Writing archive to tape...")
    success = write_to_tape(SOURCE_DIRS, TAPE_DEVICE)

    if success:
        log("Tape backup completed successfully")
    else:
        log("TAPE BACKUP FAILED")

    subprocess.run(["mt", "-f", REWIND_DEVICE, "rewind"])

if __name__ == "__main__":
    run_tape_backup()

The checksum manifest can later be compared against a restored copy to confirm data integrity — an essential step for any archival system meant to be trusted years down the line.


Best Practices

  • Always use the non-rewinding device (/dev/nst0) when writing multiple archives to a single tape.
  • Label every tape physically and digitally — with date, contents summary, and retention/expiry date.
  • Store tapes properly — cool, dry, magnetically shielded environments extend tape lifespan significantly.
  • Rotate tapes off-site for disaster recovery, following the 3-2-1 backup principle.
  • Periodically test-read old tapes — media degrades, and drives eventually stop supporting very old formats.
  • Use hardware compression on the drive rather than double-compressing with software tools.
  • Keep a tape catalog/index (via LTFS, or dedicated backup software) so you don’t have to blindly search through tapes to find a specific file.
  • Plan for drive obsolescence — LTO drives typically read back 1–2 generations and write 1 generation back; migrate old tapes to new formats periodically.

Troubleshooting

SymptomLikely CauseFix
mt: /dev/st0: No such deviceTape drive not detected by the kernelCheck dmesg, verify SCSI/SAS cabling, confirm drive is powered on
Tape backup seems to overwrite previous dataUsed rewinding device (/dev/st0) instead of non-rewinding (/dev/nst0)Always use /dev/nst0 for multi-archive tapes
tar: Cannot write: No space left on device mid-backupTape physically fullUse a new/second tape cartridge; consider splitting large backups
Can’t find a specific archive on tapeNo index maintainedUse LTFS for browsable tapes, or maintain a written/digital catalog
Old tape unreadable in new driveDrive doesn’t support that many generations backCheck LTO generation compatibility chart; migrate data to newer media periodically
Backup is extremely slowSoftware compression combined with hardware compression, or slow interfaceDisable software compression; verify SAS/Fibre Channel link speed

Useful Diagnostic Commands

# Check detected tape devices
lsscsi | grep tape

# Check current tape drive status
mt -f /dev/nst0 status

# Test read without extracting
tar -tvf /dev/nst0

# Check kernel messages for tape drive errors
dmesg | grep -i tape

Summary

Tape storage may not be flashy, but it remains an irreplaceable part of a mature backup and archival strategy — offering unmatched cost efficiency, long-term durability, and true air-gapped security that no online backup can fully replicate. By understanding Linux tape device semantics (/dev/st0 vs /dev/nst0), mastering mt and tar fundamentals, and optionally layering on LTFS for usability, you can build a tape backup system that will reliably protect your organization’s most critical long-term data for decades.


Further Reading

Total
0
Shares

Leave a Reply

Previous Post
how to backup and restoring a multi volume archive in Linux

How to Back Up and Restore a Multi-Volume Archive in Linux

Next Post
how to perform incremental backups in linux

How to Perform Incremental Backups in Linux

Related Posts