Turn On SSH Service On Ubuntu

💡 This post is insightful for the following scenarios.

  • Turn On Ubuntu SSL Service
  • Connect Ubuntu From Public Network

Background

I would like to control my server when I am not at home. Let set target server is A, and the laptop is B.

Step

1. Get the local IP of A

1
2
3
# run on A
ifconfig
# let assume this IP is 192.168.1.1

2. SSH from B in the same WI-FI - Fail

1
2
3
4
# run on B
ssh user@192.168.1.1

# ssh: connect to host user@192.168.1.1 port 22: Connection refused

3. Install OpenSSH in A

1
sudo apt-get install -y openssh-server

4. SSH from B in the same WI-FI - Success

1
2
3
4
5
# run on B
ssh user@192.168.1.1

# connect successfully
# but not secure enough

5. Generate key in A

1
2
3
4
5
6
7
8
# keep clicking enter
ssh-keygen

# enter ssh folder to see public key and private key
cd ~/.ssh
cat id_rsa.pub >> authorized_keys

# copy the private key to B

6. Change SSH configuration in A

1
2
3
4
5
6
7
8
9
sudo vim /etc/ssh/sshd_config

# enable:
# use public key to login
# "PubkeyAuthentication yes"
# people can not use password to login
# "PasswordAuthentication no"
# change SSL port:
# "Port 33333"

7. Restart SSH service in A

1
service sshd restart

8. B Use private key to ssh A

1
2
3
4
5
6
7
8
9
10
ssh user@192.168.1.1 -p 33333
# user@192.168.1.1: Permission denied (publickey).

# enter the folder that contains private key
ls
# id_rsa
chmod 0600 id_rsa

ssh user@192.168.1.1 -p 33333 -i id_rsa
# login successfully

9. Add private into system in B

1
2
3
4
5
6
# login successfully now even without linking private key, however, it needs to run this command every time you poweroff B
ssh-add -K id_rsa
ssh user@192.168.1.1 -p 33333

# or you can set up the ssh configuration on B, which is macOS system
vim ~/.ssh/config

1
2
# and you can ssh A like that now, without setting username, port and identify file
ssh ubuntu

10. Connect to A from public IP

You need to enter your router to configure NAT Forwarding.

1
2
# you can now ssh to your server in outside by public IP address just like you did in your local network
ssh user@142.251.165.100 -p 33333 -i id_rsa

Reference

Mac SSH Amazon Using Pem