Pass on Passwords with scp

Learn how to propagate files quickly and do backups easily when you set up scp to work without needing passwords.

In this article, I show you how to use the scp (secure copy) command without needing to use passwords. I then show you how to use this command in two scripts. One script lets you copy a file to multiple Linux boxes on your network, and the other allows you to back up all of your Linux boxes easily.

If you're a Linux sysadmin, you frequently need to copy files from one Linux box to another. Or, you may need to distribute a file to multiple boxes. You could use FTP, but using scp has many advantages. For instance, scp is much more secure than FTP. scp travels across the LAN/WAN encrypted, while FTP uses clear text, even for passwords.

But what I like best about scp is it's easily scriptable. Suppose you need to distribute a file to 100 Linux boxes. I'd rather write a script to do this than type 100 sets of copy commands. If you use FTP in your script, things can get messy, because each Linux box you log into is going to ask for a password. But if you use scp in your script, you can set things up so the remote Linux boxes don't ask for a password. Believe it or not, this actually is much more secure than using FTP.

Here's an example demonstrating the most basic syntax for scp. To copy a file named abc.tgz from your local PC to the /tmp dir of a remote PC called bozo, use:

scp abc.tgz root@bozo:/tmp

You now are asked for bozo's root password, so we're not quite there yet. The system still is asking for a password, so it's not easily scriptable. To fix that, follow this one-time procedure, after which you can make endless password-less scp copies:

  1. Decide which user on the local machine will be using scp later on. Of course, root gives you the most power, and that's how I personally have done it. I'm not going to give you a lecture here on the dangers of root, so if you don't understand them, choose a different user. Whatever you choose, log in as that user now and stay there for the rest of the procedure. Log in as this same user when you use scp later on.

  2. Generate a public/private key pair on the local machine. Say what? If you're not familiar with public key cryptography, here's the 15-second explanation. In public key cryptography, you generate a pair of mathematically related keys, one public and one private. You then give your public key to anyone and everyone in the world, but you never ever give out your private key. The magic is in the mathematical makeup of the keys; anyone with your public key can use it to encrypt a message, but only you can decrypt it with your private key. Anyway, the syntax to create the key pair is:

    ssh-keygen -t rsa
  3. In response, you should see:

    Generating public/private rsa key pair
    Enter file in which to save the key ... 

    Press Enter to accept this.

  4. In response, you should see:

    Enter passphrase (empty for no passphrase):

    You don't need a passphrase, so press Enter twice.

  5. In response, you should see:

    Your identification has been saved in ... 
    Your public key has been saved in ... 

    Note the name and location of the public key just generated. It always ends in .pub.

  6. Copy the public key just generated to all of your remote Linux boxes. You can use scp or FTP or whatever to make the copy. Assuming you're using root--again, see my warning in step 1--the key must be contained in the file /root/.ssh/authorized_keys. Or, if you are logging in as a user, for example, clyde, it would be in /home/clyde/authorized_keys. Notice that the authorized_keys file can contain keys from other PCs. So, if the file already exists and contains text, you need to append the contents of your public key file to what already is there.

Now, with a little luck, you should be able to scp a file to the remote box without needing to use a password. So let's test it by trying our first example again. Copy a file named xyz.tgz from your local PC to the /tmp dir of a remote PC called bozo:

scp xyz.tgz root@bozo:/tmp

Wow--it copied with no password!

A word about security before we go on. This local PC just became pretty powerful, as it now has access to all the remote PCs with only the one local password. So that one password better be strong and well guarded.

Now for the fun part. Let's write a short script to copy a file called houdini from the local PC to the /tmp dir of ten remote PCs, located in ten different cities, in only five minutes of work. Of course, it would work the same with 100 or 1000 of PCs. Suppose the 10 PCs are called brooklyn, oshkosh, paris, bejing, winslow, rio, gnome, miami, minsk and tokyo. Here's the script:

for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk
scp houdini root@$CITY:/tmp
echo $CITY " is copied"

It works like magic. With the echo line in this script, you should be able to watch as each city's copy is completed one after the next.

By the way, if you're new to shell scripting, here is a pretty good tutorial.

As you may know, scp is only one part of the much broader SSH program. Here's the cool part: when you followed my six-step procedure above, you also gained the ability to sit at your local PC and execute any command you like on any of the remote PCs--without a password, of course. Here's a simple example to view the date and time on the remote PC brooklyn:

ssh brooklyn "date"

Let's now put these two concepts together for one final and seriously cool script. It's a down-and-dirty way to back up all of your remote Linux boxes. The example backs up the /home dir on each box. It's primitive compared to the abilities of commercial backup software, but you can't beat the price. Consider the fact that most commercial backup software charges license fees for each machine you back up. If you use such a package, instead of paying license fees to back up 100 PCs remotely, you could use the script to back up the 100 PCs to one local PC. Then, back up the local PC to your commercial package and save the license fees for 99 PCs. Anyway, the script below demonstrates the concepts, so you can write your own script to suit your own situation. Simply put this script in a cron job on your local PC; no script is required on the remote PCs. Please read the comments carefully, as they explain everything you need to know:


# Variables are upper case for clarity

# before using the script you need to create a dir called '/tmp/backups'
on each
# remote box & a dir called '/usr/backups' on the local box

# on this local PC
# Set the variable "DATE" & format the date cmd output to look pretty
DATE=$(date +%b%d)

# this 'for loop' has 3 separate functions

for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk

# remove tarball on remote box from the previous time the script ran #
to avoid filling up your HD
# then echo it for troubleshooting
ssh -1 $CITY "rm -f /tmp/backups/*.tgz"
echo $CITY " old tarball removed"

# create a tarball of the /home dir on each remote box & put it in
# name the tarball uniquely with the date & city name
ssh $CITY "tar -zcvpf /tmp/backups/$CITY.$DATE.tgz /home/"
echo $CITY " is tarred"

# copy the tarball just create from the remote box to the /usr/backups
dir on
# the local box
scp root@$CITY:/tmp/backups/$CITY.$DATE.tgz /usr/backups
echo $CITY " is copied"


# the rest of the script is for error checking only, so it's optional:

# on this local PC
# create error file w todays date.
# If any box doesn't get backed, it gets written to this file
touch /u01/backup/scp_error_$DATE

for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk


# Check if tarball was copied to local box. If not write to error file
# note the use of '||' which says do what's after it if what's before it
is not # true
ls /u01/backup/$CITY.$DATE.tgz || echo " $CITY did not copy" >>

# Check if tarball can be opened w/o errors. If errors write to error file.
tar ztvf /u01/backup/$CITY.$DATE.tgz || echo "tarball of $CITY is No
Good" >> scp_error_$DATE


That's about it. In this article, I've tried to give examples that demonstrate the concepts and are not necessarily ready to be used "as is". Some of the syntax may not work for all distributions, but in the interest of brevity, I could not include all the possibilities. For example, if you are using Red Hat 6.2 or before, the syntax requires some changes. So be creative, and hopefully you can use some of this work in your own environment.

Copyright (c) 2004, Dave Sirof. Originally published in Linux Gazette issue 98. Copyright (c) 2004, Specialized Systems Consultants, Inc.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

ssh to run thing multiple

Anonymous's picture

ssh to run thing multiple machines.

error in your post

idigit's picture

Hi, I think the reason for all these comments that report failures is a possible typo in your instructions:
step 6 reads: ... Or, if you are logging in as a user, for example, clyde, it would be in /home/clyde/authorized_keys. ...

the path is incorrect. It should be:


otherwise, great post.

Excelente tutorial Mr Dave

Anonymous's picture

Le agradezco mucho su tutorial, ya que he podido realizar el respaldo automático de una base de datos de PostgreSQL
de mas de 10Gb, ya no tengo que esperar a que termine el respaldo, ahora me ha dado tiempo de salir con mi chica. Los respaldos se hacen solos, veamos como lo hice.

En Server "Source" con IP
1.- Conectado localmente con el usuario myuser crear el par de claves privada/publica:
ssh-keygen -t rsa
2.- Construír un cron para respaldo asignado al usuario myuser usando como identidad la clave privada anterior:
15 22 * * 0-6 pg_dump database > respaldo.bak
20 22 * * 0-6 scp -i /home/muyser/.ssh/id_rsa respaldo.bak myuser@
crontab -u myuser respaldo.crn

En Server "Destiny" con IP

1.- Con el usuario myuser crear la carpeta /home/myuser/.ssh
2.- Copiar la clave pública *.pub generada en "Source" a "Destiny" en la carpeta /home/myuser/.ssh/ bajo el nombre de "authorized_keys"
3.- Configuré los derechos necesarios para poder escribir en /home/muyser/data.

Y listo esperé el momento de ejecución de la tarea programada en "Source" y creanme funciona de maravilla. Espero les ayude mi experiencia. Saludos
LFM Octavio Nieves Bolaños

Good tutorial

Anonymous's picture

This explanation was very nice.

i need a same explanation procedure for using ssh

If pos send it to

ssh-keygen not working properly

Mohanad azzam's picture

dear Sir ,

still i have problem to do scp between two servers .
I did the steps that you listed but withour any response .
could you please explain more about generating publick key authentication .
and what is the requirment that shuold be done between the authorized_keys and known_hosts in the client and the server .

am trying to establish the connectivity since one week and I couldnt .
you help please if there is troubleshooting on this procedures .

More linux tutes should be written like this!

Anonymous's picture

Just wanted to say this is probably the best Linux tutorial I have ever read. Wish there were more like this around.

rsa & scp commandline parameters

Andreas Jacobs's picture


I found that ommiting the -i parameter always asked for the password

i.e.:scp file1 root@box:/directory

asked for password

Instead when using :scp -i identity file1 root@box:/directory

where identity is your 'private key'.

just did the job


still not working

Martin Rehanek's picture

I did this, but password is still required.

yeap, -i is missing

Rodislav Moldovan's picture

Hi, thanks for -i parameter!! its working now!! i`m so happy!!!

For RHEL5, you don't usually

Anjan Saikia's picture

For RHEL5, you don't usually see authorized_keys under /home/user/.ssh/
So, create a (using vi) authorized_keys file and paste the key of your local machine. This works.

Thank you very much, This

Anonymous's picture

Thank you very much, This tip is very useful.
RHEL5 Doesn't have the "authorized_keys" file under /home/user/.ssh/ ,
you need to create one.

And also make sure that the

Peter's picture

And also make sure that the permissions of the .ssh dir and the authorized_keys are set to something like chmod 400 otherwise the host won't connect and will ask for a password. Check the /var/log/secure file on the host if you've tried everything else!

chmod 700 ~/.ssh worked for

Anonymous's picture

chmod 700 ~/.ssh worked for me, chmod 400 failed.

Pass on Passwords with scp - Fantastic Article!

Anonymous's picture

This is one of the best, most clearly stated how-to's that I've read in a long time. Thanks for posting.

Keys for www-data user

krtapas's picture

Hi, I need to copy some files into three more servers on my LAN through a website. I know that the owner of Apache service is www-data user, I need to create keys for it. The trouble is that www-data is a pseudo user, that means, it doesn´t have access to the shell. I would appreciate if somebody could help me. Thanks for your time and your answers.

use c wrapper to setuid

Anonymous's picture

I had the same problem, and I found a workaround. Use C wrapper program to set the uid to different uid.
For details, see
Or google for 'setuid c wrapper' It is a very simple program.

Thanks - Let's hope it works

Anonymous's picture

Thanks - Let's hope it works on Solaris...

want to do scp on differnt port no

prithviraj's picture

I done with ur code for doing scp with out password it works very fine.
Now my requirement is that i have to use different port no.
In that case it says that
Secure connection to xxxxxxxxx on port 1234 refused.
lost connection
can you please tell me solution for that

scp file without password

Tom Stone's picture

Followed your advice. Still having a problem using scp file without password.

BoxA -- an IBM AIX box
BoxB -- a Linux box

I ran ssh-keygen -t rsa
on BoxA under UserA account

I copied the file from BoxA to BoxB (i.e. copied the file from /home/UserA/.ssh/ on BoxA to the /home/UserB/.ssh/authorized_keys file on BoxB).

I then tried the scp command on BoxA under the UserA account ...

scp file.txt UserB@BoxB:/tmp

but I still get prompted for the UserB password.

Any suggestions?


Fix for different local and remote users

Andrew's picture

If you're running this as different users on the local and remote machines, you need to suffix the remote user on the ssh commands.

So "ssh -1 $CITY..." becomes "ssh -1 root@$CITY" for example.

Solution for failure

dbp's picture

Same for me in required password. After few tries, it can ensure working if ALL mentioned files exist in BOTH side:


Still having prompt

Anonymous's picture

I still get prompt for password.

Is step 6 correct:
Copy the public key just generated to all of your remote Linux boxes. You can use scp or FTP or whatever to make the copy. Assuming you're using root--again, see my warning in step 1--the key must be contained in the file /root/.ssh/authorized_keys. Or, if you are logging in as a user, for example, clyde, it would be in /home/clyde/authorized_keys. Notice that the authorized_keys file can contain keys from other PCs. So, if the file already exists and contains text, you need to append the contents of your public key file to what already is there.
Should authorized_keys be in /home/clyde/ or /home/clyde/.ssh/ directory?

authorized_keys should be in

Anonymous's picture

authorized_keys should be in /home/clyde/.ssh/

Couple of minor issues

Keith Neargarder's picture

Couple of issues I had - one definitely due to my particular environment and the other I believe due to a small omission in the example (might again be particular to my environment though).

1. Ran into problems because there was another scp executable on my system in the folder /opt/lib/cobol/bin/scp which superseded the desired /usr/bin/scp in my PATH variable. The other scp is for Microfocus COBOL – don’t know much else about it. I used multiple solutions for this issue in various places - rearrange the PATH; put a softlink in a directory that comes before the COBOL one; reference the desired scp by absolute path (in scripts).

2. Had problems getting the scp to work without prompting for password. I followed the directions for creating the public key and copying it to the remote host authorized_keys file in the desired users home directory because that is how I read the "clyde" example saying "it would be in /home/clyde/authorized_keys". This did not work for me until I moved it to the subfolder $HOME/.ssh as I derived from the root example. Not sure if this is another issue particular to my environment but I am guessing not. Makes sense to me that the authorized_keys file would have to be in the $HOME/.ssh folder.

This page has been of great

Anonymous's picture

This page has been of great help for me . I always wanted to automatize scp myself but I always failed to get it right.

public keys and scp

Anonymous's picture

I set up two servers with public keys. One server is Linux 2.4.21-40 and the other is HPUX 11i. ssh works fine, it doesn't ask for a password, however, when I run scp it doesn't ask for a password, it just return the prompt but it doesn't copy any files. May I have a clue why it cannot copy the files from the remote server?

syntax for SCP to append the Authorized Keys

Anonymous's picture


I want to know the Syntax for the SCP command to copy the "" to the Remote Machines "authorized_keys".

Note : Syntax to Append the authorized_keys File, because my Authorized Keys file contains other machines public Keys.



Chandran's picture

Thanks for this document, i tried its not working could you please give me direction to implement this please.


i would like to know,how can

gurpreet's picture

i would like to know,how can we copy public key to multiple remote servers simultaneously, otherwise we have to copy that individually.

How are the keys revoked? or

Anonymous's picture

How are the keys revoked? or modified (to add password, change password, etc)? Do you simply delete the files created and the Known_host file?

permissions can be important

thujone's picture

If you set your permissions too loose for the .ssh directory, it might not work! Try chmod 0700


David's picture

I just wanted to say that this is an article that was VERY easy to follow. I got the expected results first time through, and the little tip that I can use it to 'control' another machine.


Set up SSH on multiple servers and workstations

Anonynous's picture

On step 6, you said the public key has to be copied to all remote Linux boxes by using scp or FTP. This way is possible for copying to some Linux boxes, but impossible for copying to 1000 Linux boxes. Is there any way to automate the copying of public key to multiple computers? Thanks!

Re: Set up SSH on multiple servers and workstations

rohit kumar's picture

You can write ftp script, which will help you to copy public key to 1000s of linux boxes.

I have 4 users on my pc and

Dicha's picture

I have 4 users on my pc and i want to sent files by scp among them without asking me password .Although i have created id_dsa & under dir .ssh/ and i have appended the public keys ,i have only some connections which take place without password .For example:

user4 with noone

Connection without password!

Di.Chatz.'s picture

i have 3 users on my PC and i have already created private/public keys.
i need connection with scp among them without password but the problem is that all connections don't take place without password.
Only these directions can be realized without password:
user1 -> user2
user1 -> user3

user2 -> user3

Why in the security section ?

Anonymous's picture

Really, using password-less security keys shouldn't figure in the Security section of any magazine ;-)

1) Use ssh-copy-id to propagate keys
2) Use ssh-agent and ssh-add with a password only once to get rid of entering passwords everytine you do a scp.

*) ssh-agent could be already launched in your distro. This is the case with SuSE 9.3. In this case, just use ssh-add. Do not launch ssh-agent again.


Using SCP in a C program

Anonymous's picture

I am trying to write a C program that uses SCP to obtain a file from another machine to the current machine. Does anyone have suggestions on how to code this? This is what I have:

char CommandLine[4096];
sprintf( CommandLine, "scp user@OtherMachine:/../../file.gz ." );
system( CommandLine );

But of course, SCP is gonna ask for a password, so how do I have the C program give the password?
user@OtherMachine's password:

automate ssh-copy-id further

ryant's picture

After accidentally toasting my ssh keys I found I had to add the new public key to *all* the servers I have to log onto. The bash script made that process easier (when I remembered to type 'goto' and not 'ssh':


# $Id: goto,v 1.1 2005/10/07 09:35:54 ryant Exp $

# just something to make adding ssh keys to
# stacks of boxen that much less painful
# use it, don't use.

if [ $# -eq 0 ]; then
echo "Usage: $0 -h -c [-n (no login)]"
exit 21

while getopts "h:c:n" opt; do
case ${opt} in
echo 'Usage: $0 -h -c '
exit 21

# if I forget to use -h host
if [ -z "${host}" ]; then
shift $(($OPTIND - 1))

ret=`ssh -o BatchMode=yes ${host} uptime 2>&1`

if `echo "${ret}" | grep -q average`; then
ssh-copy-id -i ${MYPUBKEY} ${host}

if [ ${login} = "yes" ]; then
ssh ${host} ${cmd}

exit 0


The "-o BatchMode=yes" is very helpful in that you get an immediate failure if you cannot logon with your keys -- it does not default back to the password prompt and timeout (eventually). Great for scripts.

Just my $0.02.

Beware passwordless ssh keys

Anonymous's picture

I generally tend to avoid creating ssh keys with no passphrases. The passphrase protects the private key, so creating a key without a passphrase means that anyone who manages to acquire the private key would be able to log in to remote servers with the credentials of the key owner. Consider using Keyring instead. Keyring allows you to decrypt the private key and stores it in memory. As long as /proc/kcore is set to mode 0400, it is safer than a passphrase-less key.

Wanted to mention Unison

Sukant Hajra's picture

I know the topic of this article is passwordless ssh-ing, but it seems to have stepped into a discussion of synchronization/backups. I wanted to point out that Unison is a really nice synchronization/backup tool.

It's not great for synchronizing *among* computers, but it works very, very well for synchronization *between* (two) computers. Unison's interface offers the kind of synchronization you get with a Palm/Pocket-PC device -- very intuitive.

Unison also works fine over ssh, so if you figure out ssh-agent, ssh-keygen, and so forth, you can have some pretty seamless synchronization. Also, Unison keeps a history of the archives, so it only sends "difference" information, and synchronization is extremely fast and efficient.

Okay, so that's my pitch for Unison. In my opinion it's way more fanciful than any script you're likely to hand-wrtie, and does things that rsync can't.

Okay, here's some links:

use Rsync thru SSH

fak3r's picture

I use rsync over ssh to backup all my home systems; I have a group of scripts under ~/bin/backup that send stuff to /mnt/backup on my server under each systems' name. After passing keys around as desc, create a simple script like this, cron it and sleep well ;)

    if ping -c 5 diego
    /usr/local/bin/rsync -ave ssh --delete diego:/home/fak3r/documents/ /mnt/backup/diego/documents/
    echo "Diego unreachable"
    exit 0


Suprised this is never mentioned in these tutorials.

Ian's picture

1) Non-interactive account.
2) Use of ssh-agent
3) Restricted use keys.

I have found #1 and #3 very easy to implement. It would seem that this with a few other hacks would substantially increase security.


Anonymous's picture

Has anyone gotten this to work correctly under Cygwin? I've tried it several times, step-by-step and not had any success. I have also used the -v option to see what is going on, it appears everything should work, but does not...

Yes, Windows is somewhat diff

Meeuw's picture

Yes, Windows is somewhat different with file permissions, and openssh strictly checks the file permissions.
You should start the ssh daemon in debug mode, kill all running sshd processes and start 'sshd -d', now login with a identification key and see what happens, you proberly need to change the permissions on your authorized_keys (to be non writeable for any other user (644 rw-r--r--)

Clyde's authorized_keys file

Anonymous's picture

Clyde's authorized_keys file would actually be in




Small correction in step #6

Jeff Smith's picture

In step 6, the remote file path should be "/home/clyde/.ssh/authorized_keys", not "/home/clyde/authorized_keys".

I also agree with a previous poster about using 'rsync' as a backup tool. It is very configurable as to what it backs up, and it can use SSH as a transport mechanism.

Good stuff...

Anonymous's picture

It's worth noting that if you want to do backups you might want to take it a step further by looking into the use of rsync.

rsync can run over SSH as set up in this article, without passwords, and can be an effective way to back up large directories (especially if the changes are relatively small). Each backup operation is basically one rsync command, so you could easily drop them into the above backup script in place of the scp commands.

Another 1-2 hours looking at the following page and playing with rsync will be time well invested (although the above article is still useful):

Good stuff...

Anonymous's picture

It's worth noting that if you want to do backups you might want to take it a step further by looking into the use of rsync.

rsync can run over SSH as set up in this article, without passwords, and can be an effective way to back up large directories (especially if the changes are relatively small). Each backup operation is basically one rsync command, so you could easily drop them into the above backup script in place of the scp commands.

Another 1-2 hours looking at the following page and playing with rsync will be time well invested (although the above article is still useful):

A reasonable article. But th

Anonymous's picture

A reasonable article. But the process of copying the public key to another machine can be simplified somewhat.

Try this technique:

ssh-keygen -t rsa
ssh root@bozo "cat >> .ssh/authorized_keys" <

Of course, the root@bozo would need to change, as would (possibly) the filename containing the public key, in my example.

One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix