Friday, 30 June 2017 21:17

Raspberry Pi - Auto WiFi Hotspot Switch Internet

Written by 

A script to allow the Raspberry Pi to connect to a know wifi router or automatically generate an Internet Hotspot Access Point if no network is found. You can then use SSH or VNC on the move and switch between the hotspot and network without a reboot.

When i am home I like to have my Raspberry Pi connected to the home network and the internet but when I am out I would like to connect to it via a hotspot using a tablet, phone or laptop. Usually this means when you are out you can't use your Raspberry Pi. The alternative is set it up as an access point so you can connect to it while you are out but when you are home you have to connect it to you routers ethernet port to use it on your home network.

I wanted a Raspberry Pi that connects to your home networks Wifi when you are home or generates a wifi Hotspot/Access Point when I am out.

I have done this in a previous script but, for my use, when it is in Hotspot mode it was not able to use the internet if you connect an ethernet cable. Which was fine for me but some users required this feature. So this article is how to setup a Raspberry Pi so it can automatically switch between a network wifi connection and an internet routed hotspot.

If you are using a Raspbery Pi Zero w that has no network port and don't need an internet routed Access Point then you can use theh other Hotspot switch script Raspberry Pi - Auto WiFi Hotspot Switch - Direct Connection


  • When your home:   On starting the Raspberry Pi it connects to your home routers wifi
  • When your out: On starting, if any known wifi connection is not found it will generate a hotspot so a direct wifi connection can be made to the Raspberry Pi by a tablet, phone or laptop.
  • While in Hotspot mode:  if an ethernet cable is connected the Raspberry Pi, then it will have internet access along with any wifi device connected to the Hotspot.

Additional Features:

Using a Cron, a timer can be setup so the wifi connection can be regulary checked. It will switch between a wifi router and a hotspot without a reboot depending on the results. This is useful for

  • Raspberry Pi in car entertainment systems
  • If the RPi looses wifi connection in your garden or near your home when using the camera or sensors.
  • You run a script or program at home connected to your router and wish to monitor it while you are out. As a hotspot is generated without a reboot the script/program is not interuppted.

It is also possible to run the script from a GPIO button so you can manually run the script to switch depending on where you are.



  • Raspberry Pi 3
  • Raspberry Pi 1,2 with a Wifi Dongle*,
  • Raspberry Pi Zero W and Zero with WiFi Dongle* (internet hotspot not useable as it has no ethernet port. I suggest you use the non internet version of the script Raspberry Pi - Auto WiFi Hotspot Switch - Direct Connection)
  • Wifi already configured for your home router

*some WiFi dongles don't work in adhoc mode or don't work with with the nl80211 driver used in this guide for RPi 3 & zero W inbuilt wifi, so you may want to check this first before starting.

 This setup has only be tested on the Raspbian Jessie OS and a connection has been made to the Hotspot using an Android Tablet, Ipad2 and Windows 10. All worked fine with SSH and had internet acces via the Raspberry Pi.

Note: Existing Autohotspot users

If you are currently are using one of my other autohotspot scripts and would like to change it to this setup please read all sections as there are changes to the dnsmasq.conf file, interfaces file, the service file and the autohotspot file.

Step 1:

To start with hostapd hotspot client and dnsmasq lightweight dns server need to be installed.

Open a Terminal session.

Update Raspbian with the latest updates by entering the commands:

sudo apt-get update
sudo apt-get upgrade

 To install hostapd enter the command:

sudo apt-get install hostapd

enter Y when prompted.

To install dnsmasq enter the command:

sudo apt-get install dnsmasq

enter Y when prompted

The installers will have set up the programme so they run when the pi is started. For this setup they only need to be started if the home router is not found. So automatic startup needs to be disabled. This is done with the following commands:

sudo systemctl disable hostapd
sudo systemctl disable dnsmasq

Now the hostspot configuration file can be setup. This contains the name of the WiFi signal you will need to connect to (SSID) and the security password.

To edit the configuration files I will be using the nano text editor but if you prefer an editor with an point and click interface then replace nano with leafpad in the following instructions.

Hostapd Configuration

Using a text editor edit the hostapd configuration file. This file won't exist at this stage so will be blank.

sudo nano /etc/hostapd/hostapd.conf

download file here:

  • The interface will be wlan0
  • The driver nl80211 works with the Raspberry Pi 3 & Zero W onboard WiFi but you will need to check that your wifi dongle is compatable and can use Access Point mode.

For more information on wifi dongles see

  • The SSID is the name of the WiFi signal broadcast from the RPi, which you will connect to with your Tablet or phones WiFi settings.
  • Channel can be set between 1 and 13. If you are having trouble connection because of to many wifi signals in your area are using channel 6 then try another channel.
  • Wpa_passphrase is the password you will need to enter when you first connect a device to your Raspberry Pi's hotspot. This should be at least 8 characters and a bit more difficult to guess than my example.

To save the config file press ctrl & o and to exit nano press Ctrl & x

Now the defaults file needs to be updated to point to where the config file is stored.
In terminal enter the command
sudo nano /etc/default/hostapd


And save.

DNSmasq configuration

Next dnsmasq needs to be configured to allow the Rpi to act as a router and issue ip addresses. Open the dnsmasq.conf file with

sudo nano /etc/dnsmasq.conf

Go to the bottom of the file and add the following lines (download here)

#AutoHotspot config

and the save (ctl & o) and exit (ctrl & x)

Step 2:

Now that hostapd and dnsmasq are configured we now need to make some changes to the interfaces file, setup ip_forwarding and create a service. Once these are done we can then add the autohotspot script.

Next we need to edit the interfaces file. There will be several entries relating to wlan0 already setup. Two lines needs to be changed, then entries for wlan0 should be as the example below.


sudo nano /etc/network/interfaces

Add wlan0 to the end of auto lo

auto lo wlan0

and put a # infront of both

iface wlan0 inet manual

wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf 

then add

iface wlan0 inet static

My interfaces file looks like this

# interfaces(5) file used by ifup(8) and ifdown(8)
# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d
auto lo wlan0
iface lo inet loopback
iface eth0 inet manual
allow-hotplug wlan0
#iface wlan0 inet manual
    #wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
iface wlan0 inet static
allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

now save (ctrl & o) and exit (ctrl & x)

 ip forwarding

While the RPi is in hotspot mode ip forwarding needs to be on so the internet works when an ethernet cable is attached. The autohotspot script will switch ip forwarding on and off between network mode and hotspot mode but it needs to be on by default for the script to manage ip forwarding.


sudo nano /etc/sysctl.conf

look for the line

# Uncomment the next line to enable packet forwarding for IPv4

and remove the # so it is

# Uncomment the next line to enable packet forwarding for IPv4

now save (ctrl & o) and exit (ctrl & x)

autohotspot service file

Next we have to create a service which will run the autohotspot script when the Raspberry Pi starts up.

create a new file with the command

sudo nano /etc/systemd/system/autohotspot.service

Then enter the following text or download here

Description=Automatically generates an internet Hotspot when a valid ssid is not in range

and save (ctrl & o) and exit (ctrl & x)


For the service to work it has to be enabled. To do this enter the command

sudo systemctl enable autohotspot.service

Software check:

If your version of Raspbian has been repeatedly upgraded from an old OS image, it is possible that that you don't have the correct wifi tools install. These are installed by default on more recent versions of Raspbian.

to check you have iw installed enter the command

dpkg -s iw

If it is installed the first two lines that shown should be

Package: iw
Status: install ok installed

if not enter the command

sudo apt-get install iw

AutoHotspot Script

This is the main script that will manage your wifi connections between a wifi router and an Access Point.

It will search for any wifi connection that is setup on you Raspberry Pi by using the details found in /etc/wpa_supplicant/wpa_supplicant.conf

If no wifi signal is found for a known SSID then the script will shutdown the wifi network setup and create a Hotspot. If an ethernet cable that allows internet access is connect then the Hotspot will become a full internet access point. Allowing all connected devices to use the Internet. Without an ethernet connect the Raspberry Pi can be accessed from a wifi device using SSH or VNC.

 The script works with SSID's that contain spaces and by entering your routers MAC address it can be used with hidden SSID's.

Hidden SSIDs

If you routers SSID is not broadcast/hidden then find this section in the script

#Enter the Routers Mac Addresses for hidden SSIDs, seperated by spaces ie
#( '11:22:33:44:55:66' 'aa:bb:cc:dd:ee:ff' )

and enter you routers MAC address in the brackets of mac=() as shown in the example. Make sure mutiple MAC addresses are seperated by a space.


 Creating the autohotspot script:

Create a new file with the command

sudo nano /usr/bin/autohotspotN

and add the autohotspot script. This can be downloaded from here

#version 0.90-N/HS-I
#You may share this script but a reference to must be included in copies or derivatives of this script. 
#Wifi & Hotspot with Internet
#A script to switch between a wifi network and an Internet routed Hotspot
#Raspberry Pi with a network port required for Internet in hotspot mode.
#Works at startup or with a seperate timer or manually without a reboot
#Other setup required find out more at
#These four lines capture the wifi networks the RPi is setup to use
wpassid=$(awk '/ssid="/{ print $0 }' /etc/wpa_supplicant/wpa_supplicant.conf | awk -F'ssid=' '{ print $2 }' ORS=',' | sed 's/\"/''/g' | sed 's/,$//')
IFS=$IFSdef #reset back to defaults
#Note:If you only want to check for certain SSIDs
#Remove the # in in front of ssids=('mySSID1'.... below and put a # infront of all four lines above
# separated by a space, eg ('mySSID1' 'mySSID2')
#ssids=('mySSID1' 'mySSID2' 'mySSID3')
#Enter the Routers Mac Addresses for hidden SSIDs, seperated by spaces ie 
#( '11:22:33:44:55:66' 'aa:bb:cc:dd:ee:ff' ) 
ssidsmac=("${ssids[@]}" "${mac[@]}") #combines ssid and MAC for checking
    ip link set dev wlan0 down
    ip a add brd + dev wlan0
    ip link set dev wlan0 up
    iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
    iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
    iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT
    systemctl start dnsmasq
    systemctl start hostapd
    echo 1 > /proc/sys/net/ipv4/ip_forward
    echo "Shutting Down Hotspot"
    ip link set dev wlan0 down
    systemctl stop hostapd
    systemctl stop dnsmasq
    iptables -D FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
    iptables -D FORWARD -i wlan0 -o eth0 -j ACCEPT
    echo 0 > /proc/sys/net/ipv4/ip_forward
    ip addr flush dev wlan0
    ip link set dev wlan0 up
        sleep 10 #give tine for ip to be assigned by router
	if ! wpa_cli status | grep 'ip_address' >/dev/null 2>&1
        then #Failed to connect to wifi (check your wifi settings, password etc)
	       echo 'Wifi failed to connect, falling back to Hotspot'
               wpa_cli terminate >/dev/null 2>&1
#Check to see what SSID's and MAC addresses are in range
for ssid in "${ssidsmac[@]}"
     if { iw dev wlan0 scan ap-force | grep "$ssid"; } >/dev/null 2>&1
#Create Hotspot or connect to valid wifi networks
if [ "$ssidChk" != "NoSSid" ] 
       echo 'Using SSID:' $ssidChk
       echo 0 > /proc/sys/net/ipv4/ip_forward #deactivate ip forwarding
       if systemctl status hostapd | grep "(running)" >/dev/null 2>&1
       then #hotspot running and ssid in range
              echo "Hotspot Deactivated, Bringing Wifi Up"
              wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
       elif wpa_cli status | grep 'ip_address' >/dev/null 2>&1
       then #Already connected
              echo "Wifi already connected to network"
       else #ssid exists and no hotspot running connect to wifi network
              echo "Connecting to WiFi Network"
              wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
else #ssid or MAC address not in range
       if systemctl status hostapd | grep "(running)" >/dev/null 2>&1
              echo "Hostspot already active"
       elif wpa_cli status | grep 'wlan0' >/dev/null 2>&1
              echo "Cleaning wifi files and Activating Hotspot"
              wpa_cli terminate >/dev/null 2>&1
              ip addr flush wlan0
              ip link set dev wlan0 down
              rm -r /var/run/wpa_supplicant >/dev/null 2>&1
       else #"No SSID, activating Hotspot"

and save (ctl & o) and exit (ctl & x)

one line goes off the page, for reference this is

wpassid=$(awk '/ssid="/{ print $0 }' /etc/wpa_supplicant/wpa_supplicant.conf | awk -F'ssid=' '{ print $2 }' ORS=',' | sed 's/\"/''/g' | sed 's/,$//')

but it is best to copy the script from the download link.

For the autohotspotN script to work it needs to executable. This is done with the command

sudo chmod +x /usr/bin/autohotspotN

Thats it, you are ready to go. Now test that everything is working ok.

Thanks to Willem Me and Tino for there contributions to the development of this script.

Testing the Hotspot

To test that the RPi is setup ok reboot the RPI. When the desktop returns you should have the wifi icon Raspbian Pixel WiFI icon by the clock.
For those setting this up on a headerless RPi then you should see the pi on your routers network. 

To test the hotspot works ok edit the ssid name of your router in the wpa_supplicant file.


sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

and add 'off' to the end of your routers ssid. For example:


change to


save (ctrl & o) and close (ctrl & x) the file

Now reboot the Raspberry Pi.

Once the RPi is up and running the wifi icon near the clock should now be two arrows facing opposite directions Raspbian Pixel AP mode icon This means it is an access point. On a Tablet, phone or Laptop scan for wifi signals. You should see one for RPiHotN.

Select this as the wifi signal to connect to. The password is what you setup in the hostapd.conf file. From my example it is 1234567890

android wifi in range list

Local wifi signals in range on Android

For SSH and VNC the connection ip is also if you have setup the Rpi as a webserver use the same ip to see the webpage.

For ssh use ssh This email address is being protected from spambots. You need JavaScript enabled to view it..5

For vnc use

If you now connect an ethernet cable to the Raspbery Pi and your router and wait a few seconds the hotspot will allow connected wifi devices to use the internet as well as the RPi.

 Once you are happy the setup is working ok change the wpa_supplicant.conf file back to your routers ssid. From the next reboot the autohotspotN script will manage your wifi connection.


Setting up a Timer

If the autohotspotN script is set to be run at set intervals, when you go out of range of your home router it will automatically generate a hotspot and then when you get back in range it will deactivate the hotspot and connect to the routers wifi. If you run a program in the background or use programs like tmux then any software you are running will keep working.

If you have an active ssh or vnc session running when the switch happens it will be lost.

Using a Cron job, tasks can be set off automatically at certain times, dates or intervals. For my use running the script every 5 minutes is fine but this can be changed to your needs. To setup a cron task enter the command

crontab -e

At the bottom of the file enter the command

*/5 * * * * sudo /usr/bin/autohotspotN >/dev/null 2>&1

There is a space after each entry and * except the first *.

The first * position is for minutes. If you want it to check every minute just use * instead of */5

If you want to use hours, say every 2 hours enter it as

* */2 * * * sudo /usr/bin/autohotspotN >/dev/null 2>&1

 Save the cron tab with ctrl & o and close it with ctrl & x

The cron job will automatically start straight away.

Disable Cron Timer

If you no longer need the timer running edit the cron with

crontab -e

and put a # infront so it is now

#*/5 * * * * sudo /usr/bin/autohotspot

The script will now only work at boot up or if you manually run the autohotspotN script with the command

sudo /usr/bin/autohotspotN



Dnsmasq bug: in versions below 2.77 there is a recent bug that may cause the hotspot not to start. This can be resolved by removing the dns-root-data.

check your version with : dpkg -s dnsmasq

versions 2.77 and above are ok. If not then try the command:

sudo apt-get purge dns-root-data

thanks to danny for highlighting this.


Script Removal

If you don't wish to continue using the autohotspotN script then the Raspberry Pi can be revered back to a standard wifi setup with the following steps.

Disable the script with the command

sudo systemctl disable autohotspot

Then disable ip forwarding

sudo nano /etc/sysctl.conf

look for the entry

# Uncomment the next line to enable packet forwarding for IPv4

and add a # as follows

# Uncomment the next line to enable packet forwarding for IPv4
# net.ipv4.ip_forward=1

Then reboot.

The autohotspotN script will no longer have control of you wifi. Dnsmasq and hostapd can be uninstalled if you no longer need them.

 Trouble Shooting

  • If you get no wifi connection or no hotspot and have this icon Network Downthen it is most likley the autohotspotN script is not executable or the service has not been enabled

redo the follow commands

sudo chmod +x /usr/bin/autohotspotN


sudo systemctl enable autohotspot.service


  • You are in range of your router but it only creates a hotspot. If there is an issue with connecting to the router, such as the password is wrong. The script will fall back to the hotspot so you still have some type of connection. Check your password in the wpa_supplicant.conf file. 
  • You can connect to the hotspot via an Android Phone but you can't get a ssh connection. Some users have found this issue where Android uses there data connection rather than the wifi. Disabeling data has allowed them to use ssh.   
  • If this setup is not working as expected you can check the script for errors by running it manually in a terminal window with the command, sudo /usr/bin/autohotspotN ,you can also check the service status with, sudo systemctl status -l autohotspot ,and if the hotspot has failed try, sudo systemctl status -l hostapd
  • You need to add a new wifi network to the RPi but it is in Hotspot mode so you are unable to scan for new wifi signals. You will need to add the new network to /etc/wpa_supplicant/wpa_supplicant manually. Enter the following details replacing mySSID and myPassword with the correct details


Last modified on Saturday, 22 July 2017 12:53
roboberry SuperUser.  Contactable via the site admin e-mail in the Contact Us link.


Leave a comment

Comments for Guest and account owners. Account owners will need to login to use registered e-mail address.


  • Comment Link Graeme Monday, 24 July 2017 00:37 posted by Graeme

    Hi Logan, I presume you are connecting on Hotspot mode. Which it will use but it looks like your VNC is configured to use ::5902. You can see which port it is set to in the connection settings on real vnc on the pi.
    I have just connected my self using real vnc viewer on a android tablet. My one is setup for ::5900 or :0 so connected fine after a reboot so, im not getting an issue at reboot.
    What I have noticed though is when the Pi is connected to the network the Real VNC window show ip address which is wrong. It should be the ip your router issues. in my case and port 5900.

    I think you are getting blank screen because the port has changed, every time you run vncserver it opens a new channel. If the old channel has closed then you won't be able to connect to it.
    I did run vncserver 3 times and got 3 new channels but was still able to connect to ::0 as it didn’t close. At bootup the channel should be ::0 (::5900) so that should be the one to use

    When you are connected to a router use the ip shown in the Real VNC window under "other ways to connect" that is from your router and not

    When you are in hotspot mode use

    let me know how you get on.

  • Comment Link Logan Sunday, 23 July 2017 17:58 posted by Logan

    For the record I have VNC configured through raspi-config to be enabled at start.

    When I try to VNC into my Pi using the provided IP above ( it only shows a black screen and white cursor. Im using RealVNC that comes with Pixel and Im using VNC Viewer on my android device.

    However if I run the command vncserver it provides with a different IP address that looks like this 192.XXX.X.X:2. If I then add that IP to my VNC viewer I can see the desktop and control the Pi. However if I reboot and try to connect again to the VNC viewer I get the error about failed port communication. Somthing like "the port on which the computer is listening for a connection could not be contacted".

    When that occurs, if I run the command vncserver again, I am able to connect but not with the IP provided above, only from the one provided by vncserver command. I suppose as a work around I could write a script that runs vncserver after boot but I thought I was already doing that by having it configured to start on boot through raspi-config.

    More pressing, why am I getting the black screen with white cursor. I am also configured to boot to desktop and be logged in. Any thoughts?

  • Comment Link Graeme Thursday, 20 July 2017 19:49 posted by Graeme

    Hi manny, I wouldn't like to say if you can or can't without trying. But in principal I would think yes. In hotspot mode you can have a device connected via ssh and another connected via VNC. So server client setups work. You will also be able to control kodi through the web server set-up in hotspot mode.

    If you try it out I would be interested to know how you get on.

  • Comment Link manny Thursday, 20 July 2017 03:45 posted by manny

    Is it possible to use Kodi installed on Raspbian Jessie while running the RPI3 in hotspot mode so that one can control playback and use the pi as a DLNA media renderer over the same wifi from another device connected to the pi? I'm trying to eliminate a router in my car setup and use the pi as a media server and DLNA DMR while also being the router.


Additional information