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.

 

Works with Raspbian & PiOS -  Bullseye, Buster, Stretch and Jessie.

Not compatible with PiOS Bookworm. Bookworm Version Here.

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 my home networks Wifi when I am at 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 the other Autohotspot switch script Raspberry Pi - Auto WiFi Hotspot Switch - Direct Connection

If you would just like a permanent acces point then you can use this guide Raspberry Pi - Hotspot/Access Point dhcpcd method

Easy Installer Script: the setup in this guide is available in an installer at Raspberry Pi AutoHotspot and Static Hotspot Installer Script

Aim:

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

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 an access point without a reboot depending on the results. This is useful for

  • Raspberry Pi in car entertainment systems
  • Raspberry Pi Dash Cams
  • 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.

 

 Requirements:

This has been tested on Raspbian & PiOS versions Bullseye (11) , Buster (10), Stretch (9) and Jessie (8). To see which version you have enter the command lsb_release -a

  • Raspberry Pi 3, RPi 3 B+, RPi4
  • Raspberry Pi 1 or 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 RPi4, RPi 3, RPi 3B+ & Pi Zero W inbuilt wifi, so you may want to check this first before starting.

This setup has been tested on Raspbian Jessie, Raspbian Stretch and PiOS Buster and PiOS Bullseye using a RPi4, RPi3B+, RPi3, Pi Zero W, Rpi Zero 2 and a RPI 2 . A connection has been made to the access point using an Android Tablet, Ipad2, Raspberry PI and Windows 10. All worked fine with SSH.

Note about Bullseye, Buster and Stretch Network Device Names

From Raspbian Stretch there has been changes to how the network drivers are named, called Predictable Network Interface Names,  and may be different for the usual wlan0 and wlan1 for wifi and eth0 for ethernet connections. Though the official Foundation version of PiOS seems to be keeping to the old standard names, at least at the time of writing,  this may not always be the case. For this guide I will use wlan0 as the device that is used.  

To check the device name for your setup enter the commmand iw dev and take a note of the "Interface" name. For wifi it should start with wl , replace your device name with any reference to wlan0 in the article, scripts and config files.

 

Step 1:

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

Open a Terminal session.

Update PiOS 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 and by default hostapd is masked so needs to be unmasked. This is done with the following commands:

sudo systemctl unmask hostapd

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. (Download here)

sudo nano /etc/hostapd/hostapd.conf


#2.4GHz setup wifi 80211 b,g,n
interface=wlan0
driver=nl80211
ssid=RPiHotspotN
hw_mode=g
channel=8
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=1234567890
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP TKIP
rsn_pairwise=CCMP

#80211n - Change GB to your WiFi country code
country_code=GB
ieee80211n=1
ieee80211d=1
 
  • The interface will be wlan0
  • The driver nl80211 works with the Raspberry RPi 4, RPi 3B+, RPi 3 & Pi Zero W, Pi Zero 2  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 elinux.org/RPi_USB_Wi-Fi_Adapters

  • 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 8 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 access point. This should be at least 8 characters and a bit more difficult to guess than my example.
  • The country_code should be set to your country to comply with local RF laws. You may experience connection issues if this is not correct. Your country_code can be found in /etc/wpa_supplicant/wpa_supplicant.conf or in Raspberry Pi Configuration - Localisation settings

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

(Note:  this bit for /etc/default/hostapd does not need to be changed for PiOS Buster or Bullseye. This is for the older OS's Stretch and Jessie)

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

Change:
#DAEMON_CONF=""
to
DAEMON_CONF="/etc/hostapd/hostapd.conf"

Check the DAEMON_OPTS="" is preceded by a #, so is #DAEMON_OPTS=""

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
interface=wlan0
bind-dynamic 
server=8.8.8.8
domain-needed
bogus-priv
dhcp-range=192.168.50.150,192.168.50.200,12h

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, dhcpcd.conf and create a service. Once these are done we can then add the autohotspot script.

The interfaces file is not required and should be empty of any network config. Depending which version of Raspbian you have this file may still contain network config.

Enter

sudo nano /etc/network/interfaces

If your file shows more than the standard top 5 lines 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

then make a copy of of your file and then remove any excess lines from the interfaces file.

To make a backup of your interfaces file use the command

sudo cp /etc/network/interfaces /etc/network/interfaces-backup

 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 access point mode but it needs to be on by default for the script to manage ip forwarding.

enter

sudo nano /etc/sysctl.conf

look for the line

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

and remove the # so it is

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

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

DHCPCD

dhcpcd is the software that manages the network setup. The next step is to stop dhcpcd from starting the wifi network so the autohotspot script in the next step takes control of that. Ethernet will still be managed by dhcpcd.

Open dhcpcd.conf with the command

sudo nano /etc/dhcpcd.conf

at the bottom of the file enter the line

nohook wpa_supplicant

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


[Unit]
Description=Automatically generates an internet Hotspot when a valid ssid is not in range
After=multi-user.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/autohotspotN
[Install]
WantedBy=multi-user.target

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

 

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 an access point. If an ethernet cable that allows internet access is connect then the access point 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 your 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' )
mac=()

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

If you are using the linux firewall, firewalld then the ip tables in the script will cause issue but the required modifications are later in this guide.

 

 


#!/bin/bash
#version 0.97-N/HS-I

#You may share this script on the condition a reference to RaspberryConnect.com 
#must be included in copies or derivatives of this script. 

#Network Wifi & Hotspot with Network/Internet
#A script to switch between a wifi network and an Network/Internet routed Hotspot
#A 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
#http://www.raspberryconnect.com

wifidev="wlan0" #device name to use. Default is wlan0.
ethdev="eth0" #Ethernet port to use with IP tables
#use the command: iw dev ,to see wifi interface name 

IFSdef=$IFS
cnt=0
#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 }' | sed 's/\r//g'| awk 'BEGIN{ORS=","} {print}' | sed 's/\"/''/g' | sed 's/,$//')
IFS=","
ssids=($wpassid)
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' ) 
mac=()

ssidsmac=("${ssids[@]}" "${mac[@]}") #combines ssid and MAC for checking

createAdHocNetwork()
{
    echo "Autohotspot by RaspberryConnect.com"
    echo "Creating Hotspot"
    ip link set dev "$wifidev" down
    ip a add 192.168.50.5/24 brd + dev "$wifidev"
    ip link set dev "$wifidev" up
    dhcpcd -k "$wifidev" >/dev/null 2>&1
    if iptables 2>&1 | grep 'no command specified' ; then
    	iptables -t nat -A POSTROUTING -o "$ethdev" -j MASQUERADE
    	iptables -A FORWARD -i "$ethdev" -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
    	iptables -A FORWARD -i "$wifidev" -o "$ethdev" -j ACCEPT
    elif nft 2>&1 | grep 'no command specified' ; then
        nft add table inet ap
	nft add chain inet ap rthrough { type nat hook postrouting priority 0 \; policy accept \; }
	nft add rule inet ap rthrough oifname "$ethdev" masquerade
	nft add chain inet ap fward { type filter hook forward priority 0 \; policy accept \; }
	nft add rule inet ap fward iifname "$ethdev" oifname "$wifidev" ct state established,related accept
	nft add rule inet ap fward iifname "$wifidev" oifname "$ethdev" accept
    fi
    systemctl start dnsmasq
    systemctl start hostapd
    echo 1 > /proc/sys/net/ipv4/ip_forward
}

KillHotspot()
{
    echo "Autohotspot by RaspberryConnect.com"
    echo "Shutting Down Hotspot"
    ip link set dev "$wifidev" down
    systemctl stop hostapd
    systemctl stop dnsmasq
    if iptables 2>&1 | grep 'no command specified' ; then
        iptables -D FORWARD -i "$ethdev" -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
        iptables -D FORWARD -i "$wifidev" -o "$ethdev" -j ACCEPT
    elif nft 2>&1 | grep 'no command specified' ; then
        nft delete table inet ap
    fi
    echo 0 > /proc/sys/net/ipv4/ip_forward
    ip addr flush dev "$wifidev"
    ip link set dev "$wifidev" up
    dhcpcd  -n "$wifidev" >/dev/null 2>&1
}

ChkWifiUp()
{
	echo "Checking WiFi connection ok"
        sleep 20 #give time for connection to be completed to router
	if ! wpa_cli -i "$wifidev" 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 "$wifidev" >/dev/null 2>&1
	       createAdHocNetwork
	fi
}

chksys()
{
    #After some system updates hostapd gets masked using Raspbian Buster, and above. This checks and fixes  
    #the issue and also checks dnsmasq is ok so the hotspot can be generated.
    #Check Hostapd is unmasked and disabled
    if systemctl -all list-unit-files hostapd.service | grep "hostapd.service masked" >/dev/null 2>&1 ;then
	systemctl unmask hostapd.service >/dev/null 2>&1
    fi
    if systemctl -all list-unit-files hostapd.service | grep "hostapd.service enabled" >/dev/null 2>&1 ;then
	systemctl disable hostapd.service >/dev/null 2>&1
	systemctl stop hostapd >/dev/null 2>&1
    fi
    #Check dnsmasq is disabled
    if systemctl -all list-unit-files dnsmasq.service | grep "dnsmasq.service masked" >/dev/null 2>&1 ;then
	systemctl unmask dnsmasq >/dev/null 2>&1
    fi
    if systemctl -all list-unit-files dnsmasq.service | grep "dnsmasq.service enabled" >/dev/null 2>&1 ;then
	systemctl disable dnsmasq >/dev/null 2>&1
	systemctl stop dnsmasq >/dev/null 2>&1
    fi
}


FindSSID()
{
#Check to see what SSID's and MAC addresses are in range
ssidChk=('NoSSid')
i=0; j=0
until [ $i -eq 1 ] #wait for wifi if busy, usb wifi is slower.
do
        ssidreply=$((iw dev "$wifidev" scan ap-force | egrep "^BSS|SSID:") 2>&1) >/dev/null 2>&1 
        #echo "SSid's in range: " $ssidreply
	printf '%s\n' "${ssidreply[@]}"
        echo "Device Available Check try " $j
        if (($j >= 10)); then #if busy 10 times goto hotspot
                 echo "Device busy or unavailable 10 times, going to Hotspot"
                 ssidreply=""
                 i=1
	elif echo "$ssidreply" | grep "No such device (-19)" >/dev/null 2>&1; then
                echo "No Device Reported, try " $j
		NoDevice
        elif echo "$ssidreply" | grep "Network is down (-100)" >/dev/null 2>&1 ; then
                echo "Network Not available, trying again" $j
                j=$((j + 1))
                sleep 2
	elif echo "$ssidreply" | grep "Read-only file system (-30)" >/dev/null 2>&1 ; then
		echo "Temporary Read only file system, trying again"
		j=$((j + 1))
		sleep 2
	elif echo "$ssidreply" | grep "Invalid exchange (-52)" >/dev/null 2>&1 ; then
		echo "Temporary unavailable, trying again"
		j=$((j + 1))
		sleep 2
	elif echo "$ssidreply" | grep -v "resource busy (-16)"  >/dev/null 2>&1 ; then
               echo "Device Available, checking SSid Results"
		i=1
	else #see if device not busy in 2 seconds
                echo "Device unavailable checking again, try " $j
		j=$((j + 1))
		sleep 2
	fi
done

for ssid in "${ssidsmac[@]}"
do
     if (echo "$ssidreply" | grep -F -- "$ssid") >/dev/null 2>&1
     then
	      #Valid SSid found, passing to script
              echo "Valid SSID Detected, assesing Wifi status"
              ssidChk=$ssid
              return 0
      else
	      #No Network found, NoSSid issued"
              echo "No SSid found, assessing WiFi status"
              ssidChk='NoSSid'
     fi
done
}

NoDevice()
{
	#if no wifi device,ie usb wifi removed, activate wifi so when it is
	#reconnected wifi to a router will be available
	echo "No wifi device connected"
	wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
	exit 1
}

chksys
FindSSID

#Create Hotspot or connect to valid wifi networks
if [ "$ssidChk" != "NoSSid" ]
then
       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
              KillHotspot
              echo "Hotspot Deactivated, Bringing Wifi Up"
              wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
              ChkWifiUp
       elif { wpa_cli -i "$wifidev" status | grep 'ip_address'; } >/dev/null 2>&1
       then #Already connected
              echo "Wifi already connected to a network"
       else #ssid exists and no hotspot running connect to wifi network
              echo "Connecting to the WiFi Network"
              wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
              ChkWifiUp
       fi
else #ssid or MAC address not in range
       if systemctl status hostapd | grep "(running)" >/dev/null 2>&1
       then
              echo "Hostspot already active"
       elif { wpa_cli status | grep "$wifidev"; } >/dev/null 2>&1
       then
              echo "Cleaning wifi files and Activating Hotspot"
              wpa_cli terminate >/dev/null 2>&1
              ip addr flush "$wifidev"
              ip link set dev "$wifidev" down
              rm -r /var/run/wpa_supplicant >/dev/null 2>&1
              createAdHocNetwork
       else #"No SSID, activating Hotspot"
              createAdHocNetwork
       fi
fi



Testing the Hotspot

To test that the RPi is setup ok reboot the RPI. When the desktop returns you should have the wifi icon wif 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 access point works ok edit the ssid name of your router in the wpa_supplicant file.

enter

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

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

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={ ssid="mySSID1" psk="myPassword" key_mgmt=WPA-PSK }

change to

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={ ssid="mySSID1off" psk="myPassword" key_mgmt=WPA-PSK }

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 a red cross networkdown This means it is an access point, it could also mean your network is down but other devices should detect the hotspot. 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

rpiHotspot android

 

If you find this guide useful and wish to show your appreciation then you are welcome to make a donation or share a link to this article. There is no obligation to do so, this guide is free for use and support is available to everybody as long as I know the answer :)

I am the single developer of this script and website. Any support towards the costs are welcome.

RaspberryConnect.com

 

Local wifi signals in range on Android

For SSH and VNC the connection ip is 192.168.50.5 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 192.168.50.5::5900

If you now connect an ethernet cable to the Raspbery Pi and your router and wait a few seconds the access point 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 an access point and then when you get back in range it will deactivate the access point 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.

Note on Permissions:

by default the pi user does not need to enter a password to use the sudo command. If you are not using the default pi user and while doing this guide you have had to enter a password every time sudo is needed then you will find the the cron job will not work as it wont have permission to run the autohotspotN script.

To fix this you can give the user permission to run the script without a password.
Enter the command

sudo visudo

enter your password
at the bottom of the file add the following line, where username is the user that will be using the script:

username ALL= NOPASSWD: /usr/bin/autohotspotN

Now you will be able to run the script with sudo with the cron.

Thanks to Jim for pointing this out as an issue for some users.

 

If you are not using the default PI user and you are still have issues then check your default Paths from CRON for your user. It will need /sbin/ for iw.

Adding the path line to the cron will tell it were to look, PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Thanks to Atanas Atanasov for highligting this for non PI users

 

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

 

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
net.ipv4.ip_forward=1

and add a # as follows

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

In the /etc/dhcpcd.conf file remove the line that was added

nohook wpa_supplicant

If you had previous config in your /etc/network/interfaces file and made a backup you can restore your original interfaces file with the command

sudo mv /etc/network/interfaces-backup /etc/network/interfaces

Then reboot

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

 Trouble Shooting

  • If you get no wifi connection or no hotspot then 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 an access point. 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 access point 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 access point has failed try, sudo systemctl status -l hostapd
  • You need to add a new wifi network to the RPi but it is in access point 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. If your router has a hidden SSID/not Broadcast then include the line;  scan_ssid=1
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB

network={ ssid="mySSID1" psk="myPassword" key_mgmt=WPA-PSK }

 

Change Log: here

 

 


Add comment

Comments  
Wrong password error after some time of inactivity
Hi Roboberry,

Thank you for your tutorial, I followed it (only one part : just booting with access point, and ethernet connection when available, or either standalone, no switch). My aim was to use an android smartphone as a web client to give remote commands to a web server on a Raspberry PI 4B.

It works great, the Raspberry settles access point and web server on boot, the phone connects to wifi access point with password (which is then stored) and communication with server runs well.

The only problem is that if there is no request from client for some time (a few minutes), the wifi connection stops, and then the phone cannot connect anymore to the wifi access point, it only gets "wrong password" message, even after several attempts.

So it makes it necessary to reboot after any short inactivity.

Would you have an idea how it can get solved ?
Wrong password error after some time of inactivity
Hi Pangolin Thanks for your comment, Did you use the installer script as this is just the switching guide. Either way the result will be the same. My first thought is the pi is going into power save mode on the wifi, so you loose the signal. This can be checked with sudo iw wlan0 get power_save You can disable it with sudo iw wlan0 set power_save off but this must be set everytime the Pi boots up you can put the command in the cron with crontab -e @reboot /usr/sbin/iw wlan0 set power_save off this is untested. If the wifi has gone idle, then getting it to just do something on wifi such a ping and address will keep it up which should keep the signal live. Though I can't say I have had this issue. Another thing to consider is if the Pi is drawing too much power for usb devices or gpio hats etc then one of the first things to be affected is wifi stability. hopefully this will help.
Bookworm
Hi Tyler No I don't have a version available yet as I need to do further checks on the installer. It's pretty much finished, I will be working on it over the weekend. So if all goes to plan I hope to have the initial version up next week. Thanks for your interest, I will send you a message when it's ready.
Bookworm
Hi Tyler Just to let you know the bookworm version of the Autohotspot script is now available on the homepage.
Bookworm
Hi Roboberry,
I have used this script in the past however now moving to bookworm.
I don't suppose you have a link for your bookworm beta code that I can have a play with?
Ethernet Bridge Functionality
Hi Roboberry,
Great tutorial! I'd like to combine this functionality with 'WiFi-to-Ethernet' Bridging when the Pi is acting as a WiFi client. Is this already built in to your steps, or will I have to perform additional steps for the Pi to forward all of it's incoming WiFi traffic to an Ethernet Client? Ideal behavior would be:
1) Hotspot, Pi is available to be connected to.
2) Client, passes WiFi data to Ethernet port and acts as a bridge.
Ethernet Bridge Functionality
Hi cdubs1495

Thank you. This is not setup as a bridge which will require a different configuration and for the script to activate and deactivate the bridge during any switching.
But it does do what you describe using ip forwarding and NF tables while the Access Point is available.

If ethernet is connected to eth0 any device connected to the Pi's Access Point can ping devices on the ethernet network or the internet if it is available through the ethernet port.
Unlike a Bridge, no device on the ethernet network can ping the devices on the Pi's Access point. They can only ping the pi itself via its eth0 Ip address.

All devices on the Pi's access point can ping each other and the Pi.

Hopefully that helps, let me know if you need more info.
Reply
Ah ok that makes sense! If the Pi is acting as a WiFi client and I plug a device into the Ethernet port, will it be able to connect to the internet? Sounds like yes from your comments
Reply
I might be reading your comment wrong, if you mean will the ethernet device get internet from the Pi's wifi connected to a internet wifi network then no it won't.

When the Pi is connected to a known Wifi network with internet then it functions as the Pi normally does, so a connected ethernet device won't get internet via the Wifi Network.

When the Pi generates a wifi access point, this setup expects that the ethernet connection will supply the internet to the Pi which then allows device connected to the Pi's wifi access point to use the internet via the Ethernet source.

hopefully that helps :)
developer extrordinare
Hi - is there a way i can run a script to automatically switch over to hotspot mode? I'm looking at AutohotspotN and not seeing an obvious way to do it...
developer extrordinare
Hi David

There is no function in the autohotspotN script to switch to a hotspot while a valid wifi network is in range.

There is an installer script on the home page as well. If you install that and just run option 6 it will force your setup over to an hotspot. Then if you run it again or run sudo /usr/bin/autohotspotN it will reconnect to a wifi network again.

Option 6 is a separate script that doesn't check network status so just blindly sets up the access point.

your other option is to write a script that replaces /etc/wpa_supplicant/wpa_supplicant.conf with an empty one or that can change your SSID entry to an invalid one.
Putting # infront of the ssid line won't stop the autohotspotN script readings the SSID to check.
Then run sudo /usr/bin/autohotspotN
Your wifi network then won't be found so the script will switch over to a hotspot.

hopefully one of these options is suitable for you.
hotspot script
I made 2 copies of your installer script and deleted everything but the parts of option 6 that either set the hotspot or wifi. So i now have 2 scripts - one that forces hotspot mode and one that forces wifi. Works great!

Been using your installer script for a few months and its been a great utility. Nice job with i!
hotspot script
Hi David

The cutdown script is a good option for those who know what to do. I did have that setup a while back but now it's hiding from me on one of my numerous memory sticks.
You can just use the one that creates the hotspot as running the autohotspotN script will connect the Pi to the router as well.

Glad to hear you find it useful. Thanks
Open VPN
How would I go about establishing an OPENVPN tunnel over the WiFi connection that would place anything connecting to ETH0 port to the VPN?
Open VPN
Hi Kevin

I have used open VPN with this setup. It was a while back and as far as I remember it just worked without any changes. The Pi was as an Access Point and connected to my router via Ethernet and openvpn was active.
If you do have any issues then you can change the autohotspotN script to use tun0 instead of eth0.
Check what device OpenVPN has created other than Lo, Wlan0 & Eth0 with the command 'ip a'

then in the top part of the script at /usr/bin/autohotspotN

wifidev="wlan0" #device name to use. Default is wlan0.
ethdev="eth0" #Ethernet port to use with IP tables
#use the command: iw dev ,to see wifi interface name

change
ethdev="eth0"
to what device the VPN is using, ie
ethdev="tun0"

The access point will then use tun0 instead of eth0 for all future routing.

Hopefully that helps.
Launching Wordpress
Hi there, I am going to attempt to use this to test a MVP on a pi, where logging into an ssid with no internet will, launch a wordpress page, or a captive portal before running the application being created. It is intended to be an intranet to an application with a pi and router. This is the first helpful thing I have seen in about 9 tries.
Launching Wordpress
Hi Daryl

Thanks for the feedback. There is a lot of outdated info out there making these things hard work. I'm glad you have found it useful for your project.
The wordpress page will be on the access points ip address in a browser. If you need a hostname instead add the ip
and hostname to /etc/hosts. When the Pi is connected to a router it will use the Pi's usual hostname.

good luck with your project.
Stop Hotspot
Hi there, thanks a lot for your script, it works flawlessly on my raspberry pi 4 running kali Linux. I have just one question.
How can I modify the script so it doesn't start hotspot if the LAN cable is connected?
Disable hotspot
Hi Tanatos

I haven't used it on Kali but good to know it works.
This is not something I have done but If you write some bash code to check if eth0 is connected by checking the status in /sys/class/net/eth0/ or any other suitable method

then add a if statement within the function createAdHocNetwork()

createAdHocNetwork()
{
check eth0 connected code
if eth0 is not connected, then;
echo "Creating Hotspot"
ip link set dev "$wifidev" down
ip a add 192.168.50.5/24 brd + dev "$wifidev"
ip link set dev "$wifidev" up
etc etc
fi
}


then even when the hotspot should be activated it will only be created if the eth0 is not connected.

Hope this helps.
Disable hotspot
Thanks a lot for your help, here is the code if anyone else needs to do the same thing as me, the following code works fine when you power up the raspberry pi with LAN cable connected, but it will need some more tweaking to make it work when you connect the cable while Pi is running.

createAdHocNetwork()
{
if [ $( cat /sys/class/net/eth0/carrier ) -eq 0 ]; then
echo "Creating Hotspot"
ip link set dev "$wifidev" down
ip a add 192.168.50.5/24 brd + dev "$wifidev"
ip link set dev "$wifidev" up
dhcpcd -k "$wifidev" >/dev/null 2>&1
iptables -t nat -A POSTROUTING -o "$ethdev" -j MASQUERADE
iptables -A FORWARD -i "$ethdev" -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i "$wifidev" -o "$ethdev" -j ACCEPT
systemctl start dnsmasq
systemctl start hostapd
echo 1 > /proc/sys/net/ipv4/ip_forward
fi
}
Disable Hotspot
Thanks for sharing
Hi roboberry

I upgraded latest changes to raspbian. In /etc/default/hostapd there is following warning. Do you have idea where DAEMON_CONF="/etc/hostapd/hostapd.conf" should now be put, or is it still needed?

# Defaults for hostapd initscript
#
# WARNING: The DAEMON_CONF setting has been deprecated and will be removed
# in future package releases.
Hi Eero

For Rasbian/PI OS - Buster, the file /etc/default/hostapd is no longer needed as the default location for the config file is /etc/hostapd/hostapd.conf
It is kept in the guide for compatibility with Stretch.

You can delete or rename /etc/default/hostapd in Buster and hostapd will still work, but it doesn't cause an issue if it does exist.
hi your script is fantastic! can i add in my raspberry version?
Thanks Andrea, let me know what your "raspberry version" is and I will take a look.
Hi,
Congratulations for this fantastic job.
I have configured a Pi zero ethernet/USB extender and use Permanent Hotspot.Hotspot is configured on wlan0 and I have an other USB wifi connected as client to wireless network (wlan1). How can I do for switching internet access from eth0 to wlan1. I have tried bonding but it does not work....thanks for your help. Best regards
Hi Montilien

Thank you.
This guide is for the autohotspot which currently can't use wlan1 network connection, only eth0.
If you are using the Permanent Hotspot setup from my other guide then:

To switch eth0 over to wlan1 on a permanent hotspot you need to make changes in
/etc/dhcpcd.conf
from
#Static Hotspot
nohook wpa_supplicant
interface wlan0
static ip_address=192.168.50.10/24
static routers=192.168.50.1
static domain_name_servers=8.8.8.8

to
interface wlan0
nohook wpa_supplicant
static ip_address=192.168.50.10/24
static routers=192.168.50.1
static domain_name_servers=8.8.8.8

then in /etc/iptables-hs
from
#!/bin/bash
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

to
#!/bin/bash
iptables -t nat -A POSTROUTING -o wlan1 -j MASQUERADE
iptables -A FORWARD -i wlan1 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i wlan0 -o wlan1 -j ACCEPT

if you still have an issue you may need to delete a default route if "route" shows two default routes

route del default gw 192.168.50.1

let me know if this works for you.
@roboberry I have tried your script twice on my pi zero w and both times it has rendered the network interface inoperable and does not put out a hotspot, so my pi zero is dead in the water without internet. Can you please advise? I'm new to linux..., But I appreciate any help. This will be the third time I will have to wipe my pi bc this script did now work out :/
Hi Logan

Sorry to hear you are having a issues.
I'm guessing as you have done the guide twice you have checked all steps are complete.

If you can't see the RPiHotspotN on other wifi devices then it is most likely hostapd has failed. This usually is caused by the password in /etc/hostapd/hostapd.conf being less than 8 characters, if it has been changed.
The other reason is if /etc/hostapd/hostapd.conf file name & location is different than what is written in /etc/default/hostapd

Other causes can be if the script /usr/bin/autohotspotN is not executable. recheck by entering sudo chmod +x /usr/bin/autohotspotN

if the first line of the script at /usr/bin/autohotspotN is missing it also won't work
#!/bin/bash

Other issues can be caused if the text files for the config files and the autohotspotN script have been saved in Windows before being moved to the Pi, this can cause the script not to run.

The easiest option is to use the installer script. It can be found on the home page and the top of this article. It does all the checks required and will set up the autohotspotN script as in the guide.

If you have any further issues please let me know.
I got this error "systemd "status=203/EXEC"" and I wanted to share the solution I found thanks to user "dwrz" from Stackoverflow (https://stackoverflow.com/questions/45776003/fixing-a-systemd-service-203-exec-failure-no-such-file-or-directory)

In /etc/systemd/system/autohotspot.service add "/bin/bash" before the path to the script.

Sp first:

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

and change

"ExecStart=/usr/bin/autohotspotN"

to

"ExecStart=/bin/bash /usr/bin/autohotspotN"
Hi Marinus

There are a couple of reasons you may get this error.
The first is that the line #!/bin/bash is missing from the first line of the /usr/bin/autohotspotN. This would mean PI OS wouldn't know how to run the script. By adding it to the service it is being told how to run the script. If this is the case just add the line back into the autohotspotN script and you can take the mod out of the service.

The other reason you can get a 203-exec-failure is the autohotspotN script is not executable. If you enter ls -g /usr/bin/autohotspotN
it should return
-rwxr-xr-x 1 root /usr/bin/autohotspotN
If there are no x's then its not executable. enter
sudo chmod +x /usr/bin/autohotspotN
to make it executable.


Let me know if this solves the issue, if not I would like to understand what is different about your system to cause this. This has been in place for several years and not had this issue, other than the reasons above. Thanks
I have an SSID and Pwd that has a special character in it. I have tried to convert the data to hex but am still having trouble connecting to the internet.
this is my wpa_supplicant.conf file. I have tried both the hex and string version with no success:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB

network={
#ssid="Bob's iPhone"
ssid=426F622773204970686F6E650A
psk="Password"
scan_ssid=1
key_mgmt=WPA-PSK
}
How can I modify the script to work for SSID and PSK that is entered in as hex. For instance ssid="Bob's iPhone" does not work and the hex version ssid=426F622773206950686F6E650A
does now work either
Hi Slim

Your ssid should work ok, it will fail if there is a comma in the ssid. I did a check and the script returned ok for your ssid, but fails if you replace the space with a comma.
"Checking: Bob's Iphone
No SSid found, assessing WiFi status
Checking: Bobs's
No SSid found, assessing WiFi status
Checking: Iphone
No SSid found, assessing WiFi status"

I have not used a hex ssid with this but it will only check it if it is within quotes otherwise it is just skipped. ssid="426F622773204970686F6E650A"

If your wpa_supplicant.conf was created on Windows there may be additional characters causing issues though the script can handle the usual LF CR characters issues.

You can use the mac address of the phone and put it in /usr/bin/autohotspotN near the top is the entry

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

putting the mac address in the brackets will cause it to be checked along with any references in wpa_supplicant. This also need scan_ssid=1 in the wpa_supplicant entry as you have.

Have you or are you able to check it with a different ssid just to confirm all is working ok otherwise?

Let me know if this doesn't help and I will look into it further.
First, I want to express my gratitude for this instruction, it helped me a lot.
Tell me how you can implement the functionality for Internet sharing via the Ethernet connector when there is access?
Moreover, when the Internet is not available, this is not necessary.
Hi JetBaget

I'm glad it's helped you.
The internet will be available via Ethernet when it is connected for both Hotspot and Network connections with this setup.
Could you give me more details on what the issue please?
The problem is that I have a device that I want to connect via Ethernet to the raspberry. This device has a static IP address. I found one script that creates a bridge between Wifi and Ethernet, but when the Internet turns off and the hotspot rises, everything breaks down and it becomes impossible to connect to the raspberry via SSH.

I would like to be able to raise the hotspot without rebooting the raspberry, while when the Internet appears, it should be accessible via the Internet for other devices.
Hi JetBaget

The Eth0 side of things are unchanged from the script, this is always controlled through dhcpcd.
The only change would be ip forwarding, in sudo nano /etc/sysctl.conf it is off during Network connection and on during the hotspot activation. This allows communication to outside connected networks. I don't think this is your issue.

The Ip tables within the autohotspot script also setup and disable routing between the eth0 and wlan0 this may be conflicting with your bridge setup. If you are bridging from wlan0 to eth0 then then there may be a loop.

When I switch between network & Hotspot and eth0 is connected to my router the IP address does not change and default routing stays with eth0.

I would look at any changes to your default route when the autohotspot switches to the wifi network. It maybe that your default route is switching between eth0 and the bridge causing an issue.
use the command "route"
and check for the default Destination.

Try the setup without the bridge and see what happens.

Also check you ip tables chain between network and hotspot to see what changes there are. There will only be rules from the autohotspot script during the hotspot

sudo iptables -S (thats a capital S)
Hi Roboberry, thanks for this very useful project. I have used your script on buster (option 1) and it seems that everything went smoothly. However, I experience strange behavior when I use the Pi as a hotspot. If I use an IPhone XS to test the connection everything seems to work but if I try to connect with Android the phone connects but the ip forwarding does not work and returning to use the Iphone gives me a message of "wrong password". Then I have to reboot and the system works again at least with the Iphone.
The other two modes work finely.
Sorry for the non-technical description but this is what I can report at this stage about this issue. I trust that with your help I can get more helpful information.
regards
Hi Gianni

Your welcome. That seems a bit odd, if it works on a device it should work on them all as the password doesn't change. The wifi password is set /etc/hostapd/hostapd.conf and also option7 so as long as it is 8 characters or more it should be fine.

Have you tried connecting to the Pi with VNC or SSH from a phone? Android will need mobile data switched off if you try ssh, due to permissions on android.

I haven't had any issues using he script, yet, but I will run it through a few other wifi devices and see if something pops up.

Thanks
Hi Roboberry, thank you for this super project!
I'm running strech on RPi3 an do the installation. After this Raspi can`t find WLAN any more. Only when I connect ethernet my home network is possible. -journalctl -xe
...Unit hostapd.service has failed
...hostapd[1902]:Configuration file:/etc/hostapd/hostapd.conf
...hostapd[1902]:Line 8:unknown configuration item'macadrr_acl'
...hostapd[1902]:Failed to set up interface with /etc/hostapd/hostapd.conf
...hostapd[1902]:Failed to initialize interface
...systemd[1]:hostapd.service:Control process exited, code=exited status=1
...systemd[1]:Failed to start Advanced IEEE802.11 AP and IEEE 802.1X/WPA/WPA2/ EAP Authenticator (this line colored in red)

sudo[1904]:pi:TTY=pts/0;PWD=/home/pi; USER=root;COMMAND=/bin/journalctl-xe

I hope you can help me
thanks Frank
Hi Frank, you're welcome.
The error seems to find an issue with the /etc/hostapd/hostapd.conf file which may not be complete. Can you check that line 8, macaddr_acl=0
is complete.

If it still has an issue and if you copied the code from the webpage, try downloading the text file in the download here link just above that section in the guide and pasting that into the config file.

If no luck let me know and we can look into it further
Hi Frank

The error is to do with VNC rather than the hotspot setup. The ip it is trying to connect to looks to be your router? If the pi is in hotspot mode then vnc needs to use 10.0.0.5.

Could you give me some more info about what issue you are having please. Is the Pi connected to your router or is it as a hotspot? Are you seeing the hotspots ssid on other devices, RPiHotspotN?
If it's the hotspot are other devices able to connect to it.

If you are not able to get the hotspot to work with ssh or vnc or unable to see the hotspot ssid you can try the intsaller script. There is a link to the article at the top of this page or at the bottom of the homepage.

This will install the autohotspot setup for you, it does work fine on stretch .
Hi roboberry,
thanks a lot for the fast support! With your help I did the correction "...macaddr…" but by my life ;-) thats not all, ...journal -xeI've got the next trouble...

Mai 09 18:57:03 raspberrypi kernel: random: 7 urandom warning(s) missed due to ratelimiting
Mai 09 18:57:03 raspberrypi vncserver-x11[457]: ServerManager: Server started
Mai 09 18:57:03 raspberrypi vncserver-x11[457]: ConsoleDisplay: Found running X server (pid=491, binary=/usr/lib/xorg/Xorg)
Mai 09 18:57:08 raspberrypi vncserver-x11[457]: Connections: connected: 192.168.2.113::63002 (TCP)
Mai 09 18:57:16 raspberrypi vncserver-x11[457]: session started: user pi permissions f
Mai 09 18:57:16 raspberrypi vncserver-x11[457]: Connections: authenticated: 192.168.2.113::63002 (TCP), as pi (f permissions)
Mai 09 18:57:16 raspberrypi vncserver-x11[457]: SPrintConnMgr: Failed to add printer: server-error-service-unavailable
Mai 09 18:57:22 raspberrypi kernel: w1_master_driver w1_bus_master1: Attaching one wire slave 00.c00000000000 crc ca
Mai 09 18:57:22 raspberrypi kernel: w1_master_driver w1_bus_master1: Family 0 for 00.c00000000000.ca is not registered.
Mai 09 18:58:01 raspberrypi sudo[1537]: pi : TTY=pts/0 ; PWD=/home/pi ; USER=root ; COMMAND=/bin/journalctl -xe
Mai 09 18:58:01 raspberrypi sudo[1537]: pam_unix(sudo:session): session opened for user root by (uid=0)
so i hope you can help me again
best regards Frank
I am having a problem with the autohotspotN script I just double checked what I put on my machine to what is on this page...and it doesn't like the following syntax

-- Line 24 "(" unexpected
-- Line 35 "(" unexpected
-- line 37 "(" unexpected
-- Line 84 "(" unexpected ( expecting "}")
-- Line 182 Missing '))'

Line 24 is -- ssids=($wpassid)
35 is -- mac=()
37 is -- ssidsmac=(
84 is -- ssidChk=('NoSSid')
and 182 is the end of the file.

Obviously I had to change each error to get to the next error...I removed the () at line 24...I commended out Line 35 and 37 since I am not working with hidden SSIDs I removed the () at line 84...so maybe I induced errors...but line 24 stops the whole show anyway.
Hi Mike

It looks like you have a bad copy and paste. If you have saved any files on a Windows machine then there will be extra characters not used in linux which will cause this type of error.
There is a download link to the text file just above the script in the guide, try downloading that and saving that to the Pi into the /usr/bin folder. Then make it executable with
sudo chmod +x /usr/bin/autohotspotN

There will be no need to delete or modify any of the lines to make it work.

this should solve the issue. let me know otherwise.
Hi Mike

Bash scripts are a bit more sensitive to that type of thing. Config files and programs are usually more forgiving. Hopefully it's not too life changing :)
Well color me baffled...You of course were correct...but I use notebook++ for all this type thing...I have never had this kind of drama... So for the record..on the Pi, I opened the Pi browser...right clicked on the link...saved it...went through a bit of nano foolery and it worked... I may have to rethink my entire life.. Thanks!
Hi Roboberry. Thanks for this, it's very useful.
I made the classic mistake of using a Windows text editor to knock up a wpa_supplicant file to place in the boot directory to get a Zero running headlessly. Of course, the editor placed CrLf at the end of each line rather than the just the Lf expected in Linux systems. Interestingly, WiFi worked as normal. The autohotspotN script however broke. I’m sure if I removed the Cr from wpa_supplicant.conf, it would work fine, but maybe it’s better to patch the script to cope with it.
I added these 2 lines:

#trim trailing line-feeds (particularly the \r\n pattern used by Windows)
wpassid=$(echo "${wpassid//[$'\r\n ']}")

immediately after the line where “wpassid” is initially set (by scrapping wpa_supplicant.conf).
Regards, John.
Hi JohnC

That's a good consideration. Though i'm actually surprised that in the years this script has been available nobody else has highlighted it as an issue. Though they probably either give up thinking it doesn't work or fix the file. I'm currently working on some updates so I will add that one to the list. Thanks
Hi Roboberry, thanks for your great work. I am having the same issue as Jason: my experience with RPi 2B with WiPi dongle running Buster:
Changed /etc/dnsmasq.conf dhcp-range
from
dhcp-range=192.168.50.150,192.168.50.200,255.255.255.0,12h
to
dhcp-range=192.168.4.150,192.168.4.200,255.255.255.0,12h

Changed /user/bin/autohotspotN script IP address from 192.168.50.5 to 192.168.4.1

After boot network indicator shows two blue arrows and hovering over this gives:
eth0: Link is down
wlan0: Associated with
wlan0:Configured 169.254.169.190/16

Hotpoint is running and I can connect to it with my laptop and SSH to IP address 169.254.169.190

hostname -I gives 169.254.169.190

If I then execute the following:
sudo systemctl stop hostapd
sudo /usr/bin/autohotspotN

Output is
SSid's in range: BSS 20:0c:c8:1e:27:87(on wlan0) SSID: NETGEAR95_2GEXT BSS 20:0c:c8:3c:3f:01(on wlan0) SSID: NETGEAR95
Device Available Check try 0
Device Available, checking SSid Results
No SSid found, assessing WiFi status
No SSid found, assessing WiFi status
Creating Hotspot
Network indicator now shows two red crosses and hovering over this gives
eth0: Link is down
wlan0: STOPPED

hostname -I gives 192.168.4.1

Hotpoint is running and I can connect to it with my laptop and SSH to IP address 192.168.4.1

So I put these two above commands in a script run by /etc/rc.local which gets around the problem.

Everything else works fine. Hope some clues here. Purge and re-install of dnsmasq makes no difference.
Hi dickcool
Thanks. The ip 169.254.169.# is a backup ip because dnsmasq has been unable to determine the pi's ip. The issue is because the ip you have set in autohotspotN end in .1 This is effectively the routers ip. If you change the autohotspotN script from 192.168.4.1 to 192.168.4.2 or higher but below what the range is in dnsmasq.conf and it should work again.
Hi,
I have rebuilt Pi4 from scratch with Buster and installed your script. Unfortunately can't see the RPihotspotN as an access point (Wifi icon is the double red cross). Passphrase is >8 characters. And I tried switching to channel 11 (from 8). Have rechecked the scripts and made sure script is executable and service enabled. wlan0 has ip of 192.168.50.5. Appreciate if you have any ideas ...
If I run hostapd manually there are some error type references but not sure what to make of it. I’ll try sending you the whole output by email but includes things like:
Failed to set TX queue parameters for queue 1.
And
Failed to clear default encryption keys
I just got it working on my RPi 3B+. Thanks for your detailed instructions! I am using the RPi to run a software synth and MID hub. I was already able to ssh into it on my home network, but my work network (a school district) does not allow ssh connections without special privileges. Now, I can configure the RPi from my other laptop, at work.

I am not a computer expert, and maybe I missed something, but is there a way to more easily switch between a regular wifi network connection and the hotspot...even when there is a wifi network present...without having to modify the wpa_supplicant file and restarting?

Thanks, again!
Hi Bill

I'ts good to hear you find it useful. There is no easy way to switch to hotspot when a know network is available as that is out of scope of the script. The cron timer feature is the simplest way if you were moving between a know network and no network.

To just switch to the hotspot while you are in range of a know network would require a modified script, which i'm happy to do for you. This would be a cutdown version and would happily work along side the current setup.

When run it would just force the hotspot activation. Then when you want to go back to the network, run the normal script and it would switch back. You can configure gpio buttons to run the scripts to easily switch as well.

If this sounds of use I can supply a modified script which you can run manually from the terminal via ssh to do the switch.
Thanks for the quick reply, roboberry. I tried the hotspot at work today for the first time, and it worked exactly as expected. I appreciate your offer to provide an extra script, but I will first spend more time playing around with the setup as-is...to determine if the change I asked about is that useful. On a side note, my school district just called a shutdown for the next three weeks, so I won't be using the hotspot at school any time soon. Best wishes!
Hi,
Great concept and just what I'm looking for (mobile headless unit).

But I am having a problem where entries in the wpa_supplicant file are being marked as disabled (line being added to each section: "disabled=1"). Eventually only way to connect is the hotspot. Not sure what triggers this or if it is an issue with your script or with Pi/Buster in general. Using latest Buster with a Pi4.
Hi Dave

I can't say I have come across that issue. The script doesn't change wpa_supplicant, it just reads the ssid= line and looks for match in the iw command for available ssids being broadcast.

If the ssid is found then there is no change to the wifi setup. To switch back from the hotspot wpa_supplicant it just enabled as it would be without the script on a normal boot. so any changes to your config file will be generated by wpa_supplicant i presume.

Had a quick look online and there is a suggestion that it can be caused by wpa_supplicant process if the line "key_mgmt=WPA-PSK" with the SSID and Password.

Was your wpa_supplicant.conf created by the system or manually and put in the boot folder?

If it was manually then check the config lines are at the top of the file with the correct country code. There is an example just above these comments in the trouble shoot section. The country missing can cause issues about not being able to connect.

If you can't find a solution and you feel it's the setup then i'm happy to investigate further and try to reproduce the issue.
Thanks for the detailed reply!

Pretty sure the wpa_supplicant file was autogenerated (but I had to update the country code manually).

So looks like this is an underlying Pi4/Buster issue. Do you still have the link to the "key_mgmt=WPA-PSK" with the SSID issue you found?

Thanks,
Dave
Hi Dave

Wpa_supplicant should get the country from your locales setup. I'm not sure about the headerless setup but when you do a desktop install in Buster, you set the locals and Wfi Country during the initial setup. But you can do it in raspi-config on the cmd line and it will set the country.

I done a search for "wpa_supplicant disabled=1"
and looked at
https://unix.stackexchange.com/questions/463741/wpa-supplicant-says-network-is-disabled

I'm working on updates and a installer at the moment on Buster so I will also test with alternate wpa_supplicant.conf setups. Thanks
I wrote an installer for your hotspot script some time back. Feel free to use any of it you wish. Your autohotspot is the best thing I have found that is super simple and just works. My installer does make some mods to the ip addr and ip range. https://github.com/km4ack/pi-scripts/blob/master/autohotspot-buster
Hi Jason,

Thanks, glad you found the script useful. I will take a look at your installer, thanks.
My one is nearly finished. I have decided to put all 3 setups in one installer. Now Buster uses NF tables instead of IP tables it just makes more sense to manage all the quirks in an installer rather than make the guides too complex.
Hi Dominic. I'm glad you like the article. Unfortunately there is a lot of old articles online that no longer work as things have moved on.
It seems you have an issue. The ip address 192.168.50.5 is set by the autohotspot script when it goes to hotspot mode. So it should't be possible to see it when you go back to network mode as dnsmasq gets shutdown. If both the hotspot and network are active through config issues then Network will always override the hotspot. In network mode the ip will be what the router issues. Is this the only IP you have for wlan0?

I'm not able to replicate your issue, usually if dnsmasq is started at boot you will get a 192.169 ip but not the hotspot one.

Do you get this at boot if it goes straight to network mode?
or does it happen after it has been switched from hotspot to network mode manually or with the cron timer?

Also things to check; while in network mode is dnsmasq running.
sudo systemctl status dnsmasq
see if there is lots of text looking describing it starting ip. should also say "Running"

also do the same for hostapd

if either are running then just disable them again.
sudo systemctl disable dnsmasq

hopefully we can find the issue.

That's kind of you to offer a donation.
There is a donation button in the article by the "Settig up a Timer" section.
Hi, first off I'd like to thank you for this. I've just gotten my first rasperry pi(running rasberian buster) 4 and am working on a project which is going well. Your script was just something extra to add some bells and whistles. I can say as a newbee it is working great and was easy to follow your instructions. most other attempts i did from other instructables did not work for me. I have one questions.. when defined ssid is located it connects fine but the pi doesn't seem to have internet connectivity. The reason i believe is the static ip of 192.168.50.5 is there.(by checking ifconfig) I'm assuming on connect to configured ssid the pi should then receive an ip from the connection (my home network) and assigned it the proper ip for my home network to function this way. but it seems to stay at 192.168.50.5. is this how its designed or do i have a problem. Please provide donation info as you have saved my probably days of research trying to make this happen on my own. Thanks!
Quoting Dominic:
Hi, first off I'd like to thank you for this. I've just gotten my first rasperry pi(running rasberian buster) 4 and am working on a project which is going well. Your script was just something extra to add some bells and whistles. I can say as a newbee it is working great and was easy to follow your instructions. most other attempts i did from other instructables did not work for me. I have one questions.. when defined ssid is located it connects fine but the pi doesn't seem to have internet connectivity. The reason i believe is the static ip of 192.168.50.5 is there.(by checking ifconfig) I'm assuming on connect to configured ssid the pi should then receive an ip from the connection (my home network) and assigned it the proper ip for my home network to function this way. but it seems to stay at 192.168.50.5. is this how its designed or do i have a problem. Please provide donation info as you have saved my probably days of research trying to make this happen on my own. Thanks!


Ok..problem solved..there was a static configuration in the dhcpcd.conf i commented out and it resolved all the issues!
That's good you have it sorted now. Have fun with your Pi project.
Hi, I do not have access to a LAN port. I want to try configuring the pi as access point but presently, I must connect the pi to wifi rather than over LAN to the modem. Is this possible ? Can I get instructions ?
Hi Bhawandeep Singh.
It is possible but you will need to do it with a permanent hotspot rather than the Autohotspot that this article is for.
This requires 2 wifi connections , so a Pi3 or Pi4 will also need a USB Wifi dongle.

Can you let me know what Pi you are using and if it has 2 wifi sources.

I will then let you know what to change in my Static Hotspot article to make it work.

https://www.raspberryconnect.com/projects/65-raspberrypi-hotspot-accesspoints/168-raspberry-pi-hotspot-access-point-dhcpcd-method

If you email me then I can send you the details. admin@ this site.
Thank you so much! I just did a donation of 20 pound.
I'm running apache on RPi3 and I'd like to address the raspi with a name instead of IP-Address http://192.168.50.5/myhttpSite . 192.168.50.5 = ras101 as name. I want http://ras101/myhttpSite to address the site. Where can I configure that?
Hello Eckard

Thank you for your generous donation, much appreciated.

The hostname for the hotspot can be configured in /etc/hosts

at the bottom of the file, add the hotspot ip and the host name.

127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

127.0.1.1 Buster16
192.168.50.5 ras101

This will mean when the pi has the hotspot 192.168.50.5 you should be able to use http://ras101/mysite after a reboot.
In this example when the pi goes back indoors and into network mode the host name is Buster16. Which probably isn't what you need.
so change 127.0.1.1 to ras101 as well.
This is the bit that gets changed when you update the Hostname in preferences:Raspberry Pi Configuration: Hostname option on the Desktop.
I created something similar to this. It is very simple and stable. It makes only use of systemd, wpa_supplicant und wpa_cli. So there is no need to install additional software on raspbian.

You might find it worth a look:

https://raspberrypi.stackexchange.com/questions/100195
https://github.com/0unknwn/auto-hotspot

It's open source, so feel free to use it in any regard you like!
Hi, I solved the issues and now the procedure works, BUT it is very very slow: in order to define whether to conneted to a known SSID or activate Access Point when switchs on, RPi takes about 2-3mins to defice.... is there any way to speed it up?

thanks
Hi Antonio
Glad you have it working. Is it taking that long to go to both Network and Hotspot modes?

Once it has started, if you run it manually is it quicker?

The flow is the script waits for the network devices to be available before running. It will setup network quickly and make it available but then wait 20 seconds before checking everything is working, during this time wifi is available to use. If wifi has not been given an IP by the router within 20 seconds it will go to the hotspot.

If there are issues with the network wlan0 device is available but not ready the script will wait
for 2 seconds per error up to 20 seconds before defaulting to a hotspot.

sudo systemctl status autohotspot should highlight if there has be device errors.

You can use the command
systemd-analyze time

To analyse your boot up processes. The autohotspot service should take about 21 seconds in this list.

Are you using a timer at all? If so is the delay 2 mins, meaning there is a failure at boot but is sorted by the time autohotspotN runs again on the timer.

Other than the time to run the script, network wifi is the same setup as it is without this process so shouldn't take much more time than an unmodified Pi. Normally wpa_supplicant will be run earlier and be ready when the wifi device is fully setup. With the autohotspot it is started once the wifi device is fully active.

Wifi dongles can be slower to start than internal wifi but not massively.

Let me know your responses.
Hi, my sd with jessie (on RPi2) and older version of the script (version 0.95-1-N/HS-I that was working perfectly) has been corrupted and I've installed new buster raspian and new script (version 0.95-41-N/HS-I) but it is not working at all: after followed the procedure, wifi dongle do not connect to my WiFi router, neither acts as Access Point. If I disable the script as described here, RPi2 works perfectly and connects to WiFi... any suggestion?
Of course the script is executable.
Thanks
Hi Antonio

Does it work if you run it manually with sudo /usr/bin/autohotspotN

If it does check that the autohotspot service is enabled
You can check if that run ok at boot with sudo systemctl status autohotspot

Otherwise let me know any errors you see and i will look into it.
SOLVED! for some strange reason my RPi need to have always the ";" before "then" in the "if-then" statements. Now it works perfectly.
Thanks
Antonio,
Cool glad it works.
The ; means new line. Then should be on a different line to the if line without the ;
I have installed buster, update & upgrade. Installed hotspot software and all appears to be working correctly except for vnc. Error says can not display screen. I can ssh using the IP address assigned. If I plug in the rpi hdmi and reboot then vnc displays the screen.
Hi Art

Does the PI boot straight on to a desktop screen or does it just stay in the terminal screen and you start the Desktop manually?

VNC will only work if the PI boots on to a desktop, even if you don't have a display attached. SSH will work with either.
SSH in and set the resolution via raspi-config and reboot. Then you will see the display when you VNC into it next. Not sure why this is different in Buster but it is the only way I can get it to work. Jason
Jason
Will give that a try. I have the app running on a RPI4 and noticed if the display isn't plugged in prior to booting, Buster will only boot to the console.

Before, I could plug in the display after boot using Jessie and the RPI would switch and VNC worked.

ART
Jason



Maybe a clue from the raspberrypi.org



“A few features of the old non-OpenGL video driver (such as pixel doubling
and underscan) are not currently supported by the new OpenGL driver, so the
settings for these are hidden in Raspberry Pi Configuration if the GL driver
is in use. (The GL driver is the default on Raspberry Pi 4 – older Pis will
still use the non-GL driver by default. Also, if using a Raspberry Pi 4
headless, we recommend switching back to the non-GL driver – choose ‘Legacy’
under the ‘GL Driver’ setting in ‘Advanced Options’ in raspi-config.)



art
So I finished following the set up, and everything works amazing. I can access the pi with a laptop and get on the network. Then I tried to use x11 forwarding on the ash and it wasn't working. I tried ssh -X and then starting the x server and I also tried just ssh -X. Neither worked. The x11 doesn't work over this. Funny thing is that before it was running on the hotspot, and if I switch it to the wifi, then the x11 works, any ideas?
Hi Jakabya
I have just tested this with a Pi on Raspbian Buster in Hotspot mode. From an Ubuntu Desktop PC I connected using ssh -X pi@192.168.50.5 and then loaded leafpad through ssh and got the window to appear on the PC. So it is working with my setup.
Have you checked if vnc is working as a test?
So I finished the tutorial, and it should work, but doesn't. Yes the file is executable, I tried running it, I check to see if dnsmasq is running and if hostapd is running, they both are. I checked the ip for the wlan0 and it is the changed up, so I have no idea what it could be, everything seems to be working on the pi, but on my phone and laptop, no WiFi hotspot. I don't know what it could be. Using rpi3 w/ raspberrian
Hello Steven

If you don't see the RpiHotspotN SSID on other devices then the issue is most likely with hostapd.
If everything looks fine on the PI, did you change the password in the /etc/hostapd/hostapd.conf file?
if so double check it has at least 8 characters.

Hostapd fails if the config file is not complete at /etc/hostapd/hostapd.conf also if the /etc/default/hostapd file does not have the path to the hostapd.conf file correctly or the password is too short.

I take it when your router is on the Pi connects to the router wifi fine it's just when it goes to the hotspot you can't find the RpiHotspotN ssid on other devices?

If this doesn't help, if you run hostapd manually you can get further feedback.
Let the pi generate the hotspot then stop hostapd with
sudo systemctl stop hostapd
then run it manually with
sudo hostapd -d /etc/hostapd/hostapd.conf

It will give you more details about what is going and any issues.

Please email me any errors you have from any of the sudo systemctl status hostapd and for autohotspot and I will look into it for you. admin at this site

Roboberry
Ok, so I had it working kind of. So what I had to do to get it to display the SSID on other divices was get rid of the line in /etc/hostapd/hostapd.conf that specifies the driver. The only problem with that is that now my other devices can see the SSID but can not connect to it. I am typing in the passkey right and it just times out. I am using a raspberry pi 3 b and I was wondering if specifying the correct driver would fix this. When I had the one in that you specified it gave me an error in line 2: invalid/unknow driver then the driver name. I can not seem to find the name of the driver the raspberry pi 3 b. Any help would be great
Hi Steven
Hostapd will show errors for the driver if the driver is stated or not, but it i the one used by all PI's with wifi built in. The driver is in the Linux core and is what this version of hostapd uses. So as long as you are using the PI3's wifi then the driver setup is fine. Some external usb wifi dongles use a different wifi chipset and so have to use a modified version of hostapd but for the PI the standard one is the only one that works.

I have played with the config to reproduce your issue.
If hostapd is still enabled then it will start before the hotspot and cause a bad configuration. You will see that hostapd is running fine in sudo systemctl status hostapd. The RpiHotspotN ssid exists but no device can connect. On the pi the ip for wlan0 will not be 192.168.50.5
to fix: sudo systemctl disable hostapd

In /etc/default/hostapd if the bottom line of DAEMON_OPTS="" has no # and has an entry after =, this will cause no SSID to be issued but hostapd is running.

Also if Hostapd is masked it will not run at all so there will be no SSID generated.

I feel there is another issue with hostapd rather than the driver as it doesn't need to be stated in the config for the Pi's. It's there for usb wifi.

Did you create hostapd.conf from the download link or copy the details from the webpage? if the webpage can you delete hostapd.conf and then redo it copying the text from the download above that section in the article.

Can you send me the output of sudo systemctl status hostapd when the hotspot is running.
Does wlan0 have ip 192.168.50.5 and is it the only ip for wlan0?

Does the autohotspotN script conect to your router fine. Any further details would be useful.

Thanks
I found the proper driver for the wifi, put it in the code, and it works, kind of. It works well enough that my phone can connect to it, but my laptop can not connect to if for some reason, when I manually run hostapd and then try to connect, the laptop will connect, then disconnect over and over again. This will continue for almost forever until I tell the laptop to stop or the hostapd to stop. Any ideas?
Hi Steven
Can you give me details of what driver you have installed please. I don't know why you need anything other than the default pi setup. I have used hostapd on all wifi pi's across that last 4 versions of the Raspbian OS without needing to install additional drivers.
Your laptop is failing because it is receiving wifi coms from the pi it doesn't understand. I have had the same in the past which is due to a config issue.Both dnsmasq and dhcpcd trying to control the wifi.

I will need more info about your setup, could you send me the info requested in the previous reply please as this will help me understand what your pi is doing.
Your new issue can be related to dhcpcd still running on wlan0. Can you confirm you only have the hotspot ip showig and not two ip addresses.

Can you also let me know if you copied the files from the webpage or from the download links. Are you viewing the website on the pi during the setup? Have any files been opened and saved on a windows machine?
About the drivers, I had a typo in there, sorry. There is only one ip address, and i hand coppied it, ik not the most efficient. wlan0 has ip of 10.0.0.5 in ifconfig.

As for the rest of the info...

First I run sudo /usr/bin/autohotspot
just to make sure that the hotspot is running

then I run sudo systemctl status hostapd
I get back the following:

loaded:loaded (/etc/init.d/hostapd)
active: active (running) since sun 2019-09-22
CGroup: /system.slice/hostapd.service
1452 /usr/sbin/hostapd -B -P /run/hostapd.pid /etc/hostapd/hostapd.conf


Sep 22 08:04:30 Jakabya hostapd[1452] : wlan0: STA 9c:b7:0d:0a:32:2f IEEE 802.11: disassociated
Sep 22 08:04:31 Jakabya hostapd[1452] : wlan0: STA 9c:b7:0d:0a:32:2f IEEE 802.11: associated
Sep 22 08:04:31 Jakabya hostapd[1452] : wlan0: STA 9c:b7:0d:0a:32:2f RADIUS: starting acount session 5D8729C4-00000005
Sep 22 08:04:34 Jakabya hostapd[1452] : wlan0: STA 9c:b7:0d:0a:32:2f WPA: pairwise key handshake completed (RSN)

Sep 22 08:04:35 Jakabya hostapd[1452] : wlan0: STA 9c:b7:0d:0a:32:2f IEEE 802.11: disassociated
Sep 22 08:04:35 Jakabya hostapd[1452] : wlan0: STA 9c:b7:0d:0a:32:2f IEEE 802.11: associated
Sep 22 08:04:35 Jakabya hostapd[1452] : wlan0: STA 9c:b7:0d:0a:32:2f RADIUS: starting acount session 5D8729C4-00000005
Sep 22 08:04:35 Jakabya hostapd[1452] : wlan0: STA 9c:b7:0d:0a:32:2f WPA: pairwise key handshake completed (RSN)
Hi Steven

Thanks for the info. The disassociated and associated lines show that there is a connection issue in hostapd.

The IP of 10.0.0.5 is for the direct hotspot designed for the pi zero, but this comment is posted on the internet enabled hotspot for Pi 1,2,3 & PI4 which has an ip of 192.168.50.5.

Can you check that in /etc/dnsmasq.conf the last line for dhcp-range matches dhcp-range=10.0.0.50,10.0.0.150,12h
and in the /usr/bin/autohotspot contains this section

createAdHocNetwork()
{
echo "Creating Hotspot"
ip link set dev "$wifidev" down
ip a add 10.0.0.5/24 brd + dev "$wifidev"
ip link set dev "$wifidev" up
dhcpcd -k "$wifidev" >/dev/null 2>&1
systemctl start dnsmasq
systemctl start hostapd
}

if the IP in the autohotspot script doesn't match the range on the dnsmasq.conf file then that will cause the issue if seeing the hotspot but not being able to connect to it. If you wanted the internet routed autohotspot then the ip should be 192.168.50.5

Let me know if you setup matches and which hotspot article has been installed.
Are you using Raspbian Buster or Stretch?
I have followed the instruction and everything works fine when testing. However, when rebooted and no wifi signal is present, the hotspot is created with a 169.x.x.x address instead of 192.168.50.5. Any idea why? I am running Buster on a Pi 3. Same results on a Pi 4. I never ran into this on Stretch. Thanks, Jason
Hi Jason.
The 169 ip is generated when the dhcp server is not working correctly. For the hotspot dnsmasq is used over dhcpcd. dhcpcd is used for normal network wifi. I think dhcpcd is still running which should mean your wifi has two ip addresses. If you enter 'ip addr' in terminal do you see two ip addresses assigned to wlan0? one will be 192.168.50.5 created by the autohotspotN script and the 169.x.x.x number.

If so go into /etc/dhcpcd.conf and check the nohook wpa_supplicant line is correct. I have entered it as nohooks before which does cause this issue.

An earlier version of this script didn't stop dhcpcd from running during the hotspot which works fine unless you're using a streaming service that connects before the hotspot get generated. The stream fails when the hotspot starts so it's best to disable dhcpcd for wlan0 while the hotspot is working. dhcpcd is still used for ethernet. Let me know if you still have an issue.
When I run hostname -I, I have 2 ip addresses. One for my eth0 10.x.x.x, and the other is wlan0 169.x.x.x. So here is the interesting part......I reflashed the SD with Buster (July 19). Before I have done both apt-get update & upgrade before installing the hotspot and got the 169.x.x.x. address. This time, after the fresh install, I only ran sudo apt-get update and then installed the hotspot. All worked as expected. After running sudo apt-get upgrade, the hotspot is still working as it should. I suspect something has changed in the dhcpcd package that is causing the 169.x.x.x assignment if you run 'upgrade' before installing the hotspot. Jason
Hi Jason,
Interesting i will take a look and see what has changed. Thank you.
Hi Jason. I have reinstalled Buster then done a full update before setting up the hotspot. I also got the same issue of the 169 ip address. What seems to be happening is the service for dnsmasq was enabled even though I had disabled it during the hotspot setup.

This was causing the 169 ip as the hotspot was not able to generate it's IP as dnsmasq was running.
Once the dnsmasq service was disabled again it all worked correctly.

I then reinstalled a fresh Buster imgage again and redone the test and I had no issues at all and dnsmasq did not enable. So I can only presume an update has re-enabled it after the hotspot was setup even though a full update had been done before the hotspot setup.

One to keep an eye on. If your finding anything different in future setups please let me know.
Thanks for looking into it. Glad to know I am not going crazy. haha. After fresh install and upgrade, I installed the hotspot again. Again, got the 169 ip address. Ran 'sudo systemctl disable dnsmasq' thinking this would disable dnsmasq. After reboot, I still receive the 169 address. What am I missing or is this something that will need to be done after each boot? Thanks, Jason
Hi Jason.
No there is nothing else to do on each reboot. That's the correct command to disable dnsmasq at boot. I had been fiddling around before I noticed the dnsmasq service was enabled so it could have been a result of something else as well.

With the 169 ip for the hotspot run sudo systemctl status dnsmasq
there should be a line essentially saying wlan0 was not found or unavailable. This is the core of the issue as dnsmasq was unable to configure wlan0.
I had stopped and started dnsmasq manually with sudo systemctl stop dnsmasq and then sudo systemctl start dnsmasq. Try stopping the service and disabling it then rebooting so it goes to hots spot.
If the Pi goes to wifi first and then switches to the hotspot without a reboot it all works fine.

Strange my first test failed as yours did but my second attempt went through fine. I will redo a fresh Buster SD tonight and see if I get the issue again.

The Hostapd service is masked when installed, though the service is not used and hostapd is started after dnsmasq I have unmasked it with sudo systemctl unmask hostapd. Worth a try.

I will get back to you with the results of the retest.
I think the difference is in our test method. I have no available WiFi's for the hotspot to connect to. After boot I stopped then disabled dnsmasq. Reboot. Still have 169 address. If I make a WiFi available and the hotspot connects and then run hotspot again with no wifi present, i get the correct ip address from the hotspot. So my question would be, is it possible to get the right ip from the hotspot on boot when no wifi signal is present? This always worked with stretch. I have tried playing with your script a bit to stop/disable dnsmasq in a few different places. All to no avail. Thanks, Jason
For my tests I had a non valid SSID in wpa_supplicant.conf.
If there is no router then it will go to the hotspot as no SSID is returned. So having a false SSID in wpa_supplicant would work the same.

Does sudo systemctl status dnsmasq report that wlan0 is not available or similar message?

The hotspot script contains the 192.168.50.5 ip so when that runs it will be generated. If dnsmasq has failed for some reason then dnsmasq will generate its own ip starting with 169.

The fact it works after you connect to wifi and then go back to the hotspot shows the setup is working. Which is what I saw in the first test.

It's just booting to the hotspot failed because dnsmasq couldn't access wlan0.

Once I have tested again tonight and taken notes of every action then hopefully I can debug the situation.
For the last test I done I installed Buster, rebooted. apt update, apt upgraded, rebooted, then apt updated and apt upgraded as there was some more, the apt autoremove.

Then followed my guide from the website and all was fine. The first time I didn't do the second update. But I will see ehat happens tonight.
I have redone the setup starting from scratch on a PI4, downloaded the Raspbian Buster with Desktop from the Pi foundations website.
Setup through Ethernet, entered wifi details at prompt. Let the setup wizard do an update.
Checked with apt update and Upgrade that it was fully up to date.
Once that ended I edited wpa_supplicant to a false ssid and rebooted for the first time.
Still on Ethernet I installed the hotspot from this page. I used the download links and copied the text and pasted it into the files using nano, or to the bottom of config files where applicable.

Once complete I rebooted and it went straight to a working hotspot with the 192.168.50.5 ip.

I have since enabled the dnsmasq service and rebooted, it worked fine as a hotspot.

So unfortunately I have not been able to reproduce the issue. I can only suggest uninstalling dnsmasq, sudo apt purge dnsmasq
then reinstall it, don't purge dns-root-data if you previously done that. Disable the dnsmasq service and setup the config and see if that solves the issue.

Happy to look at your config files or an SD image if you wish. If you can send me the output of
sudo systemctl status hostapd, sudo systemctl status dnsmasq, sudo systemctl status autohotspot, sudo systemctl status dhcpcd
I see if anything stands out.
Think you can do a sudo crontab -e to set up a root crontab which does not then require you use sudo in the crontab command as it is run as root, which enables you to lock down sudo with a password, instead of using sudo in the pi (or other) users crontab command which requires the lax sudo password

also noticed the iw scan does not always return the full list of access points in any given number of runs, I am in a busy wifi area here

otherwise, excellent! Thanks!
Hi Paul, your welcome. You're right you can use the root cron as well. So you don't have to use sudo. Though you have to remember if your using root cron or use cron is i have had conflicts using different scripts but outhrerwise works as well.

Iw will only come back with the first strongest signals it gets in the time limits it has, so its possible the required signal is missed in a busy area. If you use the Mac address option and add your routers mac address even if it is not hidden, it will always be checked to see if it's available. Which should solve the issue in busy areas.
added one extra condition as first elif in chain to deal with nothing back from iw (which has happened quite frequently here)

elif [ -z "$ssidreply" ]; then
j=$((j + 1))
sleep 2
Hi Paul.
Do you mean that iw finds no wifi signals at all even if they are there, so you are making it check again?

If so then this may cause an issue for users out of town where there is no signals which they want it to go to a hotspot. Im not going to have access to my Pi's until next week so will have a closer look then, but thanks for the feedback. Any feed back is good as it has been created for my world so not situations others have.