[Tips] Using scp without password

DaBeen Yi
2 min readJul 5, 2021

How to use scp command with password

Situation

  1. I need to copy plenty of files from one server to the other server.
  2. I will send files one at a time. (Complete copying a file and then move to next file to copy it.)
  3. I will use scp command
  4. But I found a little problem when I did a test.🥲 A problem is that I need to enter password of a remote server every single time.

So, to solve this issue I did a bit of research and found 3 ways to do it.

a. Using sshpass function

b. Use a new user account without password (Create a new account on a remote server.)

c. Use public, private key

a, b sounds simple and easy but I’m pretty sure it’s not a good idea for security aspect. So, I will choose c to do.

How to use do it?

I refer to this site.

  1. (From source server) Create public/private key with ssh-keygen command. (I set all options as default.)
[sonia.lee@test-server ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/sonia.lee/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/sonia.lee/.ssh/id_rsa.
Your public key has been saved in /home/sonia.lee/.ssh/id_rsa.pub.
The key fingerprint is:blabla
The key's randomart image is:blabla

2. Copy public key (/home/sonia.lee/.ssh/id_rsa.pub) to a remote server that I want to send files.

scp /home/sonia.lee/.ssh/id_rsa.pub sonia.lee@2.2.2.2:~/.ssh
  • If there is no ‘.ssh’ directory on a remote server, then create one using mkdir .ssh command.

3. Rename ‘id_rsa.pub’ to ‘authorized_keys’.

mv .ssh/id_rsa.pub .ssh/authorized_keys

4. Change permission of .ssh directory and authorized_keys file.

$ chmod 700 .ssh
$ chmod 600 .ssh/authorized_keys
  • If you create second ssh key and use for the same target then a new public key should be added on ‘authorized_keys’ file. (Do not create the other file!)

5. Check if it works

[sonia.lee@test-server ~]$ ssh sonia.lee@2.2.2.2
Last login: Mon Jul 5 15:31:25 2021 from 1.1.1.1
[sonia.lee@remote-server ~]$ exit

Appendix

A simple bash script to copy plenty of files from one to the other.

#!/bin/bashfor object in "/home/sonia.lee/tests_list"/*
do
scp $object sonia.lee@2.2.2.2:~
sleep 5
done

🍰

--

--