I regularly use SSH (Secure Shell) to control the various Raspberry Pis that I have set up as none of them are connected to a monitor / keyboard / mouse and it provides easy access from my laptop.
Note: The first piece of advice when using SSH with Raspbian is to make sure the default account password is changed. If you are using a firewall make sure the new SSH port is defined in the firewall and if you use port forwarding on your router (e.g. to allow SSH connections from the internet) make sure it forwards the relevant ports. With all that said…
I’ve already advised on installing / using a firewall with Raspbian but what if you want to hide that your Pi has SSH enabled? By default SSH uses port 22 but this can be changed, on the device that is allowing SSH connections open a terminal and enter:
sudo nano /etc/ssh/sshd_config
This command uses the nano editor (feel free to use other editors such as vim) to open the ssh server configuration file so that changes can be made.
There are a few settings that can be changed here, including the maximum number of sessions and maximum number of authentication attempts, but today the line I am going to address is:
This line is currently commented out with the # and has the default port value (port 22). Uncomment the line and change the 22 to a different port value. Ports numbers up to 1023 are “well known” ports (see https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers) and should be avoided. I’m going to use port 2244.
With that line changed use CTRL X to exit the nano editor and make sure to enter Y (yes) to save changes.
The SSH service will then need restarting, or the device rebooting.
Once the SSH service has restarted or the device rebooted then the port will have changed and trying to SSH will generation a connection refused message.
To use SSH to connect to the correct port some adjustment needs making to the SSH connection line, so instead of:
We now need to enter:
ssh -p PORTNUMBER user@ip_address
For my example this is:
ssh -p 2244 firstname.lastname@example.org
What About Ansible?
If you use Ansible and change the SSH port from port 22 to a different port number then you may notice that Ansible fails to connect. This is because Ansible uses SSH and uses the default SSH port. To let Ansible know that you have changed the port the Ansible inventory file will need updating.
To do this using nano enter:
sudo nano /etc/ansible/hosts
The ansible hosts file will open and contain details about the hosts set up in Ansible.
Any hosts that are using a different SSH port needs the port appending to with :PORTNUMBER , e.g. 192.168.0.38 becomes 192.168.0.38:2244
More details are available at: https://docs.ansible.com/ansible/2.3/intro_inventory.html