Setting up a headless Raspberry Pi

It's been a little while since I last installed Raspbian on a Raspberry Pi. One key change that passed me by was:

2016-11-25:

  • SSH disabled by default; can be enabled by creating a file with name "ssh" in boot partition

As a result, when I tried to connect via SSH I got the following message:

$ ssh 192.168.1.123
ssh: connect to host 192.168.1.123 port 22: Connection refused

As the change log entry suggests, the quick fix to this problem is to create an empty file called ssh in the boot partition before starting the Raspberry Pi. If you're curious why this changed, it's worth reading the official blog post on the change. The rest of this post is going to go over the steps required to set up a headless Raspberry Pi, now this change has been implemented.

Imaging an SD card

There are a few different ways to install Raspbian. The official Raspberry Pi docs suggest using Etcher; by all means feel free to follow them, however I normally use dd:

$ dd if=2017-11-29-raspbian-stretch-lite.img of=/dev/sdd bs=1M status=progress
1855979520 bytes (1.9 GB) copied, 510.010932 s, 3.6 MB/s
1772+0 records in
1772+0 records out
1858076672 bytes (1.9 GB) copied, 510.548 s, 3.6 MB/s

Note: make sure you get the right device! Check /proc/partitions if you're not sure.

Enabling SSH

The next thing to do is create an empty file in the boot partition called ssh:

Boot partition with an empty ssh file.

You should now be able to boot from the SD card. When the Raspberry Pi boots up it will then run the following systemd unit file which should enable and start sshd:

[Unit]
Description=Turn on SSH if /boot/ssh is present
ConditionPathExistsGlob=/boot/ssh{,.txt}
After=regenerate_ssh_host_keys.service

[Service]
Type=oneshot
ExecStart=/bin/sh -c "update-rc.d ssh enable && invoke-rc.d ssh start && rm -f /boot/ssh ; rm -f /boot/ssh.txt"

[Install]
WantedBy=multi-user.target

Note: if you're curious, the unit file can be found in /lib/systemd/system/sshswitch.service.

Changing the password

Once the Raspberry Pi has booted you should be able to log into it:

$ ssh pi@192.168.1.123
The authenticity of host '192.168.1.123 (192.168.1.123)' can't be established.
ECDSA key fingerprint is SHA256:vxSHK93pryNefDCsHoeVfO4tlo0HN/HhSWYUGb6bjUc.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.123' (ECDSA) to the list of known hosts.
pi@192.168.1.123's password:

Finally once you've logged in with the default raspberry password, you should used passwd to reset the password:

pi@raspberrypi:~ $ passwd
Changing password for pi.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully