2
votes

I can SSH into the EC2 instance:

ssh -i "my_key.pem" ec2-user@my-public-ip

However, scp doesn't work:

scp -r –i "my_key.pem" ./my_file ec2-user@my-public-ip:/home/ec2-user/my_file

Permission denied (publickey).
lost connection

I've also tried using public instance DNS, but nothing changes.

Any idea why is this happening and how to solve it?

3
Place -r after -i "my_key.pem"mootmoot
Post the verbose logs of both commands.Jakuje

3 Answers

3
votes

The only way for this to happen is the private key mykey.pem is not found in the current directory. It is possible you tried ssh from a directory different than scp.

Try the following with full path to your key:

scp -r –i /path/to/my_key.pem ./my_file ec2-user@my-public-ip:/home/ec2-user/my_file

If it fails, post the output with -v option. It will tell you exactly where the problem is

scp -v -r –i /path/to/my_key.pem ./my_file ec2-user@my-public-ip:/home/ec2-user/my_file
1
votes

I am bit late but this might be help full to someone.
Do not use the /home/ec2-user. Rather directly use the file name or folder name E.g. the following command will put your my_file at the home folder (i.e. /home/ec2-user)

scp -r –i "my_key.pem" ./my_file ec2-user@my-public-ip:my_file

Or Say if you have a folder at /home/ect-user/my_data
Then use the following command to copy your file to the folder

scp -r –i "my_key.pem" ./my_file ec2-user@my-public-ip:my_data
0
votes

Stupidly late addendum:

To avoid specifying the private key every time, just add to the .ssh/config file (create it if not already there) the following (without comments):

Host testserver                  // a memorable alias
Hostname 12.34.56.67             // your server ip
User ec2-user                    // user to connect
IdentityFile /path/to/key.pem    // path to the private key
PasswordAuthentication no

Then a simple ssh testserver should work from anywhere (and consequently your scp too).

I use it to connect with Vim via scp using:

vim scp://testserver/relative/file/path

or

vim scp://testserver//absolute/file/path

and

vim scp://testserver/relative/dir/path/ (note the trailing slash)

to respectively edit files and browse folders directly from local (thus using my precious .vimrc <3 configuration).

Solution found here

Hope this helps! :)