Skip to content

Instantly share code, notes, and snippets.

@sevmorris
Last active July 17, 2024 04:45
Show Gist options
  • Save sevmorris/a47ac303ec862e74248f38f5c52d7d04 to your computer and use it in GitHub Desktop.
Save sevmorris/a47ac303ec862e74248f38f5c52d7d04 to your computer and use it in GitHub Desktop.

Headless Raspberry Pi Initial Setup Guide

This guide outlines the steps I follow after a fresh Raspberry Pi OS Lite (64-BIT) installation on a headless RasPi. It assumes you have already installed the OS, enabled SSH, and successfully connected to your RasPi via SSH. While it works well for my purposes, your preferences and requirements might differ. Use this as a starting point and adjust it as needed.

After completing this guide you may want to check out my Headless Raspberry Pi Optimization Guide.


Update/Upgrade

Update the list of available packages and then upgrade all installed packages to their latest versions, automatically handling dependencies:

sudo apt update && sudo apt -y full-upgrade

Initial Configuration

These settings can also be configured using raspi-config. I simply prefer using commands.

Enable Console Autologin:

This configuration change allows your RasPi to automatically log in as the specified user on boot, eliminating the need to manually enter credentials every time.

  1. Open the autologin configuration file:

    sudo nano /etc/systemd/system/getty@tty1.service.d/override.conf
    
  2. If the file doesn't exist, create it and add the following content:

    [Service]
    ExecStart=
    ExecStart=-/sbin/agetty --autologin pi --noclear %I $TERM
    

    (Replace pi with your desired username if it's different.)

  3. Save and exit the editor (Ctrl+X, then Y, then Enter).

Expand Filesystem:

This process ensures that your operating system utilizes all the available space on your SD card, which is especially important if you've installed a larger card after initially setting up your RasPi.

  1. Install Required Tool:

    The tool to expand the root partition, growpart, is not included in the default Raspberry Pi OS installation.

    sudo apt install cloud-guest-utils
    
  2. Check the current partition layout:

    sudo parted -l
    
  3. Resize the root partition to fill the SD card:

    sudo growpart /dev/mmcblk0 2
    
  4. Expand the filesystem to match the resized partition:

    sudo resize2fs /dev/mmcblk0p2
    
  5. Reboot:

    sudo reboot
    

Configure key-based ssh authentication

Key-based authentication is significantly more secure than password-based authentication for remote access. Passwords are vulnerable to brute-force attacks, whereas keys are much harder to crack. Additionally, key-based authentication allows for convenient, passwordless logins once set up correctly.

FIRST STEP - ON LOCAL MACHINE:

Generate a pair of cryptographic keys (public and private). The private key remains on your local machine and should be kept secret.

If you have not already generated keys execute this command on your local machine:

ssh-keygen -t rsa

Copy the public key to your Raspberry Pi (adjust for correct user & ip):

scp ~/.ssh/id_rsa.pub <user>@<ip>:

SECOND STEP - ON REMOTE MACHINE (RasPi):

SSH into remote machine and create .ssh directory, then copy public key to authorized_keys file:

mkdir -p .ssh && cat ~/id_rsa.pub >> ~/.ssh/authorized_keys

Remove the original copy:

rm ~/id_rsa.pub

Reboot

sudo reboot

Install and Configure Things

Install a batch of applications

sudo apt -y install curl figlet git htop ii neofetch net-tools nmon

This command installs a set of tools commonly used for system administration, monitoring, software development, and basic image viewing. It's particularly useful for setting up a headless Raspberry Pi, where most interactions are done through the command line.

Here's a breakdown of each package:

  • curl: A command-line tool for transferring data using various protocols, including HTTP, FTP, and others. Commonly used to download files or scripts from the internet.
  • figlet: Creates large text banners from regular text. Mostly used for fun and decorative purposes.
  • git: A distributed version control system used for tracking changes in source code during software development. Essential for collaborating on projects.
  • htop: An interactive process viewer similar to top, but with a more user-friendly interface and features like vertical and horizontal scrolling.
  • ii: A simple command-line image viewer for viewing images in the terminal.
  • neofetch: Displays system information (OS, kernel, hardware, etc.) in a visually appealing format along with your system's logo.
  • net-tools: A collection of basic networking tools like ifconfig (now replaced by ip) and netstat (now replaced by ss). Still useful for some specific tasks.
  • nmon: A system monitoring tool that displays performance statistics for CPU, memory, network, and disk usage.

Install Github CLI

GitHub CLI (Command Line Interface) is a tool that lets you interact with GitHub repositories and features directly from your terminal or command prompt. It provides a way to perform common actions like creating pull requests, reviewing code, and managing issues without leaving your command-line environment.

Copy/paste & execute the entire block:

type -p curl >/dev/null || (sudo apt update && sudo apt install curl -y)
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
&& sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
&& sudo apt update \
&& sudo apt install gh -y

Install Oh My Bash

Oh My Bash is a free, open-source framework for managing your Bash configuration on Unix-like systems. It simplifies customization by providing a collection of themes, plugins, and helpful functions to enhance your command-line experience.

bash -c "$(curl -fsSL https://raw.githubusercontent.com/ohmybash/oh-my-bash/master/tools/install.sh)"

Modify .bashrc & create .hushlogin

The following code changes the default Oh My Bash theme to my preferred theme called Zork.

.hushlogin is an empty file that suppresses the display of the "Last login" message and other system information that's typically shown when logging into a Unix-like system through a terminal.

Copy/paste & execute the entire block:

# Change Oh My Bash theme
sed -i 's/font/zork/g' ~/.bashrc

# Append the following to ~/.bashrc
cat >> ~/.bashrc << EOL

alias c="clear && source ~/.bashrc"

# Remove duplicate $PATH entries (https://unix.stackexchange.com/a/149054)
PATH="$(perl -e 'print join(":", grep { not $seen{$_}++ } split(/:/, $ENV{PATH}))')"

# A rather comprehensive update alias:
alias update='sudo apt update && sudo apt -o Dpkg::Options::="--force-confdef" dist-upgrade -y && sudo apt autoremove -y && if sudo test -f /var/run/reboot-required; then read -p "A reboot is required to finish installing updates. Press [ENTER] to reboot now, or [CTRL+C] to cancel and reboot later." && sudo reboot; else echo "A reboot is not required. Exiting..."; fi'

# Show line numbers in nano
alias nano="nano --linenumbers "

neofetch
EOL

touch ~/.hushlogin
source ~/.bashrc

OPTIONAL TASKS

Overclock

Overclocking can boost performance but might increase heat and power consumption. You should have your RasPi in a case with a fan.

  1. Edit Configuration:

    sudo nano /boot/firmware/config.txt 
    
  2. Add Parameters:

    over_voltage=6        # Increase voltage for stability (6 is a safe starting point)
    arm_freq=2147         # Maximum CPU frequency (2147 MHz is a common limit for Pi 4)
    gpu_freq=750          # GPU frequency (adjust if needed for graphics-heavy tasks)
    
  3. Save and Exit:

    Press Ctrl+X to save the file and exit nano (follow prompts).

Important Considerations:

  • Monitor Temperature: Use vcgencmd measure_temp to check your RasPi's temperature regularly. If it gets too hot, reduce the overclock settings or add cooling.
  • Power Supply: Overclocking requires a reliable power supply capable of providing enough current.
  • Warranty: Overclocking might void your warranty. Proceed at your own risk.
  • Stability: Not all Raspberry Pis will overclock to the same extent. You might need to experiment to find stable settings.

Create USB swap drive

This section of the guide outlines the steps to set up a dedicated swap partition on a USB drive. By utilizing a USB drive for swap space, you can free up valuable system resources on your RasPi's SD card and potentially improve overall performance.

  1. Disable and uninstall dphys-swapfile:

    sudo dphys-swapfile swapoff
    sudo dphys-swapfile uninstall
    sudo update-rc.d dphys-swapfile remove
    

    If the following returns a directory:

    ls -l /etc/systemd/system/multi-user.target.wants/dphys-swapfile.service
    

    remove it:

    sudo rm /etc/systemd/system/multi-user.target.wants/dphys-swapfile.service 
    
  2. Identify USB Drive:

    lsblk
    
  3. Format (replace sda with correct drive if different):

    sudo fdisk /dev/sda
    
    • Type d, then 1 to delete existing partitions (if any).
    • Type n, then p for primary, accept defaults.
    • Type t, then 82 for Linux swap.
    • Type w to write changes.
  4. Activate and Make Permanent:

    sudo mkswap /dev/sda1  # Replace with your partition
    sudo swapon /dev/sda1
    echo "/dev/sda1  none    swap    sw    0   0" | sudo tee -a /etc/fstab 
    
  5. Verify:

    sudo swapon --show  
    free -h
    


This guide was created with the assistance of Gemini.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment