Secure file transfers by switching from FTP to SCP
Q I have a simple shell script that is scheduled to download files from a remote server by FTP. In the shell script I have hard-coded USERNAME and PASSWORD to string variables to access the remote server. How do I prevent the USERNAME and PASSWORD being seen by others when they just open up the shell script file?
A The safest way to do this requires SSH access to the server. If this is available, you can use the scp command to send the files. The syntax for this is similar to cp, but it works over an encrypted SSH link. For example, you would download a file with
scp -p user@server:/path/to/my/file
As it stands, this will still ask for a password, but SSH has a means of authenticating users by means of keyfiles. If you do not already have a keyfile pair, use ssh-keygen to generate them. Full details are in the man page, but ssh-keygen -t dsa will create a pair with the default settings. This generates two files, a private key named id_dsa, to go in ~/.ssh, and a public key named id_dsa.pub. The names will be different if you choose to create RSA instead of DSA keys. Copy the public key to a file named authorised_keys and put this in ~/.ssh on the server. Now SSH will use the keys to authenticate and not require a separate password.
If SSH is not an option, you will have to use an FTP client to transfer the files. Some of these have the option to store passwords in a configuration file, which you should chmod to 600 so that only you and the root user can read it. This is safer than putting the password in a script to be used when you run the programs, because then the password can be read with ps while the program is running. For example, Ncftpget and Ncftpput are part of the Ncftp package and accept a login definition file instead of a URL. The file format issimple:
Then you can download the files with a single line in your script
ncftpget -f login.def dest/dir path/to/file1 path/to/file2 ...
where login.def is the file containing the login information. Ncftp, the interactive FTP client in this package, is able to store encrypted passwords in its bookmarks file, but this file is not used by the non-interactive Get and Put programs.0 FTP is inherently insecure. Even if your password is not stored anywhere, it is still sent in plain text when logging in. If security is important, you should really look for an alternative means of transferring the files.
Follow us on Identi.ca or Twitter