In this section we will use the AWS CLI (Command Line Interface) to copy data from:
Local machine to EC2 instance and vice-versa
echo “Hello, world” > test.txt
scp -i path/to/key.pem path/to/test.txt ubuntu@<ip-address>:/home/ubuntu/
If you are using windows command prompt and have the PuTTY suite of utilities installed, run the following command
pscp -P 22 -i path/to/key.ppk path/to/test.txt ubuntu@<ip-address>:/home/ubuntu/
Alternative: use rsync - the options here preserve timestamps and permissions (-a), and only transfer if it would result in an updated version (-u). This can help with tracking what the latest file is; using scp as above will just overwrite the destination even if the file exists at the destination and is newer.
rsync -e 'ssh -i /path/to/key.pem' -avxu /path/to/test.txt ubuntu@<ip-address>:/home/ubuntu/
Open the test.txt file using a text editor on your remote machine and edit it - add random text and save it.
Copy the test.txt file back to your local machine by using the scp/pscp command on your local terminal.
scp -i path/to/key.pem ubuntu@<ip-address>:/home/ubuntu/test.txt path/to/folder/localmachine
If you are using windows command prompt run the following command
pscp -P 22 -i path/to/key.ppk ubuntu@<ip-address>:/home/ubuntu/test.txt path/to/folder/localmachine
Alternative: use rsync:
rsync -e 'ssh -i /path/to/key.pem' -avux ubuntu@<ip-address>:/home/ubuntu/test.txt /path/to/folder/localmachine
EC2 to EC2 instance
Now let us copy the sample test.txt file from your current instance (CI) to another instance (AI) you have earlier started.
-i
option in SSH. Be sure to change the permissions as well (chmod 0400 keyname.pem). You can use scp to copy it to your new CI. (You will need the key file in order to communicate (SSH or SCP) with another instance with the same key pair)scp -i path/to/key.pem path/to/test.txt ec2-user@<ip-address>:/home/ec2-user/
NOTE: Username to be used here are ec2-user or ubuntu if your instance was spun up from an Amazon Linux OS or Ubuntu Linux OS images, respectively.
ssh -i path/to/key.pem ec2-user@<ip-address>