SFTP allows you to securely transfer files in Linux. But sometimes you may need to automatically transfer files using SFTP. In such cases, the password prompt may pose an obstacle. In this article, we will look at how to create an SFTP script to transfer files in Linux, with password. You will need to use a third party library like keychain, sshpass or expect that automatically supplies your SFTP password, to simplify your life. For our article, we will be using SSHpass. We will also look at how to setup promptless password authentication without using SSHpass, using ssh-copy.
What is SSHpass
SSHPass is a simple command line tool that allows you to provide passwords to command prompt and scripts so that you can automate tasks that require authentication, without interruption. It facilitates non-interactive password authentication.
Sftp script to transfer files in Linux with password
Here are the steps to transfer files in Linux with password
1. Set SSH password
Open terminal and run the following command to set your SSH password. Replace your-password-here with your SSH password.
2. Transfer file in Linux
Run the following command to transfer files in Linux. Replace user with your SFTP username, remote-host with your SFTP host address, /data with the remote folder location, and your-file.log with your filename that you want to transfer.
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << ! cd /data put your-file.log bye !
You can add the above two commands to your shell script file to get your SFTP script to transfer files using password.
You may alternatively use ssh-copy function to do the same thing. In this approach, you will need to create a public key for your client and add this public key on your remote server. Once you do that, the remote server will always use your public key and stop prompting you for password.
Open terminal and run the following command to create public key for your client.
You will be prompted 3 questions, just press enter key for each prompt. This will generate your public key.
Run the following command to copy your public key over to your remove SFTP server. Replace remote-host with your SFTP server’s host IP address.
ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host
You will be prompted to access/reject the remote host’s key. Press y yo accept it. Next, you will be asked to enter your remote server’s password. Enter it to successfully add your public key to the remote server’s list of accepted public keys. You will be able to find it in .ssh/authorized_key file.
Henceforth, you won’t be prompted for password while using scp, ssh, or sftp.
In this article, we have looked at two different ways to transfer files using SFTP.