dnestoff
3/4/2020 - 3:50 PM

EC2 Commands

Commands for working with EC2 instances via SSH and the command line.

EC2 Commands for command line

Adding a pub key to an EC2 instance

Use the following command to copy your key to your Amazon EC2 instance. /you/.ssh/id_rsa.pub is the location to your ssh key, pem_file.pem is the .pem file you normally use to login, and user@ec2-instance.com is the user and hostname to your EC2 instance:

cat /you/.ssh/id_rsa.pub | ssh -i pem_file.pem user@ec2-instance.com "cat >> .ssh/authorized_keys"

https://mikeeverhart.net/2013/05/adding-an-ssh-key-to-amazon-ec2/

Open SSH Tunnel

A command to open up an SSH tunnel at a given port (port = 9000 below):

SSH && ssh -i pem_file.pem -N -M -S /tmp/ssh_tunnel_%h.sock -L 9000:<rds-endpoint>:3306 user@ec2-instance.com -v

# check if a server runs on apache2 or nginx

if [[ `ps -acx|grep apache|wc -l` > 0 ]]; then
>     echo "VM Configured with Apache"
> fi
ubuntu@ip-172-168-1-192:~$ if [[ `ps -acx|grep nginx|wc -l` > 0 ]]; then
>     echo "VM Configured with Nginx"
> fi
# Check the disk space usage (in human readable format)
df -h
# Check a specific disk
df -hT /dev/xvda1

  # Example output

# Filesystem      Size  Used Avail Use% Mounted on
# udev            462M     0  462M   0% /dev
#tmpfs            99M  1.9M   97M   2% /run
#/dev/xvda1       16G   14G  1.8G  89% /
#tmpfs           492M     0  492M   0% /dev/shm
#tmpfs           5.0M     0  5.0M   0% /run/lock

# Find files over specific size
sudo find /var -xdev -type f -size +100M

  # Example output
  
# /var/www/html/path/to/file
# /var/www/html/path/to/file2
# /var/www/html/path/to/file3

# Linux find largest file in directory recursively using find
  # du will estimate file space usage, sort will sort out the output of du command, head will only show top 20 largest files
du -a /dir/ | sort -n -r | head -n 20