Jun 2

Public/Private Key as User/Root

Tags:

Sometimes it’s the small things that are fun to think through.  I was recently transferring a plethora of files between two servers, so I set up a private/public key to avoid typing in a user password every time I hit enter.

I usually use the secure copy (scp) command to transfer files via command line, so that’s what I did.  Everything was hunky-dory until I needed to use root permissions to transfer a few of the files.  Here were the sequence of events:

$ scp servertheory.com.log server2user@123.45.67.89:~/dir/
servertheory.com.log 100% 3996KB 3.9MB/s 00:01

$ sudo scp servertheory.com.log server2user@123.45.67.89:~/dir/
[sudo] password for server1user:
server2user@123.45.67.89’s password:
servertheory.com.log 100% 3996KB 3.9MB/s 00:00

As you can see, when I use root privileges with sudo to transfer the file, the private/public key no longer works.  It’s now asking for the destination’s server2user password.

So what’s the reason for this?  The explanation is simple.  When you use root privs via the sudo command, you are elevating yourself to that level.  The sudo user will no longer reference the private key located in server1user:~/.ssh/private_key because it’s referencing root:~/.ssh/private_key.  Therefore, if you’d like to have the same simple access to transfer files to server2user, you have two options.  First, you can create a new pair of private/public keys for your root account; or second, you can simply copy the private key to your root:~/.ssh/ folder which will reference the same public key under server2user.  Here’s what happened when I did the latter:

$ scp servertheory.com.log server2user@123.45.67.89:~/dir/
servertheory.com.log 100% 3996KB 3.9MB/s 00:01

$ sudo scp servertheory.com.log server2user@123.45.67.89:~/dir/
[sudo] password for server1user:
servertheory.com.log 100% 3996KB 3.9MB/s 00:00

Asking for the sudo user’s password is normal.  When it didn’t ask for server2user@123.45.67.89’s password, we knew that the technique was working.

Have fun with your servers!

—————————————–

Always remember… WHAT IF AND WHY NOT?!?