How to specify FTP credentials in command line scripts

It’s easy to establish an FTP connection using the ftp command from the Linux Command Line. Sadly this command does not accept login credentials as parameters – which means that if we use it in a script, our script will pause and wait for us to type those credentials in manually. Not really suitable for automated backups.

Thanks to a clever mechanism called netrc we can create a file in the home directory of the user who runs the script and provide credentials there. Let me show you how this works.

First we create a file called .netrc. It’s a hidden file and it needs to reside in the home directory of the user who will connect via FTP. I’m going to use root for this:

vi ~/.netrc

# machine  login  password 
machine ftp.domain.com login yourusername password yourpassword

The first line is just a comment to you can remember how to add parameters here. The second line is an example of a host you want to connect to. Add as many other servers as you like, all following the same pattern.

Be aware that you need to connect to the server as it is specified in the .netrc file. In the above example, if you would connect to domain.com instead, you would be asked for credentials as netrc cannot find a match.

The .netrc file needs to be readable only by this one user, otherwise connections may fail. We do this by changing the file permissions to 600:

chmod 600 ~/.netrc

That should do it! Try to connect with

ftp ftp.domain.com

and the connection will be established without the prompt for credentials.

If netrc isn’t working for you, or you choose not to use it, note that you can also provide FTP credentials with a here script. I find that approach a bit clunky, but the following link has details on how to do that:





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.