Pass on Passwords with scp

October 6th, 2005 by Dave Sirof in

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:


#!/bin/sh
for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk
tokyo
do
scp houdini root@$CITY:/tmp
echo $CITY " is copied"
done

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:


#!/bin/sh

# 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
tokyo
do

# 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
/tmp/backups
# 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"

done


# 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
tokyo

do

# 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" >>
scp_error_$DATE


# 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

done

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.

good

On November 23rd, 2007 Anonymous (not verified) says:

hai
this page is too good.
the concept is very beautiful.
script is very easy to understand.

thanks&regards

Thanks - Let's hope it works

On November 12th, 2007 Anonymous (not verified) says:

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

want to do scp on differnt port no

On August 20th, 2007 prithviraj (not verified) says:

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

On June 14th, 2007 Tom Stone (not verified) says:

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 id_rsa.pub file from BoxA to BoxB (i.e. copied the file from /home/UserA/.ssh/id_rsa.pub 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?

Thanks.

Solution for failure

On May 26th, 2007 dbp (not verified) says:

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

/root/.ssh/authorized_keys
/root/.ssh/id_rsa
/root/.ssh/id_rsa.pub

Still having prompt

On March 27th, 2008 Anonymous (not verified) says:

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

On May 30th, 2008 Anonymous (not verified) says:

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

Couple of minor issues

On May 22nd, 2007 Keith Neargarder (not verified) says:

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

On April 14th, 2007 Anonymous (not verified) says:

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

On January 16th, 2007 Anonymous (not verified) says:

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

On January 10th, 2007 Anonymous (not verified) says:

Hi,

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

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

Thanks
Joel

SSH AUTO LOGIN

On October 27th, 2006 Chandran (not verified) says:

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

regards,
Chandran

i would like to know,how can

On September 21st, 2006 gurpreet (not verified) says:

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

On June 12th, 2006 Anonymous (not verified) says:

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

On March 23rd, 2006 thujone (not verified) says:

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

Thanks

On February 5th, 2006 David (not verified) says:

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.

Thanks!
Stay JOLLY!
D

Set up SSH on multiple servers and workstations

On December 23rd, 2005 Anonynous (not verified) says:

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

On January 9th, 2007 rohit kumar (not verified) says:

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

On November 2nd, 2005 Dicha (not verified) says:

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 & id_dsa.pub under dir .ssh/ and i have appended the public keys ,i have only some connections which take place without password .For example:

user1->user2
user1->user3
user2<-->user3
user4 with noone

Connection without password!

On November 2nd, 2005 Di.Chatz. (not verified) says:

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 ?

On October 18th, 2005 Anonymous (not verified) says:

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.

Cheers.

Using SCP in a C program

On October 18th, 2005 Anonymous (not verified) says:

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

On October 13th, 2005 ryant (not verified) says:

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':


#!/bin/sh

# $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
fi

MYPUBKEY=~/.ssh/id_rsa.pub
cmd=""
login="yes"
while getopts "h:c:n" opt; do
case ${opt} in
h)
host=${OPTARG}
;;
c)
cmd="${OPTARG}"
;;
n)
login="no"
;;
*)
echo 'Usage: $0 -h -c '
exit 21
;;
esac
done

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

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

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

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

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

On October 10th, 2005 Anonymous (not verified) says:

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

On October 8th, 2005 Sukant Hajra (not verified) says:

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:
http://www.cis.upenn.edu/~bcpierce/unison/
http://www.linuxjournal.com/article/7712

use Rsync thru SSH

On October 8th, 2005 fak3r (not verified) says:

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
    then
    /usr/local/bin/rsync -ave ssh --delete diego:/home/fak3r/documents/ /mnt/backup/diego/documents/
    else
    echo "Diego unreachable"
    fi
    exit 0

fak3r

Suprised this is never mentioned in these tutorials.

On October 7th, 2005 Ian (not verified) says:

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.

Cygwin

On October 7th, 2005 Anonymous (not verified) says:

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

On October 10th, 2005 Meeuw (not verified) says:

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

On October 7th, 2005 Anonymous (not verified) says:

Clyde's authorized_keys file would actually be in

/home/clyde/.ssh/authorized_keys

not

/home/clyde/authorized_keys

Small correction in step #6

On October 7th, 2005 Jeff Smith (not verified) says:

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.

2dn step: rsync

On October 7th, 2005 polarizer (not verified) says:

Since rsync[1] can use a working public key ssh auth transparently it would be the better choice for backup/syncronization once you have to pubkey auth working.


man rsync

>For remote transfers, a modern rsync uses ssh
>for its communications, but it may have been configured
>to use a different remote shell by default, such as
>rsh or remsh.

[1] http://samba.anu.edu.au/rsync/

polarizers 2cent

Even better would be unison:

On October 7th, 2005 Anonymous (not verified) says:

Even better would be unison:

http://www.cis.upenn.edu/~bcpierce/unison/

But, using scp is sometimes more appropriate.

Good stuff...

On October 7th, 2005 Anonymous (not verified) says:

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):
http://samba.anu.edu.au/rsync/

Good stuff...

On October 7th, 2005 Anonymous (not verified) says:

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):
http://samba.anu.edu.au/rsync/

A reasonable article. But th

On October 6th, 2005 Anonymous (not verified) says:

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" < identity.pub

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

Or even simpler with ssh-copy

On October 7th, 2005 Anonymous (not verified) says:

Or even simpler with ssh-copy-id

ssh-keygen -t rsa
ssh-copy-id -i identity.pub root@bozo

BTW, it's appropriate that the host is called 'bozo' as having passphrase-less keys is a dumb idea.

You should never ssh to root

On October 9th, 2005 Anonymous (not verified) says:

You should never ssh to root (PermitRootLogin=no)

Not for automated cron jobs.

On October 7th, 2005 Anonymous (not verified) says:

Not for automated cron jobs. :)

ftp can be used in script

On October 8th, 2005 hanwoody (not verified) says:

ftp can be used in script,and can support tls.

search for pscp on google.

On November 1st, 2006 Anonymous (not verified) says:

search for pscp on google. It is part of PuTTY and is free. There is a windows and a linux version available. You can specify a password using the -pw option.

Thank you. Finally someone

On November 2nd, 2007 Anonymous (not verified) says:

Thank you. Finally someone mentions the one step process for this, instead of the the two or more step key crap above.

Featured Video

Shawn Powers has a message for hardware vendors. Listen up!

From the Magazine

August 2008, #172

There's nuttin like a Cool Project to give you some relief from the summer heat, so get out your parka cuz we got a bunch of em. First up is the BUG, not a bug, The BUG. It's got a GPS, camera and more, in a hand-sized package that's user programmable. The BUG does everything. It's both a floor wax and a dessert topping. Get one now. Need a software version of a Swiss Army knife? Take a look at Billix, and don't leave home without it. Then, chew on this one, an X server on a Gumstix device driving an E-Ink display. Need more storage? How about 16 Terabytes? Can do.

And, of course, we have the usual cast of characters: Marcel, Reuven, Dave, Kyle, Doc, plus the new kid on the block Shawn Powers. But it doesn't stop there: build a MythTV box on a budget, build your own GIS system, set up the tools to monitor your enterprise and more. Finally, remember The War of the Worlds? Now you can play too.

Read this issue