Friday, 30 June 2017 21:17

Raspberry Pi - Auto WiFi Hotspot Switch Internet

Written by 
  • Author Type: Individual

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 Stretch and Raspbian Jessie.

Latest updates to setup - 15th May 2018 - hostapd.conf, dhcpcd.conf, autohotspotN


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 Hotspot switch script Raspberry Pi - Auto WiFi Hotspot Switch - Direct Connection

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

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 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
  • 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 Jessie and Raspbian Stretch. To see which version you have enter the command lsb_release -a

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

This setup has been tested on Raspbian Jessie and Raspbian Stretch using a RPi3B+, RPi3RPI Zero W and a RPI 2 . A connection has been made to the Hotspot using an Android Tablet, Ipad2, Raspberry PI and Windows 10. All worked fine with SSH.

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.

Note:

Dnsmasq bug: in versions below 2.77 there is a recent bug that may cause the hotspot not to start for some users. This can be resolved by removing the dns-root-data. It may be benificial to do this before you start the rest of the installation as it has been reported that doing it after installation for effected users does not work but you won't know if it is an issue until after the installation is complete.

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.

 

Note about Raspbian Stretch Network Device Names

For 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 Raspbian Stretch 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 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. (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 Pi 3B+, RPi 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 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 hotspot. 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

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,255.255.255.0,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 hotspot 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

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' )
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.95-4-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 Internet
#A script to switch between a wifi network and an 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 }' ORS=',' | 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 "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
}

KillHotspot()
{
    echo "Shutting Down Hotspot"
    ip link set dev "$wifidev" down
    systemctl stop hostapd
    systemctl stop dnsmasq
    iptables -D FORWARD -i "$ethdev" -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
    iptables -D FORWARD -i "$wifidev" -o "$ethdev" -j ACCEPT
    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
}


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
        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 "$ssidreplay" | 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 "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 "$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
}

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

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

 

For the autohotspotN script to work it needs to be 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.

Firewalld: 

if you are using the firewall firewalld then you will need to replace the hotspot activation and deactivation functions so it works ok with the firewall.  In the autohotspotN script locate the createAdHocNetwork() section and the KillHotspot() funtion and replace it with this code


createAdHocNetwork()
{
    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
    firewall-cmd --direct -add-rule ipv4 nat POSTROUTING 0 -o eth0 -j MASQUERADE
    firewall-cmd --direct --add-rule ipv4 filter FORWARD 0 -i eth0 -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
    firewall-cmd --direct --add-rule ipv4 filter FORWARD 0 -i "$wifidev" -o eth0 -j ACCEPT
    systemctl start dnsmasq
    systemctl start hostapd
    echo 1 > /proc/sys/net/ipv4/ip_forward
}

KillHotspot()
{
    echo "Shutting Down Hotspot"
    ip link set dev "$wifidev" down
    systemctl stop hostapd
    systemctl stop dnsmasq
    firewall-cmd --direct --remove-rule ipv4 nat POSTROUTING 0 -o eth0 -j MASQUERADE
    firewall-cmd --direct --remove-rule ipv4 filter FORWARD 0 -i eth0 -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
    firewall-cmd --direct --remove-rule ipv4 filter FORWARD 0 -i "$wifidev" -o eth0 -j ACCEPT
    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
}

 Thank you to Z-WolF for supplying this update.

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.

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 Raspbian Pixel AP mode icon 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

android wifi in range list

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 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.

 

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 :)

RaspberryConnect.com

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.

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 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 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 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. 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 }

 

 

Last modified on Monday, 20 August 2018 20:58
Google
roboberry

RapberryConnect.com SuperUser.  Contactable via the site admin e-mail in the Contact Us link.

Website: www.raspberryconnect.com

Leave a comment

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

126 comments

  • Comment Link roboberry Monday, 27 August 2018 12:21 posted by roboberry

    Hi Luigi, The DHCPCD server is restarted as part of bringing the network back up in KillHotspot, its the last line. So you don't need to reactivate it there.
    Having the dhcpcd server running with wlan0 during the hotspot will cause there to be two IP addresses active on wlan0 . see ip addr
    On a previous version of the script I did leave dhcpcd running with dnsmasq, showing the blue arrows, and it worked fine for me as you are also finding but several users found that other services such as streaming lost connection if the streaming service connected to dhcpcd before dnsmasq started. Also some devices see the connection as unstable and don't connect to the hotspot.
    So if it works for your use then thats ok but for it to fit the widest range of users dhcpcd needs to be stopped on wlan0 for the hotspot, which causes the two red crosses for the wifi icon but is correct.
    I presume you have an issue with dnsmasq that is causing the issue either in the config or the dns-root-data issue.

    Report
  • Comment Link Luigi Friday, 24 August 2018 06:15 posted by Luigi

    Hi,

    Thank you for your kind answer. In the meanwhile I fixed the problem by restarting dhcpcd at the end of both createAdHocNetwork() and killHotSpot(). Now, in the hotspot mode I get a double blue arrow on the top bar and it seems working by connecting other computers. May be this a solution?

    Ciao
    Luigi

    Report
  • Comment Link roboberry Monday, 20 August 2018 21:20 posted by roboberry

    Hi Luigi. I presume you are using a PI with built in wifi? if you are using a PI with a wifi dongle then it is likely that wifi dongle is not usable as a access point, check if it has a AP mode.

    To trouble shoot the built in wifi; when the hotspot is active the wifi icon will be two red crosses and will show the message "Wlan0: STOPPED" this is because dhcpcd has been disabled on wlan0. dnsmasq will be managing the network for wlan0 at this point. ETH0 will still be managed by dhcpcd though.
    Check that dnsmasq is running ok with sudo systemctl status dnsmasq
    that should say it is running. If not then there should be an error in the message. Check the dnsmasq config is ok.

    Also see if the ip of 192.168.50.5 has been generated on wlan0 with the command ip addr

    When your router is active again the PI will only connect if you are using the cron timer or you manually enter sudo /usr/bin/autohotspotN
    otherwise it won't pick up your router until you reboot.

    When the PI goes back to network mode, dnsmasq is disabled and dhcpcd will be back in control of wlan0.

    Let me know how you get on and what happens and I iwll look into it further

    Report
  • Comment Link Luigi Sunday, 19 August 2018 23:02 posted by Luigi

    Hi,

    thank you for your script. I am experiencing the following problems:
    - the hotspot seems to be created (hostapd is running as service) but the SSID is not broadcasted
    - when my home router goes up again, the wifi connection is not restarted. I solved this problem by typing
    sudo systemctl daemon-reload
    sudo systemctl restart dhcpcd

    In bot case, if I move the mouse over the network icon, i get the message "wlan0: STOPPED". Please, may you help me to fix this problem? Thank you

    Report
  • Comment Link MinhP Tuesday, 14 August 2018 06:16 posted by MinhP

    Thanks, Roboberry for answer my question. Ok, I will try change difference channel. I will be back town next two week and try out.

    MinhP

    Report
  • Comment Link Atanas Atanasov Saturday, 11 August 2018 10:45 posted by Atanas Atanasov

    Hi roboberry,
    yes, I didn’t use the pi user... I’ve configured everything as root, including the root crontab.
    When I do such permanent configurations I prefer to run them as root and leave them there.. to not show up in the user crontab and etc... and I do not like using sudo extensivly as in every command during configuration... lol

    Report
  • Comment Link roboberry Friday, 10 August 2018 20:24 posted by roboberry

    Hi Atanas Atanasov, thanks for the detailed info about the crontab issue. Are you using a user name other than the default PI user?

    There is a permissions issue using a cron tab and you are not the using the default PI user, which is noted in the article, as additional users don't get the same permissions and paths as the PI user.

    If you have a different user I will add an additional note to be aware of that as well.

    Glad you have found the script useful otherwise.

    Report
  • Comment Link roboberry Friday, 10 August 2018 20:13 posted by roboberry

    Hi TomP

    You should be ok with the latest pi version of dnsmasq (2.76), that is a precaution from a reported issue but seems to be fine in general.

    What specific issue are you having with the hotspot, does it go through the motions of creating a hotspot but then it doesn't come up?

    First of all in terminal run the autohotspotN script manually.
    sudo /usr/bin/autohotspotN

    If the feedback says that it has generated a hotspot then check the status of dnsmasq with
    sudo systemctl status dnsmasq or sudo journalctl -xe
    these will show you if there are any errors with dnsmasq running.

    it should say status running

    do the same for hostapd
    sudo systemctl status hostapd
    this also should say running.

    also check that network wifi is down as the hotspot will fail if wifi is still up
    wpa_cli status -i wlan0
    it should say failed to connect to non-global......
    If that's is still up the check the nohooks line in dhcpcd.conf but I suspect that is fine.

    Let me know what results you get

    Report
  • Comment Link roboberry Friday, 10 August 2018 19:43 posted by roboberry

    HI MinHP, The test with turning off wifi and connecting the network cable is to see if the PI can still get internet access through the network cable, the iphone won't be able to connect at this point as the wifi is off.

    If you think you have a weak signal try using a different wifi channel as other routers in your area may be causing the issue.
    in /etc/hostapd.conf change channel=8 to different channels and try again.

    I have a 5Ghz setup but I haven't used it much, there also seems to be more limitations in some countries and less reliable in densely populated areas than 2.5ghz N.
    I haven't spent much time on my pI'S latley but I will add it as an option when I get time.

    Are you able to connect to the hotspot from your laptop and get internet access?
    If so then the issue will be with the Iphone.

    Report
  • Comment Link Atanas Atanasov Friday, 10 August 2018 08:28 posted by Atanas Atanasov

    Hi everybody .. First, please excuse me if something is not clear, but I'm not a native English person. I want to share my experience in case somebody else is having the same troubles as me.

    I have followed this tutorial, and everything worked perfect until I set this into the crontab (I didn't know at first the crontab was the problem, since I did it instantly following the tutorial, but found that after extensive debugging). Over all, the main script and setup works. Great job!

    The problem:
    When the RPi 3 B+ (Stretch) boots, everything is fine - it connects to WiFi or create a hotspot (if no known WiFi in range) and I'm able to connect via SSH and configure whatever I need (never checked if connected to Ethernet will start to spread Internet over WiFi hotspot, but I don't need that right now). After a while I've started getting problems .... interruptions of ssh sessions and etc..
    However, checking the ifconfig, after a while the IP changes to the one from the dnsmasq (192.168.50.5), which was so strange, since the RPi was connected to the WiFi and has Internet. I have checked running processes, and dnsmasq and hostapd were running for some reason?! However, if using the remote SSH (not attached to monitor), after a while I got disconnected, and I have no way to see if RPi was running or just unstable because of some other things... There were no hotspot network running, so I know it was running on WiFi, but was unresponsive.

    So I debugged this with monitor attached.. After it changes the IP to the dnsmasq one, I have run the autohotspotN script manually and everytime it shows:

    SSid's in range: ..... correct SSID list (removed to be more clear)
    Device Available Check try 0
    Device Available, checking SSid Results
    Valid SSID Detected, assesing Wifi status
    Shutting Down Hotspot
    iptables: Bad rule (does a matching rule exist in that chain?).
    iptables: Bad rule (does a matching rule exist in that chain?).
    Hotspot Deactivated, Bringing Wifi Up
    Checking WiFi connection ok

    So, after manual run of the script, it switches back to 192.168.0.X (the proper WiFi assigned IP) and shuts down the dnsmasq and hostapd processes. After a while, switches them ON again and the IP changes once again. So I have understood this is periodic process, so it must to be the crontab... since after boot and manual run it's just perfect. I have removed the crontab entry and it worked without glitches for a while... so then I was 100% sure it's the crontab setup.

    Then ... I have decided to spent some time on the crontab debug... I have logged the output of the script... and catch this:
    SSid's in range: /usr/bin/autohotspotN: line 86: iw: command not found
    Device Available Check try 0
    Device Available, checking SSid Results
    No SSid found, assessing WiFi status
    No SSid found, assessing WiFi status
    Creating Hotspot

    Then, next log entry was:
    SSid's in range: /usr/bin/autohotspotN: line 86: iw: command not found
    Device Available Check try 0
    Device Available, checking SSid Results
    No SSid found, assessing WiFi status
    No SSid found, assessing WiFi status
    Hostspot already active

    So, I have understood there's a problem with iw command, but when I run the script manually it just works perfect (same on boot)... So it must be something else.... It was the $PATH for the cron ... The cron wasn't seeing /sbin/ where iw is originally located. Once I have edited the crontab and added on top of any configured scripts:
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

    everything went perfect and this now works in the way I'm expecting.. It's no longer activating dnsmasq and hostapd unless out of WiFi range. I guess the default RPi PATH for crontab is not including all possible bin paths, or at least mine wasn't.

    Hope this helps somebody else experiencing my problem.

    Report
  • Comment Link TomP Tuesday, 07 August 2018 16:55 posted by TomP

    Hi roboberry

    I can't get the hotspot to work. is there a log file I can call up?

    Problem: When I removed dns-root-data and then installed dnsmsq, it wants to install dns-root-data. And I'm stuck with installing version 2.76

    All other text and permissions are correct..

    Thanks!

    Report
  • Comment Link MinhP Sunday, 05 August 2018 18:40 posted by MinhP

    Hi Roboberry,

    Sorry missed answer your first question. Yes, I had my ethernet cable connect to the Pi and turn off Wifi had same issued that my iPhone could not open the web page.

    Thanks, for your following up my question.

    MinhP

    Report
  • Comment Link MinhP Sunday, 05 August 2018 18:35 posted by MinhP

    Hi Roboberry,

    Yes, I had setup my country US correct on your instruction. My iPhone can see my PI-Mp but I could not access to the internet from my iPhone. It was showed nothing once I tried http://www.google.com or Yahoo.com. I was also tried to turn off my iPhone data but the same issued. You said will up date the hotspot to access 5G, when will this update? I think your instruction setup for 2.5G may be cause weak signal to access the hotspot?

    When I try not install your instruction, let said by default. I could access it from my laptop putty with the IP address, it mean my Pi B+ was still working good.

    Report
  • Comment Link roboberry Sunday, 05 August 2018 10:59 posted by roboberry

    Hi Durga prasad, If you would like to use an external wifi adapter for the hotspot instead of the built in wifi then you just need to change the device from wlan0 to wlan1

    in /etc/hostapd.conf
    interface=wlan0 to interface=wlan1

    in /etc/dnsmasq.conf
    #AutoHotspot config
    interface=wlan0
    to
    #AutoHotspot config
    interface=wlan1

    in /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
    to

    wifidev="wlan1" #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

    Those changes should use the ALFA Wifi Adapter instead of the internal wifi.

    Report
  • Comment Link roboberry Sunday, 05 August 2018 10:48 posted by roboberry

    Hi MinhP, did you try the suggestions in my previous response, if so could you let me know if your PI can access the internet when a network cable is attached and and wifi is off.

    When the Pi is in hotspot mode internet is only available if a network cable is attached to the Pi, can you confirm this your setup when the iphone says no internet

    There can be different reasons depending what you pi is and is not doing so can you give me some feedback on the state of your pi.
    If Internet via a network cable works fine then we know the pi is working fine.
    Have you set your localisation settings in Pi_Configuration for your country, that can cause some connection issues with phones.
    On the pi goto Preferences/Raspberry Pi Configuration. Then the Localisation tab and "Set wifi Country"
    choose the correct details for your country.

    On Android Phones you can't connect to the hotspot of you have Mobile Data active. I don't know about Iphones but try turning off Mobile Data before connection to the hotspot.

    If you can let me know the the answers to the above I can look into the issue further, thanks

    Report
  • Comment Link MinhP Friday, 03 August 2018 06:36 posted by MinhP

    Thanks, for reply. I have to re install it again on new Raspberry B + and I can see my Pi on my iPhone. Please let me know how to test it? I can't open the page on my iPhone?

    Report
  • Comment Link MinhP Thursday, 02 August 2018 06:28 posted by MinhP

    Thanks, Roboberry for quick reply. I have re do it again on your instruction on my new Raspberry P3 + B and I can able see my Raspberry on my iPhone. Please let me know how do I test it on my iPhone? I would like control on/off from my iPhone to turn on the LED.

    Thanks, again for your support

    Minh P

    Report
  • Comment Link Durga prasad Wednesday, 01 August 2018 07:00 posted by Durga prasad

    I want to create an own wifi network using the raspberry pi3 and AWUS036NHA (ALFA Wifi Adapter). I am using this ALFA Adapter for longer ranges.Using that network I want to transmit the data . I have tried this http://www.raspberryconnect.com/network/item/330-raspberry-pi-auto-wifi-hotspot-switch-internet but I am not getting the correct solution.

    Report
  • Comment Link roboberry Tuesday, 31 July 2018 20:33 posted by roboberry

    Hi Minh, could you let me know if you are able to connect to the PI's hotspot with ssh or VNC ok. Just to confirm the hotspot to the PI is working ok.

    If the hotspot is working fine but you don't get internet when the Network Cable is attached to the LAN port then just check the line in
    /etc/sysctl.conf
    is
    # Uncomment the next line to enable packet forwarding for IPv4
    net.ipv4.ip_forward=1

    and /etc/dhcpcd.conf has the line
    nohook wpa_supplicant

    but as you have checked this all other parts to make the internet work are in the script.

    While the pi is on network mode with wifi disabled and the Network cable attached do you get internet access, if so it should also still work in hotspot mode.

    If you could give me further info on what happens I will into it further for you.

    Report
  • Comment Link Minh Tuesday, 31 July 2018 05:40 posted by Minh

    Hi,

    After I have done all the steps and my iPhone see R3PI but it keep said " No Internet Connection", please help and let me know how to fix this?

    Thanks,
    Minh

    Report
  • Comment Link roboberry Thursday, 19 July 2018 21:40 posted by roboberry

    Hi Rob, The issue depends on what state the PI is ending up in. I presume that the hotspot is not getting created but it is also not getting a network connection.

    Firstly when you add your country code it updates /etc/wpa_supplicant/wpa_supplicant.conf.
    the top 3 lines of the file should look like this

    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    country=GB

    with your country in place of GB if your not in the uk. If these lines are not included then it will cause an issue.

    next see if the AutohotspotN script run successfully, enter sudo systemctl status autohotspot
    This will show you the if the script successfully run at start up.

    If there is an error it will show what the issue is.
    You can also run the script manually and it will give feed back about what it is doing.
    sudo /usr/bin/autohotspotN

    If you can let me know a bit more detail about what messages you get and if the network side works or not I will look into it further for you.

    Report
  • Comment Link Rob Tuesday, 17 July 2018 22:33 posted by Rob

    Hi there. Great detailed write-up. I am completely new to Raspberry Pi 3 B+ and my terminal line code Kung-Fu has always been week. I have Raspbian Stretch 4.14 installed I think its the full desktop version. I have tried this hotspot setup 3 times now with zero results. Each try was with a fresh OS install and updates. A friend did this with his and it worked on the first try. has has the rasp 3B+ as well. I have tried the trouble shooting commands and still nothing.

    I know when I do this mod the wifi keeps asking for me to input the wifi country and i do but it never takes it looks like. The wifi will also say wlan0: not associated. I literally copied and pasted these commands in and tweaked the lines as need per your instructions.

    Just not sure what else to do. My end results is I just want to be able to VNC in without any outside network help directly from my VNC app on my tablet.

    Thanks
    --Rob

    Report
  • Comment Link Guy Sheffer Tuesday, 26 June 2018 14:12 posted by Guy Sheffer

    Finally got time to release this:
    https://github.com/guysoft/HostSpotOS/releases/tag/0.1.0

    Report
  • Comment Link roboberry Wednesday, 30 May 2018 09:37 posted by roboberry

    Hi Rosario, Thank you for the Donation it is very much appreciated.
    I don't use a firewall myself with the script but the guide does have the separate modifications to the ip tables if you use the firewalld Linux firewall, in the Firewalled section just above Testing the hotspot.
    If you are not using that or not able to used Firewalled then let me know what one you are using and I will see what adaptions it needs.

    Regarding the Change Log; I was considering that as there were a few tweaks this time. Adding a text file to a change log would probably be a good option.

    Recent changes are: dealing with some more network error messages that may happen. The changes to DHCPCD.conf now give control to autohotspot script as some setups needed it, so it is safer to make it the default setup.
    Hostapd now uses 80211N, I will probably include a 5ghz option for PI3B+ soon. I have given the script longer to check if the network is connected before it decides it has failed and goes to a hotspot.
    I will put a more detailed log up. Thanks

    Report
  • Comment Link Rosario Tuesday, 29 May 2018 23:00 posted by Rosario

    Hi :)

    Just forgot to say, that it could be wonderful if you could show on the page, what has been update/changed. A sort of change log.

    Even a link list of all old articles with the different old version, could be helpful to understand what has changed.

    Thanks! :)

    Report
  • Comment Link Rosario Tuesday, 29 May 2018 22:57 posted by Rosario

    Hi :)

    Thank you so much for this tutorial and the scripts. They work wonderful with my Pi Zero/W.

    I've just made a donation to you. Thank You Again!

    There are some problem every time I set the firewall on. It won't works.

    Is there a rule to put inside the iptable to allow the script work correctly?

    Best Regards

    Report
  • Comment Link roboberry Tuesday, 08 May 2018 21:41 posted by roboberry

    Hi Wim Janse, Unfortunately It won't fix your issue if you need IP6 as the dnsmasq is only configured for ip4. But it is capable of handling ip6 so if you're able to configured dnsmasq for ip6 then I will support if there are any changes needed to the autohotspot script for you.

    Report
  • Comment Link Wim Janse Sunday, 06 May 2018 10:57 posted by Wim Janse

    Hi roboberry,

    Thanks for the feedback, I'm eager to see your solution for ip6, as now I have another problem, ie. xrdp (remote desktop) is not longer working, as this needs both an ip4 and ip6 address (which is a bug in xrdp, already for almost a year since someone noticed this)

    Report
  • Comment Link roboberry Tuesday, 01 May 2018 19:56 posted by roboberry

    Hi Wim Janse, Your welcome, thanks for feedback. This seems to be an issue for only a few users so not sure why ip6 ip's cause an issue. I'm working on setup that seems to cause an ip issue if the boot time is slow which may fix your issue as well, which I post when fully tested.

    Report
  • Comment Link Wim Janse Saturday, 28 April 2018 14:19 posted by Wim Janse

    Hi roboberry,

    thanks for this fantastic guide, very well done.

    Just to inform you, I installed all this on a brand new RPi3B+ with latest version Stretch.
    I encountered same problem as Carlo, ie. could not login with SSH, this worked only after a ping from the RPi to my iPad.
    However, the solution given by IPv4 here below did the trick, everything working flawlessly.

    So thanks again, and thanks to IPv4.

    Report
  • Comment Link roboberry Thursday, 19 April 2018 12:40 posted by roboberry

    Hi Mana, you're welcome :)

    Report
  • Comment Link Mana Sunday, 15 April 2018 17:51 posted by Mana

    Hi roboberry,

    Thank you so much for this post. This is the one I was looking after tried so many set up.

    Report
  • Comment Link Roboberry Wednesday, 11 April 2018 22:35 posted by Roboberry

    Hi, Ole, i have just tested CraftBeerPi with both this hotspot script and the static hotspot process. They both generated a hotspot and connected to CraftBeerPi without issue. I was able to access it from two android devices and surf the net as ethernet was connected. So im not able to replicate the issue.

    I have; country_code=GB added to the hostapd.conf file but otherwise as my guide.
    If not done already set your localisation in raspberry pi config. If you have any detail of the issue i will try to look into it further.

    Report
  • Comment Link roboberry Wednesday, 11 April 2018 21:27 posted by roboberry

    Hi Ole, I am going to install Cratfbeerpi as i'm interested to see what the issue is. I see it uses flask as the webserver which I know works as I have used it with the hotspot so there is obviously a config conflict somewhere. I will let you know what I find.

    Report
  • Comment Link Ole Wednesday, 11 April 2018 14:48 posted by Ole

    I just removed it.

    I tried starting and stopping Craftbeerpi, then it started working but then SSH failed to connect.

    After reboot some times it seemed like SSH worked, some times Craftbeerpi..

    I may get it again, got any else ideas?

    ( Currently I'm just using an esp8266 as hotspot powered by the pi itself when away from WiFi. But ofc this is not optimal )

    Report
  • Comment Link roboberry Tuesday, 10 April 2018 21:15 posted by roboberry

    Hi Oleost

    Some people have had similar issues with other services, unfortunately I have not been able to replicate them.
    Try adding the country code to /etc/hostapd/hostapd.conf

    country_code=GB

    change GB to your country if not the UK. If your not sure what your code should be it will be in /etc/wpa_supplicant/wpa_supplicant in the top 3 lines.

    can you confirm that the Ethernet ip is not working with 192.168.50.5

    let me know if this helps

    Report
  • Comment Link Oleost Monday, 09 April 2018 22:09 posted by Oleost

    Hi, thanks for providing script and tutorial.

    Im trying to setup this on an RPi3, running Rasbian Strech with Craftbeerpi 3 installed. https://github.com/Manuel83/craftbeerpi3

    The Craftbeerpi 3 interface is accessed at http://raspberry.ip:5000

    But when I try and access it through 192.168.50.5:5000 I while in hotspot mode I`m unable to get the interface up. If I connect the ethernet cable again it works again at the newly assigned RPi3 IP adress.


    Any ideas to make it work ?

    Report
  • Comment Link roboberry Wednesday, 04 April 2018 19:49 posted by roboberry

    Hi IPv4, thanks for letting us know, appreciated.

    Report
  • Comment Link IPv4 Monday, 02 April 2018 20:16 posted by IPv4

    Hi Roboberry,

    Thanks for this great guide!

    I had similar issues as Carlos when following your instructions on a fresh install of the 2018-03-13-raspbian-stretch-lite image. My issues was solved by disabling IPv6.

    IPv6 was disabled by adding the following to /etc/sysctl.conf:

    net.ipv6.conf.all.autoconf = 0
    net.ipv6.conf.all.accept_ra = 0
    net.ipv6.conf.all.disable_ipv6 = 1

    Thanks!

    Report
  • Comment Link roboberry Wednesday, 28 March 2018 21:14 posted by roboberry

    Hi Carlos, thanks for the clarification. The IP should not be available unless dnsmasq is running. The dhcpcd service is running wifi when the network is up and there will be no ip config set up there and /etc/network/interfaces has no config in Stretch. The 192.168.100.1 ip is only referenced in the autohotspotN script and will only be setup when the hotspot is generated by autohotspotN as it isn't entered in dnsmasq.conf so it dosn't make sense to me. With the PI in network mode with ethernet in, using the command ip addr do you see the ip 192.168.100.1 assigned to wlan0 and is there more than one IP assigned?

    Im not able to reproduce your issue, I will have a go with a new image and SD. Again with the country code for the hotspot. I know it is required for 5GHz mode using hw_mode=a in hostapd.conf but it runs fine without a country code as long as it is hw_mode=g

    Thanks for the info and I will let you know if I can find the issue.

    Report
  • Comment Link Carlos Wednesday, 28 March 2018 10:13 posted by Carlos

    Hi,

    I just added my country code to hostapd.conf and it seems to work now:

    country_code=ES

    What I cannot figure out is why it worked with an Ethernet cable connected to the RPi - maybe the connectivity was done via eth0 although the IP used to ping/SSH belonged to the hotspot generated network.

    Ocen again thanks Roboberry!

    Report
  • Comment Link Carlos Wednesday, 28 March 2018 08:32 posted by Carlos

    Dear Roboberry,

    Excuse me, I did not explain myself. What I meant is that as long as an Ethernet cable is plugged into the RPi *before* the hotspot (hostapd + dnsmasq) is started (not started on boot but with cron-driven /usr/bin/autohotspotN instead) I can connect to the wi-fi network generated by the RPi, ping its IP (which in my case is x.x.100.1) and access it through SSH (of course through wlan0). Once the hotspot is initiated this way I can unplug the Etherne cable and I am still able to ping and SSH the RPi as before.

    On the other hand, if no Ethernet cable is connected to the RPi before the hotspot initialization, I can connect to the wi-fi generated by the RPi but I cannot ping or SSH it. I tried to plug the Ethernet cable after this but it does not work as if it were plugged before de hotspot starting (i.e. I still cannot ping or SSH the RPi).

    In the second case my PC gets an IP from the configured range in the RPi, subnet mask and gateway IP as expected. I can also access the RPi via eth0 and check (systemctl status) the hostapd and dnsmasq and everything seems to be OK. The only thing that I noticed is that in the second case (no Ethernet cable plugged before hotspot initialization) my PC (and also my phone) does not connect as quickly as it does on the first case.

    I appreciate the offer to review my config files but I do not think they are the root of the problem. We are missing something that occurs in my setup (and Vincent and Adam's too) which is causing the problem. I will keep investigating. Please e-mail me if you eventually find what is happening.

    Thank you!

    Report
  • Comment Link roboberry Tuesday, 27 March 2018 21:45 posted by roboberry

    Hi Carlos, It seems a bit strange that the Ethernet can access the hotspot IP. Dnsmasq settings are for wlan0 and not eth0. The ethernet IP should be generated by the network it is connected to, so for me the ethernet is from my router at 192.168.0.47 the hotspot for wifi devices is 192.168.50.5 generated by the PI and gets routed the the Internet via the ip tables.
    Check that the dnsmasq and hostapd services are disabled from auto staring
    sudo systemctl disable dnsmasq
    sudo systemctl disable hostapd

    I presume there is no additional config for your ip added to /etc/dhcpcd.conf

    I have updated my OS and tested it on a Pi3 and a PI3 B+, which generated a hotspot and managed to connect my PC, android tablet, the other pi to the hotspot and ssh from them all. So I can't reproduce your issue. Though Adam R is reporting ssh issues so maybe something has changed in the last update but unfortunately im not getting it.

    Your welcome to email me you config files and copy of the script and I will check them out on my pi but they should be the same.

    Report
  • Comment Link Adam R Tuesday, 27 March 2018 18:28 posted by Adam R

    I have the same issue as Vincent, except that I noticed that SSH and PING work from my Macbook to the Pi (192.168.50.5) BEFORE the DHCP server on the Pi assigns my Macbook an IP address. As soon as an IP address is assigned to my Macbook, the connection to 192.168.50.5 is terminated.

    Hope that helps narrow down the issue.

    Report
  • Comment Link Carlos Tuesday, 27 March 2018 11:04 posted by Carlos

    Dear Roboberry,

    Thank you for your quick reply. I can confirm the changes I made regarding IPs are the same as you pointed and dnsmasq and hostapd seem to work fine. I also changed the wi-fi channel and the problem persists.

    I forgot to mention a couple of things that are probably important:

    1) I am using a brand new Raspberry Pi 3 B+ with Raspbian Stretch / Linux rpitesting 4.9.80-v7+ #1098 SMP Fri Mar 9 19:11:42 GMT 2018 armv7l GNU/Linux.

    2) I am not wiring the RPi to an Ethernet cable since I do not need Internet when there is no wi-fi on range, just SSH.

    I have been testing and I can reach 192.168.100.1 when an Ethernet cable is connected before the hotspot is mounted and it remains accessible even if I unplug the cable after hostapd and dnsmasq are active. But if no Ethernet cable is connected before the starting of the hotspot I have no access to the RPi IP (no ping, no SSH), even if I plug it after or even if I disconnect from the hotspot wi-fi network and connect back.

    I tried to comment out the iptables forwarding directives in /usr/bin/autohotspotN but it has no visible effect in this behavior.

    If you need more info or there is something I can do for you on this matter please ask me to.

    Thanks in advance!

    Carlos.

    PS:

    pi@rpitesting:~ $ sudo systemctl status dnsmasq
    ● dnsmasq.service - dnsmasq - A lightweight DHCP and caching DNS server
    Loaded: loaded (/lib/systemd/system/dnsmasq.service; disabled; vendor preset: enabled)
    Active: active (running) since Tue 2018-03-27 09:49:37 UTC; 13min ago
    Process: 515 ExecStartPost=/etc/init.d/dnsmasq systemd-start-resolvconf (code=exited, status=0/SUCCESS)
    Process: 504 ExecStart=/etc/init.d/dnsmasq systemd-exec (code=exited, status=0/SUCCESS)
    Process: 501 ExecStartPre=/usr/sbin/dnsmasq --test (code=exited, status=0/SUCCESS)
    Main PID: 514 (dnsmasq)
    CGroup: /system.slice/dnsmasq.service
    └─514 /usr/sbin/dnsmasq -x /run/dnsmasq/dnsmasq.pid -u dnsmasq -r /run/dnsmasq/resolv.conf -7 /etc/dnsmasq.

    Mar 27 09:49:37 rpitesting dnsmasq[514]: using nameserver 8.8.8.8#53
    Mar 27 09:49:37 rpitesting dnsmasq[514]: read /etc/hosts - 5 addresses
    Mar 27 09:49:37 rpitesting dnsmasq[515]: Too few arguments.
    Mar 27 09:49:37 rpitesting systemd[1]: Started dnsmasq - A lightweight DHCP and caching DNS server.
    Mar 27 09:50:33 rpitesting dnsmasq-dhcp[514]: DHCPREQUEST(wlan0) 192.168.100.138 f4:f2:6d:1e:07:52
    Mar 27 09:50:33 rpitesting dnsmasq-dhcp[514]: Ignoring domain iei.local for DHCP host name Puesto07
    Mar 27 09:50:33 rpitesting dnsmasq-dhcp[514]: DHCPACK(wlan0) 192.168.100.138 f4:f2:6d:1e:07:52 Puesto07
    Mar 27 10:00:27 rpitesting dnsmasq-dhcp[514]: DHCPREQUEST(wlan0) 192.168.100.138 f4:f2:6d:1e:07:52
    Mar 27 10:00:27 rpitesting dnsmasq-dhcp[514]: Ignoring domain iei.local for DHCP host name Puesto07
    Mar 27 10:00:27 rpitesting dnsmasq-dhcp[514]: DHCPACK(wlan0) 192.168.100.138 f4:f2:6d:1e:07:52 Puesto07

    pi@rpitesting:~ $ sudo systemctl status hostapd
    ● hostapd.service - LSB: Advanced IEEE 802.11 management daemon
    Loaded: loaded (/etc/init.d/hostapd; generated; vendor preset: enabled)
    Active: active (running) since Tue 2018-03-27 09:49:38 UTC; 13min ago
    Docs: man:systemd-sysv-generator(8)
    Process: 568 ExecStart=/etc/init.d/hostapd start (code=exited, status=0/SUCCESS)
    CGroup: /system.slice/hostapd.service
    └─574 /usr/sbin/hostapd -B -P /run/hostapd.pid /etc/hostapd/hostapd.conf

    Mar 27 09:50:33 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 IEEE 802.11: associated
    Mar 27 09:50:33 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 RADIUS: starting accounting session 5ABA13B2-000
    Mar 27 09:50:33 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 WPA: pairwise key handshake completed (RSN)
    Mar 27 10:00:01 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 WPA: group key handshake completed (RSN)
    Mar 27 10:00:25 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 IEEE 802.11: disassociated
    Mar 27 10:00:25 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 IEEE 802.11: associated
    Mar 27 10:00:25 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 IEEE 802.11: disassociated
    Mar 27 10:00:27 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 IEEE 802.11: associated
    Mar 27 10:00:27 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 RADIUS: starting accounting session 5ABA13B2-000
    Mar 27 10:00:27 rpitesting hostapd[574]: wlan0: STA f4:f2:6d:1e:07:52 WPA: pairwise key handshake completed (RSN)

    Report
  • Comment Link roboberry Monday, 26 March 2018 20:35 posted by roboberry

    Hi Carlos, Thank you. I don't know if Vincent resolved the issue but are you able to try it from a different device and also try changing the channel in the hostapd.conf file just in case of interference?

    The other option is when the hotspot is up, stop hostapd and run it manual and see what feedback it gives.
    enter: sudo systemctl stop hostapd
    then: sudo hostapd /etc/hostapd/hostapd.conf
    then try to connect your device again and see what feedback you get, add -d or -dd to see more detail, actually quite a lot :) sudo hostapd -d /etc/hostapd/hostapd.conf


    Also check dnsmasq is still running ok with sudo systemctl status dnsmasq it should say active in green and no errors in the lower text.

    just to confirm your changes
    /etc/dnsmasq.conf will have
    dhcp-range=192.168.100.150,192.168.100.200,255.255.255.0,12h

    and the autohotspotN script will be
    createAdHocNetwork()
    {
    ip link set dev "$wifidev" down
    ip a add 192.168.100.1/24 brd + dev "$wifidev"

    Let me know how you get on either way. If still an issue I will look into it further.

    Report
  • Comment Link Carlos Monday, 26 March 2018 15:21 posted by Carlos

    Hi,

    First of all thank you for such a good pice of work.

    I am experiencing the same issue as Vincent mentioned previously - I cannot connect via SSH to the RPi after it creates the hotspot and I connect to it. Any ideas on what I'm doing wrong? The only thing I altered from your guide for compatibility reasons is the RPi IP (192.168.100.1 instead of 192.168.50.5) and the range of DHCP to match this network.

    Thanks in advance!

    Report
  • Comment Link roboberry Tuesday, 06 March 2018 20:48 posted by roboberry

    Hi Guy, Good to see the script is being put to good use. Thanks for the reference in the script.

    Not something I have needed to look at but my initial thoughts would be to create a new function that checks /sys/class/net/ for devices starting with e and capture the name. Then determine if you have a valid connection to a router, ip command or the options found in the /sys/class/net/folder. This returns true or false.

    I would call the new function after the FindSSID call and capture the result in a variable.
    Then in the main IF sequence add in a elseif that if eth0 (or similar device name) is true then print "Ethernet up"

    The logic would then be that, wifi is activated if available ssid found, if no wifi found check LAN variable is True then do no more, if Lan variable is False continue to the hotspot creation.

    If you don't have much luck let me know via email and I will look into it further.

    Report
  • Comment Link Guy Sheffer Tuesday, 06 March 2018 08:12 posted by Guy Sheffer

    Hey!
    Thanks for the guide! Creator of CustomPiOS here, I made for it an auto-hotspot module. So now any distro can now use this.
    Source is here: https://github.com/guysoft/CustomPiOS/tree/CustomPiOS/src/modules/auto-hotspot

    I have a question - what should I add to the script so when an ethernet cable is connected it would not bring up the hotspot? I want to set an option only if the device failed to connect to a network then it will bring up the network and let you set it up.
    That way CustomPiOS can make distros with an auto-hotspot to set them up.

    Report
  • Comment Link roboberry Wednesday, 21 February 2018 20:40 posted by roboberry

    Hi Kit, is your issue just when your PI connects to your router or an issue in hotspot mode?

    I have a similar problem with my PI3 connecting to my android tablet, the ip just won't authorise. But other devices will happily connect without an issue. Also If I take the SD card from the PI3 and put it in a Pi Zero W or PI2 the android tablet connects fine. So the issue for me is just between the PI3 and my android tablet the script and setup is fine.

    if you are having an issue with connecting to your router double check you have the 3 lines at the top of your wpa_supplicant.conf file. It should be something like
    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    country=GB

    Check that dnsmasq is not active with sudo systemctl status dnsmasq, it should show it is not active (dead)

    If thats fine add; nohook wpa_supplicant
    to the bottom of the /etc/dhcpcd.conf file. This will allow the autohotspot script to start network wifi.

    Report
  • Comment Link Kit Wednesday, 21 February 2018 02:47 posted by Kit

    I have most of this setup, but the Wifi network keeps disconnecting and reconnecting every few seconds.

    Report
  • Comment Link Roboberry Thursday, 08 February 2018 21:46 posted by Roboberry

    Hi Vincent, are you able to try from a different device just to confirm it's not just an issue between the pi and the phone. I use an android tablet and someone get delays before they see each other, but other devices connect ok.

    Another possible issue could be interference so maybe change the channel in the /etc/hostapd.conf file from 6 to say to 3.
    Let me know how you get on and i will look into it further.

    Report
  • Comment Link vincent Thursday, 08 February 2018 07:03 posted by vincent

    Hi, Thanks for these great scripts!

    I follow the steps and when under autospot mode, my phone can get an ip address from pi, but can not ping the pi's IP address(192.168.50.5) or ssh to the pi. But if I try to ping my phone's address on the pi, then the network will be ok, both ping and ssh starts to work. No error from output of systemctl status dnsmasq or hostapd. Does anyone have an idea ? thanks!

    Report
  • Comment Link roboberry Tuesday, 30 January 2018 20:05 posted by roboberry

    Hi Jason, Not sure why you don't have a sysctl.conf file, are you using Raspbian Jessie or Stretch? Just check you have a /etc/sysctl.d folder. you can create a new /etc/sysctl.conf file and just add net.ipv4.ip_forward=1 and it should work. In the manual it lists other locations the conf file can be found, enter man sysctl.conf

    Could you let me know what the wifi icon is doing if it is not the double arrows and what does it say when the mouse is put on it.
    Is the network mode working ok and connecting to your router?
    While attempting hotspot mode check the status of dnsmasq and hostapd with
    sudo systemctl status dnsmasq and sudo systemctl status hostapd and check for any errors.
    Also what does the autohotspotN script report when it is run manually?

    The timer is not required and won't cause any issues.

    Let me know what results you get and I will look into this further

    Report
  • Comment Link jason Monday, 29 January 2018 09:27 posted by jason

    HI Roboberry
    Ive added all the scripts etc and still not getting the access point to show double arrows.
    Ive tried the trouble shooting and no go with teh SSID test to "off"

    I havnt set up the timer, would this need to be setup.
    cheers
    jason

    Report
  • Comment Link Jason Monday, 29 January 2018 06:02 posted by Jason

    Hi Rob,
    Great script and exactly what I was needing but you've heard this before.

    When I opened the file to edit:
    sudo nano /etc/sysctl.conf
    It was blank, what should have been in there?
    I'm using the latest rasbian and have done updates etc as per start.
    Cheers Jason

    Report
  • Comment Link roboberry Sunday, 21 January 2018 20:35 posted by roboberry

    Hi Z-Wolf, thanks you for sharing your firewall friendly commands. Unfortunately that's is one of the issues, if ip-tables are already setup it will probably cause a conflict. It will be a useful addition, I will add them in to the article as additional notes. Thanks

    Report
  • Comment Link Z-WolF Sunday, 21 January 2018 01:56 posted by Z-WolF

    Hi there,

    I have firewalld on my raspi3, and it did not wanted to play nice with the iptables commands on the script. So i translated them to firewall-cmd.

    createAdHocNetwork()
    {
    ... Line 42 onwards
    #iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
    firewall-cmd --direct -add-rule ipv4 nat POSTROUTING 0 -o eth0 -j MASQUERADE
    #iptables -A FORWARD -i eth0 -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
    firewall-cmd --direct --add-rule ipv4 filter FORWARD 0 -i eth0 -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
    #iptables -A FORWARD -i "$wifidev" -o eth0 -j ACCEPT
    firewall-cmd --direct --add-rule ipv4 filter FORWARD 0 -i "$wifidev" -o eth0 -j ACCEPT
    ...
    }

    KillHotSpot()
    {
    ... Line 56 or 60 (may vary depending on lines above)
    firewall-cmd --direct --remove-rule ipv4 nat POSTROUTING 0 -o eth0 -j MASQUERADE
    #iptables -D FORWARD -i eth0 -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
    firewall-cmd --direct --remove-rule ipv4 filter FORWARD 0 -i eth0 -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
    #iptables -D FORWARD -i "$wifidev" -o eth0 -j ACCEPT
    firewall-cmd --direct --remove-rule ipv4 filter FORWARD 0 -i "$wifidev" -o eth0 -j ACCEPT
    ...
    }

    Added the removal of MASQUERADE otherwise throws a warning that rule already exists when hotspot -> wifi client -> hotspot dance.

    Hope it helps.

    Report
  • Comment Link roboberry Friday, 19 January 2018 11:10 posted by roboberry

    Hi Fredo
    My Nexus 7 use to do that which is what I was using but when the AP got dropped from KitKat onwards, I had to come up with a different solution which is where the script came from. But I'm glad you have found a suitable solution for you.

    Report
  • Comment Link fredo Thursday, 18 January 2018 09:14 posted by fredo

    Hi, roboberry, thnx for the info.
    found a simpler solution: create a ap on my android, let kali connect to ap. that does it for me.

    Report
  • Comment Link Roboberry Wednesday, 17 January 2018 15:16 posted by Roboberry

    Hi fredo, It has only been tested on Raspbian Jessie and Raspbian Stretch. A user did try using a previous version on Kali but I think he had issues generating the hotspot.
    Raspbians network is managed by the dhcpcd.service so if Kali uses a network manager then it probably doesn't work. If sudo systemctl status dhcpcd shows that dhcpcd starts wpa_supplicant, the /etc/network/interfaces file is not used and then there may be a chance but I can't confirm it will.
    If you do give it a go it would be good to know if it works ok.

    Report
  • Comment Link fredo Wednesday, 17 January 2018 12:38 posted by fredo

    Hi!
    Any idea if this works on Kali Linux/Arm too?

    Report
  • Comment Link roboberry Sunday, 07 January 2018 20:46 posted by roboberry

    HI JWBlank, If you run the script manually with sudo /usr/bin/autohotspotN it should switch as the script takes down the network settings. I presume the autohotspot service is not running as the network is brought up by the system as normal at boot. The script assess the situation and changes to a hotspot at that point, so the autohotspotN script has not run or there is an error.
    So either the service is not running, redo sudo systemctl enable autohotspot
    the scripts permissions are not ok, sudo chmod +x /usr/bin/autohotspotN
    or there is an error causing the script not to run. Running it manually with sudo /usr/bin/autohotspotN should highlight any issues there.
    or use sudo systemctl status autohotspot to get the service status.

    Let me know what issues you find and I will do my best to get you up and running.

    Report
  • Comment Link JWBlank Sunday, 07 January 2018 01:33 posted by JWBlank

    This is exactly what I've been looking for. Unfortunately, I'm stuck getting it to start the hotspot. As suggested, I've edited /etc/wpa_supplicant/wpa_supplicant.conf to read "Myssidoff". But when I login, I'm still automatically connected to Myssid. Is it possible NetworkManager is taking over?

    Report
  • Comment Link roboberry Thursday, 28 December 2017 09:13 posted by roboberry

    Hi Islam, Your welcome. Thanks for the tip. It is set for the most widely used settings but, it makes sense to add in N as well now. I will add that to my to do list

    Report
  • Comment Link roboberry Thursday, 28 December 2017 09:08 posted by roboberry

    Hi Shibu, Thank you and I'm glad it is useful to you.

    Report
  • Comment Link Shibu Monday, 25 December 2017 23:51 posted by Shibu

    Hi,
    Great idea, something exactly what I was looking for. Appreciate spending time in documenting this in detail. It worked perfectly on my pi zero.
    Thank You!

    Report
  • Comment Link Islam Mansour Saturday, 23 December 2017 23:49 posted by Islam Mansour

    Thanks so much for such awesome tutorial, I tried it and it works really well, that is what I needed.

    I wanted to mention to increase the speed of the wifi, this option can be used to enable the 802.11n support.
    Simply, add this following line to at the end of this file:
    sudo nano /etc/hostapd/hostapd.conf

    ieee80211n=1 # 802.11n support

    Report
  • Comment Link roboberry Sunday, 17 December 2017 23:53 posted by roboberry

    Hi Marc, The wpassid line will return a single string containing all ssids in wpa_supplicant with a comma between each entry. With these two lines
    IFS=","
    ssids=($wpassid)
    ssids gets a list of each ssid from the string.

    There will be an issue if in the wpa_supplicant file the ssid has no quote marks
    ie ssid=myssid rather than ssid="myssid"
    which will return a blank string. Also does your ssid have any other characters other than spaces letters and numbers?

    some users have not had the correct wpa_supplicant file which has caused similar issues. Does your /etc/wpa_supplicant/wpa_supplicant.conf file start with
    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    country=GB

    with country as your country if not GB.

    to see what is being returned from wpa_supplicant after IFS=$IFSdef #reset back to defaults
    enter this line

    echo "wpassid returns " $wpassid

    then when you run the autohotspot script manually you can see what it picks up.

    Let me know how you get on.

    Report
  • Comment Link Marc Sunday, 17 December 2017 07:17 posted by Marc

    Hi, Love your script, exactly what I was looking for.


    there is one small part I cannot get to work, retrieving the list of known ssids from wpa_supplicant.conf.

    I found the workarround by manually declaring my networks, but i would like the program to work as written :)

    I tried to find out why by dissecting this command

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

    on the command line all this returns is a comma followed by the prompt. I think this is because of the ORS statement in the second awk command. Leaving that statement out does return a list of the ssids. However, this list cannot be processed in the rest of the script because I think it expects a single line.

    could you help me out?

    cheers,

    Marc

    Report
  • Comment Link Roboberry Sunday, 10 December 2017 11:06 posted by Roboberry

    Hi Greg, I have just checked out your comment from yesterday on a pi and have tried a few things but i can't replicate the issue. The lines you commented would only run if your ssid is being broadcast, hostapd is not running, so no hotspot is running and no ip has been assigned to wlan0 by a router.
    If your pi is getting the 169.254 ip then the status ip address may be not available which will cause it to run the lines you commented.

    Run wpa_cli -i status wlan0 , while the network is up. You should see a line ip_address, that's what is available when your router issues an ip. Until that point the line won't appear.

    Are you getting the ip from your router or the 169.254 ip still?

    Report
  • Comment Link Greg Saturday, 09 December 2017 22:12 posted by Greg

    I have just tried the following:
    -I deleted my network from wpa_supplicant.conf
    -reboot -> starts in hotspot mode
    -I use my webinterface to add the network to wpa_supplicant.conf again
    -the website automatically runs /usr/bin/autohotspot (so I do not reboot)
    -shuts down the hotspot and turns on the wifi
    -Pi has internet access, everything works normally

    I think, in that case the lines I commented out do not matter because that branch of the if statement is not executed. It's weird - but it works.

    Report
  • Comment Link Greg Saturday, 09 December 2017 21:45 posted by Greg

    Hi,

    in my /etc/wpa_supplicant/wpa_supplicant.conf file, the order of the first three lines is different:

    country=GB
    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1

    also I do not have this line: key_mgmt=WPA-PSK, just the ssid and pwd.

    My /etc/.network/interfaces file does not have a config for wlan0 or an entry for wpa_supplicant.

    I'll try the rest of your suggestions.
    Cheers,
    Greg

    Report
  • Comment Link roboberry Saturday, 09 December 2017 21:15 posted by roboberry

    Hi Greg, from your dhcpcd logs it shows wlan0: DHCP lease expired, this is why you are getting a 169.254. ip. The lease is managed by the router and the dhcp server. What should happen is each time you are issued an ip it is valid for a period of time such as 12 hours or 24 hours. When the wifi device is off and then brought back up the lease should be renewed. Your pi is not renewing the ip lease so it defaults to a local one. This is not the cause of the autohotspot script because all it does is take down wifi and bring it back up again.

    The lines you have disabled would cause no wifi to be generated when you go from hotspot to wifi. So you may have wpa_supplicant running twice on your pi from some other network config. I presume your /etc/.network/interfaces file has no config for wlan0 or an entry for wpa_supplicant?

    If you enter the command sudo dhclient -v you should get a line with your IP and renewal in 41568 seconds. the seconds may will be different. If this is really low then your lease will expire while your pi is active.

    if you do sudo dhclient -v -r it should release the ip and create a new lease.
    Try this with the autohotspot script enabled and disabled.

    The file /var/lib/dhcp/dhclient.leases should give you some info on current ip lease times.

    and sudo grep dhclient /var/log/syslog should tell you more on what it happening with your dhcp client.

    You can take down and bring up with the following commands to see if your lease is being renewed with the autohotspot script disabled.
    ip link set dev wlan0 down
    ip link set dev wlan0 up

    But something is not working properly on your network setup outside of the changes from the article. Disabling those lines should cause no network wifi from a hotspot on a standard network setup and have no effect if the wifi is already active.
    In normal use the wifi device is not brought down so you never see the effect of the lease not renewing when it brought back up.

    Can you confirm you /etc/wpa_supplicant/wpa_supplicant.conf file has the correct lines at the top of the file. As missing lines will cause issues

    It should look like this but the country different if you are not in the UK

    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    country=GB

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


    Hopefully this highlight an underlying issue.

    Report
  • Comment Link Greg Friday, 08 December 2017 23:17 posted by Greg

    Hi,

    after a lot of headscratching, I commented two lines from your autohotspot script:

    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

    Now everything works, both hotspot and client mode!

    Cheers,
    Greg

    Report
  • Comment Link Greg Thursday, 07 December 2017 20:09 posted by Greg

    Hi, this is the output without the autohotspotN script:
    sudo systemctl status dhcpcd
    ● dhcpcd.service - dhcpcd on all interfaces
    Loaded: loaded (/lib/systemd/system/dhcpcd.service; enabled; vendor preset: enabled)
    Active: active (running) since Thu 2017-12-07 20:17:26 CET; 49min ago
    Process: 327 ExecStart=/usr/lib/dhcpcd5/dhcpcd -q -b (code=exited, status=0/SUCCESS)
    Main PID: 356 (dhcpcd)
    CGroup: /system.slice/dhcpcd.service
    ├─356 /sbin/dhcpcd -q -b
    └─470 wpa_supplicant -B -c/etc/wpa_supplicant/wpa_supplicant.conf -iwlan0 -Dnl80211,wext

    Dec 07 21:03:03 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1
    Dec 07 21:04:15 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1
    Dec 07 21:05:17 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1
    Dec 07 21:05:52 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1
    Dec 07 21:05:56 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1
    Dec 07 21:05:59 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1
    Dec 07 21:06:02 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1
    Dec 07 21:07:16 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1
    Dec 07 21:07:20 raspberrypi dhcpcd[356]: wlan0: Router Advertisement from fe80::1

    and this is the output with autohotspotN script in client mode:
    sudo systemctl status dhcpcd
    ● dhcpcd.service - dhcpcd on all interfaces
    Loaded: loaded (/lib/systemd/system/dhcpcd.service; enabled; vendor preset: enabled)
    Active: active (running) since Thu 2017-12-07 20:02:36 CET; 3min 18s ago
    Process: 374 ExecStart=/usr/lib/dhcpcd5/dhcpcd -q -b (code=exited, status=0/SUCCESS)
    Main PID: 383 (dhcpcd)
    CGroup: /system.slice/dhcpcd.service
    ├─383 /sbin/dhcpcd -q -b
    └─472 wpa_supplicant -B -c/etc/wpa_supplicant/wpa_supplicant.conf -iwlan0 -Dnl80211,wext

    Dec 07 20:02:42 raspberrypi dhcpcd[383]: wlan0: adding address fe80::4123:a746:4449:c48b
    Dec 07 20:02:42 raspberrypi dhcpcd[383]: wlan0: soliciting an IPv6 router
    Dec 07 20:02:43 raspberrypi dhcpcd[383]: wlan0: rebinding lease of 192.168.1.100
    Dec 07 20:02:48 raspberrypi dhcpcd[383]: wlan0: probing for an IPv4LL address
    Dec 07 20:02:48 raspberrypi dhcpcd[383]: wlan0: DHCP lease expired
    Dec 07 20:02:48 raspberrypi dhcpcd[383]: wlan0: soliciting a DHCP lease
    Dec 07 20:02:52 raspberrypi dhcpcd[383]: wlan0: using IPv4LL address 169.254.87.255
    Dec 07 20:02:52 raspberrypi dhcpcd[383]: wlan0: adding route to 169.254.0.0/16
    Dec 07 20:02:52 raspberrypi dhcpcd[383]: wlan0: adding default route

    Report
  • Comment Link roboberry Wednesday, 06 December 2017 23:19 posted by roboberry

    Hi Greg, The IP should be the one issued by your router usually in the range 192.168.#.# but it seems that an ip address starting with 169.254.#.# is when there is no dhcp server running so the device assigns a local ip to itself. If you do a search for: linux ip starting with 169.254 there are a few discussions about it.
    When it goes into hotspot mode it will generate a 169.254 ip along with the 192.168.50.5 ip but it always disappears when the wifi network comes up. So for some reason your pi's dhcp server is not working right. I have tried various changes to the setup in the dhcpcd.conf file, adding config to /etc/network/interfaces file and enabling dnsmasq by default but have been unable to replicate your issue.

    you could try sudo systemctl status dhcpcd and see if you get any errors.
    also you can take out the line interface wlan0 in /etc/dhcpcd.conf it's not required but won't be causing the issue. Turns out to be a red herring in a development bug fix.

    Have you installed any other software for networking that may be conflicting?

    let me know if you make any progress and I will help where i can.

    Report
  • Comment Link Greg Wednesday, 06 December 2017 21:54 posted by Greg

    Thank you for your quick reply. I had some time to try different things and I noticed that in client mode (using your script), my pi gets a very strange IP address, that does not look like the one it normally gets:

    wlan0: flags=4163 mtu 1500
    inet 169.254.87.255 netmask 255.255.0.0 broadcast 169.254.255.255
    inet6 fe80::4123:a746:4449:c48b prefixlen 64 scopeid 0x20
    ether b8:27:eb:55:56:da txqueuelen 1000 (Ethernet)
    RX packets 255 bytes 31895 (31.1 KiB)
    RX errors 0 dropped 0 overruns 0 frame 0
    TX packets 393 bytes 47206 (46.0 KiB)
    TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

    If I do ssh pi@169.254.87.255 instead of ssh pi@raspberrypi.local, it connects instantaneously. However, things like:
    sudo apt-get update are still very slow.
    Does this ring any bell?

    I switched off IP-forwarding but that does not seem to make a difference.

    Report
  • Comment Link roboberry Saturday, 02 December 2017 22:55 posted by roboberry

    Hi Greg, seems a bit of a strange one. The script doesn’t make any changes to the system if network is available at boot time. So other than ip_forwarding on by default, which is disabled when the autohotspot script runs there is no changes.
    I run ssh -v .... on my set up.
    In your results the line "debug1: /etc/ssh/ssh_config line 52: Applying options for *" is line 19 for me which refers to Hosts *
    Line 52 for me is # RekeyLimit 1G 1h
    which doesn’t activate due to the # so maybe something to look into.

    But it seems odd that it's fine when when you have disabled the script. Try enabling ip_forwarding but not the autohostpost script and see how ssh works.
    Presuming you have no other setup or firewall thats is using IP rules. Otherwise the IP_forward dosn't do anything until the ip-tables are set.

    let me know if you have any luck. You could try the the other autohotspot setup and script on your pi, just to see if there may be something else conflicting as the Direct article is more basic.

    Report
  • Comment Link Greg Saturday, 02 December 2017 19:46 posted by Greg

    Thank you very much for this tutorial. It is exactly what I needed.
    I have a pi 3 with stretch. I followed every step and it works. But there are some problems:
    When the pi finds my wifi network and goes into client mode, I have problems connecting to it via ssh. The connection will eventually be established, but it takes ages. Also some other things do not work properly, e.g. youtube-dl, apt-get update, ...
    When the pi runs in ap mode, ssh works just fine.

    I reversed everything as you described and all is back to normal. However, I would really love to use your script. Do you have any idea what the problem might be?

    Here is some output from ssh when the pi runs in client mode, maybe it helps:

    ssh -v pi@raspberrypi.local
    OpenSSH_7.5p1, LibreSSL 2.5.4
    debug1: Reading configuration data /etc/ssh/ssh_config
    debug1: /etc/ssh/ssh_config line 52: Applying options for *
    debug1: Connecting to raspberrypi.local [fe80::4123:a746:4449:c48b%en1] port 22.
    debug1: connect to address fe80::4123:a746:4449:c48b%en1 port 22: Operation timed out
    debug1: Connecting to raspberrypi.local [169.254.87.255] port 22.
    debug1: Connection established.

    Report
  • Comment Link roboberry Friday, 03 November 2017 21:48 posted by roboberry

    Hi Dominaezzz, Thanks for the info. Having a blank wpa_supplicant file is fine, that doesn't cause an issue.

    Your dnsmasq output is fine, the lines you mention, dnsmasq[733]: using nameserver 8.8.8.8#53"
    "dnsmasq[733]: read /etc/hosts - 5 addresses"
    "dnsmasq[734]: Too few arguments."

    are the same as my output. I decided to do a system update this evening and now I am getting issues as well. My laptop will connect to the AP and eventually get internet through the access point but my android tablet won't hold a connection. So may be related to your issue. It was all working fine until the update.
    Check your hostapd status as well to see if that shows an issue.

    I will try and solve my issue which may be related :(

    Report
  • Comment Link Dominaezzz Friday, 03 November 2017 21:05 posted by Dominaezzz

    Everything seems okay.
    The output of dnsmasq status is:
    Nov 02 01:32:38 raspberrypi dnsmasq-dhcp[733]: DHCP, IP range 192.168.50.150 -- 192.168.50.200, lease time 12h
    Nov 02 01:32:38 raspberrypi dnsmasq-dhcp[733]: DHCP, sockets bound exclusively to interface wlan0
    Nov 02 01:32:38 raspberrypi dnsmasq[733]: using nameserver 8.8.8.8#53
    Nov 02 01:32:38 raspberrypi dnsmasq[733]: read /etc/hosts - 5 addresses
    Nov 02 01:32:38 raspberrypi dnsmasq[734]: Too few arguments.
    Nov 02 01:32:38 raspberrypi systemd[1]: Started dnsmasq - A lightweight DHCP and caching DNS server.
    Nov 02 01:38:09 raspberrypi dnsmasq-dhcp[733]: DHCPREQUEST(wlan0) 192.168.50.199 e4:a7:a0:45:e3:0e
    Nov 02 01:38:09 raspberrypi dnsmasq-dhcp[733]: DHCPACK(wlan0) 192.168.50.199 e4:a7:a0:45:e3:0e DOMINIC-LAPTOP
    Nov 02 01:46:09 raspberrypi dnsmasq-dhcp[733]: DHCPREQUEST(wlan0) 192.168.50.199 e4:a7:a0:45:e3:0e
    Nov 02 01:46:09 raspberrypi dnsmasq-dhcp[733]: DHCPACK(wlan0) 192.168.50.199 e4:a7:a0:45:e3:0e DOMINIC-LAPTOP

    Report
  • Comment Link Dominaezzz Thursday, 02 November 2017 22:44 posted by Dominaezzz

    Also, I forgot to mention I don't have any wifi networks setup in my wpa_supplicant file because I didn't require it to connect to WiFi at all unless I can make it a wifi extender. I wanted the AP to always show.

    Report
  • Comment Link Dominaezzz Thursday, 02 November 2017 22:36 posted by Dominaezzz

    Hello again,
    Everything seems to be correct.
    The only thing that raised and eyebrow was the status of DNSmasq.
    The service is still active (running) but one of the lines says:

    "dnsmasq[733]: using nameserver 8.8.8.8#53"
    "dnsmasq[733]: read /etc/hosts - 5 addresses"
    "dnsmasq[734]: Too few arguments."

    Report
  • Comment Link Roboberry Thursday, 02 November 2017 09:41 posted by Roboberry

    Hi Dominaezzz, That sounds like DNSmasq is the issue. Have a look at the status with sudo systemctl status dnsmasq and also try sudo journalctl -xe
    This will tell you what is going on with it. During development of this I was getting the error; device not found wlan0.
    Double check that in /etc/dhcpcd.conf that the line added; interface wlan0 was not ending in a s, interfaces. You can guess how I know about that one :) and also double check the /etc/network/interfaces file has no device config in it.

    Let me know if that's not the issue and I will look into it further.

    Report
  • Comment Link Dominaezzz Thursday, 02 November 2017 01:44 posted by Dominaezzz

    Hello,
    Thank you for your post, found it very useful. Have been struggling with this on Stretch for a while now.
    I followed the instructions on a fresh install of Stretch and the access point shows up on my computer but there's no internet connection and I can't ssh into the pi using the IP address.

    Report
  • Comment Link roboberry Monday, 30 October 2017 21:47 posted by roboberry

    Hi Z, you're welcome. Thanks for confirming I didn't mess up the instructions :)

    Report
  • Comment Link Z Monday, 30 October 2017 21:39 posted by Z

    Confirmed it works perfectly. Very well done! This made my day.

    Report
  • Comment Link Z Monday, 30 October 2017 20:52 posted by Z

    Roboberry,

    Wow, thank you so much! I'm going to try it right now. I'll post back with any issues.

    Report
  • Comment Link roboberry Monday, 30 October 2017 20:01 posted by roboberry

    Hi Z, The new script is now available, ran out of time at the weekend. This should get you up and running. Has been working fine for me :)

    Report
  • Comment Link Z Monday, 30 October 2017 04:51 posted by Z

    Hey roboberry,

    Still no joy, that that might be due to the fact that I didn't start with a fresh pi install. Looking forward to the updated tutorial!

    Report
  • Comment Link roboberry Thursday, 26 October 2017 23:31 posted by roboberry

    hi Stephane, Thanks, i'm glad you have found it useful. you must be using Raspbian Jessie as it worked. I plan on updating the article this weekend with some changes so it will work on Raspbian Stretch as well. So if you upgrade to Stretch at some point, you will need to change your setup.

    Report
  • Comment Link Stéphane Thursday, 26 October 2017 09:44 posted by Stéphane

    Fantastic tutorial, thank you so much :) I didn't use the script cause I really just need the hotspot to use the pi as a local server to manage usb midi devices. I've set up an apache server, I just need to connect to the pi in wifi with my phone or tablet and I can interact in ssh or via the web server and some cgi.
    Great job!

    Report
  • Comment Link roboberry Tuesday, 24 October 2017 11:37 posted by roboberry

    Hi Z, I think recent updates to Hostapd and WPA_Supplicant have fixed the issues I was having with Stretch as I have it all working straight after the updates. I have one minor fix to make and will update the articles. Hopefully by the end of the week.
    For your issue on Stretch it sounds like the Hotspot and Wifi are both active, i.e. Hostapd and Dnsmasq are conflicting with wpa_supplicant.
    for this setup to work on stretch remove all the device setup from /etc/network/interfaces so it only shows the default 5 lines at the top.
    then in /etc/dhcpcd.conf at the bottom enter interface wlan0

    Wpa_supplicant is now run with the dhcpcd service but the entry in the interfaces file also runs it.

    If that doesn't help then check back later this week and the full setup will be posted plus the extra tweaks to the scripts.

    Report
  • Comment Link Z Tuesday, 24 October 2017 07:53 posted by Z

    Hey, great work here. As many have mentioned. Stretch is having some issues.

    I followed Popcorn's suggestion and changed a few lines in the code. However I'm still having issues getting the pi to connect to my home wifi. It runs the AP fine, however whenever I turn on my home wifi, the AP disappears like normal, but it has trouble connecting to the home wifi. It was able to reconnect once, however all other times I simply do not see it on my network.

    Anything you can suggest? Looking forward to that update for stretch! Thank you!

    Report
  • Comment Link Randall Burks Thursday, 19 October 2017 04:59 posted by Randall Burks

    Have been successfully using your hotspot this year via SSH for development. I am very interested in the following:
    1: On starting RPi 3B-Pixel, it unconditionally creates hotspot.
    2: While OS is running, if RPi 3B-Pixel detects my Android Phone Hotstpot (which has internet connection), dump your hotspot and connect to my Android Phone Hotspot so that it can get to the internet.
    3: While running, if RPi 3B-Pixel does not detect my Android Phone Hotspot, restart your hotspot.
    4: Would be nice if RPi 3B-Pixel detects my ethernet on my home network with internet, it overrides everything and uses ethernet to get to internet and SSH through ethernet.

    Note that all year I have been using your older version with great success to access via SSH over your hotspot and over ethernet and over WiFi. I just can't figure out how to integrate 1 thru 4 above. Any suggestions? This is very important for my project.

    Thank You
    BurksFamly

    Report
  • Comment Link Roboberry Wednesday, 11 October 2017 19:59 posted by Roboberry

    Hi Valerio, for now you would need Jessie for this script to work as you need. Unfortunately the foundation only offers stretch so unless you have a backup you may find it hard to go back to Jessie.

    Lakshmi,
    I'm hoping to get it working soon as i want it working for myself as well. So hopefully a new script wont be too far away.

    Graeme

    Report
  • Comment Link Lakshmi Narasimman Wednesday, 11 October 2017 16:41 posted by Lakshmi Narasimman

    Is fix ready for raspbian stretch

    Report
  • Comment Link Valerio Tuesday, 10 October 2017 18:57 posted by Valerio

    .... apologies, I just went through the script and noticed a new bit at the end to disable the script :)

    Report
  • Comment Link Valerio Tuesday, 10 October 2017 18:46 posted by Valerio

    Hi Graeme,

    Thanks for your reply! Essentially you're right, it turns out I'm using stretch and not jessie. However the script works in the sense that the RPi does set up its own hotspot and I can VNC into it (and WinSCP files to and from the RPi), which is what I needed it to do.

    However I now need to download some Arduino packages which require an internet connection, and this is where problems begin: I never quite checked whether the RPi could connect to a wifi on top of setting up the hotspot (the wifi at work is a bit of a nightmare for that), but I don't even see available networks on the RPi and just plugging in an ethernet cable makes no difference.

    I have tried the first troubleshooting example, but it didn't make a difference (and I suppose it won't if I'm using Stretch)
    Also, when I run the sudo /usr/bin/autohotspotN command, I get "Hotspot already active"

    ... so long story short, the script does the main thing I wanted it to do (the hotspot), but is there a way to 'temporarily' undo the changes described on this page, get the 'original' connectivity, download what I need and then 're-activate' the hotspot set up? One obvious way would be to follow the changes described here in reverse, but I was wondering if there was a quicker way.

    Also, can I just choose to install Raspbian Jessie as opposed to Raspbian Stretch if I were to re-install the OS? By the way, I'm using a RPi 3 Model B.

    Thanks again! In the meantime I will make the changes to the interfaces file

    Valerio

    Report

Additional information