Skip to content

Instantly share code, notes, and snippets.

@rakesh1988
Forked from jc-torresp/access-pi-anywhere.md
Created July 6, 2024 16:52
Show Gist options
  • Save rakesh1988/7049df6a7808c2e471dea7d7493ffad6 to your computer and use it in GitHub Desktop.
Save rakesh1988/7049df6a7808c2e471dea7d7493ffad6 to your computer and use it in GitHub Desktop.
Configuration to access Raspberry Pi from anywhere with UPnP port forwarding

Access Raspberry Pi from anywhere

Dynamic DNS

We need to use so called Dynamic DNS (DDNS) to create and dynamically update a mapping between a chosen domain name and an “external” IP address of our Raspberry Pi (i.e. router IP address).

  • Look for a DDNS provider.
  • Register a new user account.
  • Choose a desire domain name.
  • Configure it on router.

UPnP port forwarding

Router's NAT hides all devices in the “internal” router network (LAN) from inbound Internet connections. To route “external” (WAN) connections to the Raspberry Pi we will employ port forwarding on a router. We will rely on Universal Plug and Play (UPnP) protocol to dynamically configure proper port forwarding rules.

Installation:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install miniupnpc

Check router supports UPnP:

upnpc -l

This command should:

  • Enumerate all supported UPnP devices on local network.
  • Display their internal- and external IP addresses.
  • List their current port forwarding rules.

Add a port forwarding (for SSH and RDP protocol):

upnpc -e 'SSH on Raspberry Pi' -r 22 TCP
upnpc -e 'RDP on Raspberry Pi' -r 3389 TCP

Repeat process to other services on Raspberry Pi that we would like to port forwarding.

Establish an SSH connection to the Raspberry Pi from the Internet:

ssh user@your.domain.name

NOTE: most routers are not able to establish “external” connections from the internal network itself, so a separate Internet connection is needed to fully test the setup.

Unattended configuration

Create a shell script in editor:

sudo nano /usr/local/bin/redirect.sh

Insert content:

#!/bin/bash
upnpc -e 'SSH on Raspberry Pi' -r 22 TCP > /dev/null
upnpc -e 'RDP on Raspberry Pi' -r 3389 TCP > /dev/null

Configure Cron to periodically run the script (every 20 minutes):

sudo crontab -e

Add the following line:

*/20 * * * * /usr/local/bin/redirect.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment