in

15 Examples of SFTP command in Linux

Hi there! As a fellow Linux enthusiast, I know you‘re looking for an in-depth guide on using SFTP commands to securely transfer files between systems. Well, you‘ve come to the right place!

In this post, we‘ll explore 15 practical examples of the powerful SFTP command with detailed explanations and usage tips. I‘ll share my experiences as a Linux system admin to provide extra insights on these file transfer capabilities.

Whether you‘re a rookie or seasoned pro, this guide aims to level up your SFTP skills to safely move data between servers like a pro. Let‘s get started!

1. Connecting to an SFTP Server

The first step is initiating an SFTP connection with the remote host. Here is the basic syntax:

sftp username@remotehost

For example, to connect as ‘john‘ to sftp.example.com, you would run:

sftp [email protected]

After executing this command, you may be prompted to verify the host key fingerprint to ensure you are connecting to the correct server. Type ‘yes‘ to continue establishing the connection.

Next, you‘ll be asked for a password to authenticate as the user ‘john‘:

Connecting to sftp.example.com...
The authenticity of host ‘sftp.example.com (192.0.2.1)‘ can‘t be established.
ECDSA key fingerprint is SHA256:1234EFgh5678IJkl90ABcd1234EFgh5678IJkl90ABcd.
Are you sure you want to continue connecting (yes/no)? yes 
Warning: Permanently added ‘sftp.example.com‘ (ECDSA) to the list of known hosts.
[email protected]‘s password:

Once successfully authenticated, you will enter an interactive SFTP session indicated by the sftp> prompt. All commands for file transfers and remote file system management will be run in this session.

sftp>

Now you‘re ready to start transferring files over the secure SFTP connection!

Pro Tip: For password-less logins, you can set up public-key authentication using SSH keys between the client and server. This is more secure than using password logins which are prone to brute force attacks.

2. Uploading Files to the Remote Server

Let‘s look at how to transfer files from your local machine to the remote system using some examples.

To upload a single file, use the put command followed by the local file path and the remote destination path:

sftp> put myfile.txt /remote/directory/path

For example:

sftp> put report.pdf /shared/reports
Uploading report.pdf to /shared/reports/report.pdf

This will transfer the local file ‘report.pdf‘ to the ‘/shared/reports‘ directory on the remote host.

You can also use relative paths from your local and remote working directories instead of full paths.

To upload multiple files in one go, use the mput command followed by a wildcard pattern like *.txt:

sftp> mput *.txt

This will upload all .txt files from the current local directory to the remote working path.

For example:

sftp> mput *.pdf
Uploading report.pdf to /shared/reports/report.pdf
Uploading guide.pdf to /shared/reports/guide.pdf

This securely uploaded all PDFs to the ‘/shared/reports‘ remote directory in a single transfer.

Pro Tip: When uploading files, use absolute paths for clarity. Also ensure proper permissions are set on the target directories. Restrict folder access to prevent unauthorized access to uploaded data.

3. Downloading Files from the Remote Server

Now let‘s look at how to transfer files in the other direction – from the remote server to your local machine.

To download a single file, use the get command followed by the remote file path and optionally a custom local file name:

sftp> get /remote/directory/filename.ext [localfilename.ext]

For example:

sftp> get /shared/reports/report.pdf
Fetching /shared/reports/report.pdf to report.pdf 

This will download ‘report.pdf‘ from the remote host to your local working directory.

To keep the original filename, you can omit specifying a local file path. But it‘s often safer to explicitly define the local name to avoid overwriting existing files.

To download multiple files, use the mget command with a wildcard as the source:

sftp> mget /remote/path/*.txt

For example:

sftp> mget /shared/reports/*.pdf
Fetching /shared/reports/report.pdf to report.pdf
Fetching /shared/reports/guide.pdf to guide.pdf

This will download all PDFs from the ‘/shared/reports‘ directory on the remote server.

Pro Tip: Take care when downloading into non-empty directories – accidentally overwriting existing files is no fun! Use absolute paths for the local destination or specify custom filenames.

4. Checking the Working Directory on Local and Remote

While transferring files, it‘s important to keep track of the current working directory on both your local machine and the remote server.

Use the pwd (print working directory) command to see the current remote path:

sftp> pwd
Remote working directory: /home/john

To check your local machine‘s working directory, use lpwd (local print working directory):

sftp> lpwd
Local working directory: /home/localuser 

Knowing your current directories helps avoid silly mistakes like uploading files to the wrong location!

Pro Tip: Get into the habit of running pwd and lpwd regularly to confirm your working paths, especially after navigating to new directories.

5. Changing the Working Directory

You can change the current working directory on the local and remote hosts using cd and lcd.

On the remote server, use cd just like in a regular shell:

sftp> cd /var/www/html
sftp> pwd
Remote working directory: /var/www/html

To switch the working directory on your local machine, use lcd:

sftp> lcd /home/localuser/downloads
sftp> lpwd  
Local working directory: /home/localuser/downloads

This allows you to easily navigate into different directories without disconnecting from the SFTP session.

Pro Tip: Avoid typing out long absolute paths multiple times by changing directories for more readable commands. But don‘t forget to verify the paths with pwd and lpwd!

6. Creating Directories on the Remote Server

SFTP also allows you to directly manage folders and directories on the remote server.

For example, to create a new directory called ‘backups‘ under ‘/var/www/html‘, run:

sftp> mkdir /var/www/html/backups

The new folder will be created on the remote host.

You can also create local directories using lmkdir:

sftp> lmkdir /home/localuser/sftp-downloads 

This can be useful for organizing your local file structure during an SFTP session.

Pro Tip: Ensure proper directory permissions are set on the remote server after creating new folders. Restrict access to prevent untrusted users from manipulating data.

7. Listing Directory Contents

To explore the filesystem of the remote server, you can list the contents of the current working directory using the ls command:

sftp> ls
file1.txt  file2.txt

This will display all files and directories within the remote path.

To see contents of your local working directory, use lls:

sftp> lls
localfile1.txt  localfile2.txt

You can pass flags like -l and -a to ls and lls for modifying the output. This allows easy inspection of available files.

Pro Tip: Get familiar with Linux ls flags for sorting and formatting directory listings. The -l option is great for detailed file attributes and permissions.

8. Deleting Files and Folders on the Remote Server

To manage data on the remote system through SFTP, you can directly delete files and folders.

For example, deleting a file is done with the rm command:

sftp> rm report-old.pdf

To remove a directory (must be empty) use rmdir:

sftp> rmdir legacy_backups

These file system changes apply only to the remote SFTP host – your local data remains untouched.

Pro Tip: Take extreme caution when deleting data over SFTP. Permanently losing important remote files is devastating! Double check paths and run ls before hitting enter.

9. Moving and Renaming Files on the Remote Server

To organize data on the remote system, SFTP allows moving and renaming files entirely through the CLI.

For example, to rename a file:

sftp> rename report.pdf annual-report.pdf

To move it into a different directory:

sftp> rename /shared/reports/annual-report.pdf /shared/annual_reports/annual-report.pdf

This moves and renames the file in one step without needing to transfer any data.

Pro Tip: Moving large files across filesystems can be slower than renaming locally and re-uploading. Test to find the fastest option for your environment.

10. Running Local Shell Commands

You can also run shell commands and scripts on your local machine while connected to the SFTP server.

The ! prefix executes a local command from the SFTP prompt.

For example, to list your local home directory:

sftp> !ls ~/
file1.txt Documents Pictures

Or do a local directory copy:

sftp> !cp -r /home/localuser/downloads /media/backupdrive

This saves you from constantly disconnecting and losing your place while performing related tasks.

Pro Tip: The ! command is a powerful tool, but use it judiciously. Avoid destructive actions that could impact production systems.

11. Transferring Files Between Remote Servers

SFTP supports transferring files directly between two remote servers without routing through your local machine.

Start by opening a second SFTP session to the target server in a separate terminal:

sftp newuser@newhost 

Next, on your original SFTP connection, download the file but specify the URL of the other server as the destination:

sftp> get /var/logs/app.log newuser@newhost:/shared/logs/app.log

This will directly transfer the ‘app.log‘ file from the first host to the new one without touching your local filesystem.

Pro Tip: Multi-hop transfers can speed up large file movements between remote sites. But ensure proper bandwidth is available on the network between hosts.

12. Resuming Failed Transfers

Sometimes transfers get interrupted due to network issues or timeouts. SFTP includes options to resume failed file transfers so you don‘t have to start from scratch.

For uploads, use reput instead of put to pick up where a transfer left off:

sftp> reput largefile.zip

Similarly, reget will resume a download instead of restarting it:

sftp> reget access.log

This saves a tremendous amount of time and frustration when working with large files or spotty connections.

Pro Tip: Always use reput and reget when you suspect a transfer was interrupted. But check that the partial file wasn‘t corrupted first.

13. Monitoring Transfer Progress

When working with large files, it‘s handy to see progress indicators and transfer speeds:

sftp> progress
Progress meter enabled
sftp> get LARGE_FILE

This will display the ongoing progress and speed as the data transfers. Useful for estimating remaining time on big transfers.

To disable the progress meter:

sftp> progress
Progress meter disabled

Pro Tip: Keep an eye on transfer speeds and note any bottlenecks. A 10 Gb network won‘t help if your storage media can only write data at 200 Mbps!

14. Automating File Transfers with Scripting

Manually running SFTP commands works for one-off transfers. But for frequent large transfers, automation is key for operational efficiency.

You can write SFTP commands into a script to run without any interactive input:

#!/bin/bash

sftp user@destination <<EOF
cd /uploads
put *.csv
bye
EOF

Save this as sftp_script.sh and run it whenever you need to batch upload new CSVs.

For more complex workflows, use a robust automation tool like Ansible which supports SFTP tasks.

Pro Tip: Scripted and automated transfers remove human error and ensure consistency. Use version control for code to track changes over time.

15. Enabling Encryption and Compression

To take your SFTP security up a notch, consider enabling SSH encryption like AES-256 and data compression to protect files in transit:

sftp -oCompression=yes -oCipher=aes256-ctr user@host 

The -o options pass directives to the underlying SSH connection. This encrypts and compresses data end-to-end.

Strong ciphers and SSH key authentication thwart eavesdroppers attempting to intercept transferred data.

Pro Tip: Default SFTP encryption is good but extra paranoia never hurts! Evaluate your threat model and enable additional SSH protections if needed.

Key Takeaways and Best Practices

Let‘s recap some of the key tips for securely transferring files like a pro using SFTP:

  • Use SSH keys instead of password authentication
  • Ensure remote directories have appropriate permissions
  • Enable encryption and compression for added security
  • Script and automate frequent transfers to prevent mistakes
  • Change to specific local and remote working directories instead of full paths
  • Resume failed uploads/downloads instead of starting over
  • Verify transfers worked as expected with ls on source and destination
  • Take care when overwriting or deleting data – SFTP does not have recycle bin recovery!

Following these best practices will lead to smooth, secure, and efficient data transfers.

The built-in sftp command provides a powerful way to move data between systems. Mastering SFTP will enable you to securely manage data across both local and remote environments.

Final Thoughts

Thanks for joining me on this deep dive into 15 practical examples for mastering SFTP file transfers in Linux!

I hope these detailed tips give you the confidence to use SFTP proficiently for critical data workflows. Let me know if you have any other SFTP usage questions!

Now go forth and move data like a pro!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.