Using SFTP with Bash

Learn how to use SFTP in a bash script.

You can use the sftp command-line utility directly in a Bash script to perform SFTP operations. Here's a basic guide on how to use SFTP with Bash:

  1. Connecting to an SFTP Server: You can use the sftp command to establish a connection to an SFTP server. Below is an example of how to connect to an SFTP server:

    #!/bin/bash
    
    HOST="sftp.example.com"
    USERNAME="your_username"
    PASSWORD="your_password"
    PORT=22
    
    sftppass -p "$PASSWORD" sftp -oPort=$PORT $USERNAME@$HOST

    Replace "sftp.example.com" with the hostname or IP address of your SFTP server, "your_username" with your username, and "your_password" with your password. You can also adjust the port number if your SFTP server uses a different port.

  2. Performing SFTP Operations: Once connected, you can execute SFTP commands interactively or within the script to perform various operations such as uploading files, downloading files, listing directory contents, creating directories, etc. For example:

    • Uploading a file:

      put /path/to/local/file.txt /path/to/remote/file.txt
    • Downloading a file:

      get /path/to/remote/file.txt /path/to/local/file.txt
    • Listing directory contents:

      ls /path/to/remote/directory
    • Creating a directory:

      mkdir /path/to/remote/new_directory
  3. Exiting SFTP: Once you've finished with your SFTP operations, you can exit the SFTP session by typing exit or by sending an EOF (End-of-File) signal (usually by pressing Ctrl+D).

  4. Using Password in Bash Script: Storing passwords directly in Bash scripts is not recommended for security reasons. However, if you need to automate SFTP operations in a script, you can use tools like sshpass to provide the password securely. Make sure to install sshpass first (e.g., sudo apt-get install sshpass on Debian-based systems).

    Here's an example of how to use sshpass in a Bash script:

    #!/bin/bash
    
    HOST="sftp.example.com"
    USERNAME="your_username"
    PASSWORD="your_password"
    PORT=22
    
    sshpass -p "$PASSWORD" sftp -oPort=$PORT $USERNAME@$HOST <<EOF
    # SFTP commands go here
    EOF

    Replace "your_password" with your actual password. This approach securely provides the password to the sftp command without exposing it in the script itself.

By following these steps, you can use Bash scripts to automate SFTP operations securely. Ensure that you handle errors and exceptions appropriately in your scripts.

Last updated