Connect to Wi-Fi From Terminal on Ubuntu 22.04/20.04 with WPA Supplicant
In this tutorial, we are going to learn how to connect to Wi-Fi network from the command line on Ubuntu 22.04/20.04 server and desktop using wpa_supplicant. In a modern home wireless network, communications are protected with WPA-PSK (pre-shared key) as opposed to WPA-Enterprise, which is designed for enterprise networks. WPA-PSK is also known as WPA-Personal. wpa_supplicant is an implementation of the WPA supplicant component. A supplicant in wireless LAN is client software installed on end-user’s computer that needs to be authenticated in order to join a network.
Please note that you will need to install the wpa_supplicant
software before connecting to Wi-Fi, so you need to connect to Wired Ethernet first, which is done for just one time. If you don’t like this method, please don’t be mad at me. Maybe someday Ubuntu will ship wpa_supplicant
on a clean install.
Step 1: Find The Name of Your Wireless Interface And Wireless Network
Run iwconfig
command to find the name of your wireless interface.
iwconfig
wlan0
used to be a common name for wireless network interface on Linux systems without Systemd. Because Ubuntu uses Systemd, you are going to find that your wireless network interface is named something like wlp4s0
. You can also see that it’s not associated with any access point right now.
If your wireless interface isn’t shown, perhaps you need to bring it up with the following command.
sudo ifconfig wlp4s0 up
Then find your wireless network name by scanning nearby networks with the command below. Replace wlp4s0
with your own wireless interface name. ESSID is the network name identifier.
sudo iwlist wlp4s0 scan | grep ESSID
Step 2: Connect to Wi-Fi Network With WPA_Supplicant
Now install wpa_supplicant
on Ubuntu 22.04/20.04 from the default software repository.
sudo apt install wpasupplicant
We need to create a file named wpa_supplicant.conf
using the wpa_passphrase
utility. wpa_supplicant.conf
is the configuration file describing all networks that the user wants the computer to connect to. Run the following command to create this file. Replace ESSID and Wi-Fi passphrase with your own.
wpa_passphrase your-ESSID your-wifi-passphrase | sudo tee /etc/wpa_supplicant.conf
Note that in the above screenshot, I wrapped my ESSID with double-quotes, because my ESSID contains whitespace.
The output of wpa_passphrase
command will be piped to tee
, and then written to the /etc/wpa_supplicant.conf
file. Now use the following command to connect your wireless card to wireless access point.
sudo wpa_supplicant -c /etc/wpa_supplicant.conf -i wlp4s0
The following output indicates your wireless card is successfully connected to an access point.
Successfully initialized wpa_supplicant wlp4s0: SME: Trying to authenticate with c5:4a:21:53:ac:eb (SSID='LinuxBabe.Com Network' freq=2437 MHz) wlp4s0: Trying to associate with c5:4a:21:53:ac:eb (SSID='LinuxBabe.Com Network' freq=2437 MHz) wlp4s0: Associated with c5:4a:21:53:ac:eb wlp4s0: CTRL-EVENT-SUBNET-STATUS-UPDATE status=0 wlp4s0: WPA: Key negotiation completed with c5:4a:21:53:ac:eb [PTK=CCMP GTK=CCMP] wlp4s0: CTRL-EVENT-CONNECTED - Connection to c5:4a:21:53:ac:eb completed [id=0 id_str=]
Note that if you are using Ubuntu desktop edition, then you need to stop Network Manager with the following command, otherwise it will cause a connection problem when using wpa_supplicant.
sudo systemctl stop NetworkManager
And disable NetworkManager auto-start at boot time by executing the following command.
sudo systemctl disable NetworkManager-wait-online NetworkManager-dispatcher NetworkManager
By default, wpa_supplicant runs in the foreground. If the connection is completed, then open up another terminal window and run
iwconfig
You can see that the wireless interface is now associated with an access point.
You can press CTRL+C
to stop the current wpa_supplicant process and run it in the background by adding the -B
flag.
sudo wpa_supplicant -B -c /etc/wpa_supplicant.conf -i wlp4s0
Although we’re authenticated and connected to a wireless network, we don’t have an IP address yet. To obtain a private IP address from DHCP server, use the following command:
sudo dhclient wlp4s0
Now your wireless interface has a private IP address, which can be shown with:
ip addr show wlp4s0
Now you can access the Internet. To release the private IP address, run
sudo dhclient wlp4s0 -r
Connecting to Hidden Wireless Network
If your wireless router doesn’t broadcast ESSID, then you need to add the following line in /etc/wpa_supplicant.conf
file.
scan_ssid=1
Like below:
network={ ssid="LinuxBabe.Com Network" #psk="12345qwert" psk=68add4c5fee7dc3d0dac810f89b805d6d147c01e281f07f475a3e0195 scan_ssid=1 }
Step 3: Auto-Connect At Boot Time
To automatically connect to wireless network at boot time, we need to edit the wpa_supplicant.service
file. It’s a good idea to copy the file from /lib/systemd/system/
directory to /etc/systemd/system/
directory, then edit the file content, because we don’t want a newer version of wpa_supplicant
to override our modifications.
sudo cp /lib/systemd/system/wpa_supplicant.service /etc/systemd/system/wpa_supplicant.service
Edit the file with a command-line text editor, such as Nano.
sudo nano /etc/systemd/system/wpa_supplicant.service
Find the following line.
ExecStart=/sbin/wpa_supplicant -u -s -O /run/wpa_supplicant
Change it to the following. Here we added the configuration file and the wireless interface name to the ExecStart
command.
ExecStart=/sbin/wpa_supplicant -u -s -c /etc/wpa_supplicant.conf -i wlp4s0
It’s recommended to always try to restart wpa_supplicant when failure is detected. Add the following right below the ExecStart
line.
Restart=always
If you can find the following line in this file, comment it out (Add the # character at the beginning of the line).
Alias=dbus-fi.w1.wpa_supplicant1.service
Save and close the file. (To save a file in Nano text editor, press Ctrl+O
, then press Enter
to confirm. To exit, press Ctrl+X
.) Then reload systemd.
sudo systemctl daemon-reload
Enable wpa_supplicant service to start at boot time.
sudo systemctl enable wpa_supplicant.service
We also need to start dhclient
at boot time to obtain a private IP address from DHCP server. This can be achieved by creating a systemd service unit for dhclient
.
sudo nano /etc/systemd/system/dhclient.service
Put the following text into the file.
[Unit] Description= DHCP Client Before=network.target After=wpa_supplicant.service [Service] Type=forking ExecStart=/sbin/dhclient wlp4s0 -v ExecStop=/sbin/dhclient wlp4s0 -r Restart=always [Install] WantedBy=multi-user.target
Save and close the file. Then enable this service.
sudo systemctl enable dhclient.service
How to Obtain a Static IP Address
If you want to obtain a static IP address, then you need to disable dhclient.service
.
sudo systemctl disable dhclient.service
We need to use netplan to configure static IP address on Ubuntu 22.04/20.04. Create a configuration file under /etc/netplan/
.
sudo nano /etc/netplan/10-wifi.yaml
Add the following lines to this file. Replace 192.168.0.102
with your preferred IP address. Please be careful about the indentation. An extra space would make the configuration invalid.
network: ethernets: wlp4s0: dhcp4: no addresses: [192.168.0.102/24] gateway4: 192.168.0.1 version: 2
Save and close the file. Then apply the configurations.
sudo netplan apply
You can also turn on the --debug
option if it doesn’t work as expected.
sudo netplan --debug apply
If there are other .yaml
files under /etc/netplan/
directory, then netplan
will automatically merge configurations from different files. netplan
uses systemd-networkd
as the backend network renderer. It’s recommended to configure the wpa_supplicant.service
runs before systemd-networkd.service
, so the system will first associate with a Wi-Fi access point, then obtain a private IP address.
sudo nano /etc/systemd/system/wpa_supplicant.service
Find the following line.
Before=network.target
Change it to:
Before=network.target systemd-networkd.service
Save and close the file.
Another way to obtain a static IP address is by logging into your router’s management interface and assigning a static IP to the MAC address of your wireless card, if your router supports this feature.
Using a Hostname to Access Services on Ubuntu
Actually, you don’t have to obtain a static IP address for your Ubuntu box. Ubuntu can use mDNS (Multicast DNS) to announce its hostname to the local network and clients can access services on your Ubuntu box with that hostname. This hostname can always be resolved to the IP address of your Ubuntu box, even if the IP address changes.
In order to use mDNS, you need to install avahi-daemon, which is an open-source implementation of mDNS/DNS-SD.
sudo apt install avahi-daemon
Start the service.
sudo systemctl start avahi-daemon
Enable auto-start at boot time.
sudo systemctl enable avahi-daemon
Avahi-daemon listens on UDP 5353, so you need to open this port in the firewall. If you use UFW, then run the following command.
sudo ufw allow 5353/udp
Then you should set a unique hostname for your Ubuntu box with the hostnamectl
command. Replace ubuntubox with your preferred hostname, which should not be already taken by other devices in the local network.
sudo hostnamectl set-hostname ubuntubox
Now restart avahi-daemon.
sudo systemctl restart avahi-daemon
If you check the status with
systemctl status avahi-daemon
you can see the mDNS hostname, which ends with the .local
domain.
On the client computer, you also need to install an mDNS/DNS-SD software.
- Linux users should install
avahi-daemon
. - Windows users need to enable the Bonjour service by either installing the Bonjour print service or installing iTunes.
- On macOS, Bonjour is pre-installed.
Now you can access services by using the ubuntubox.local
hostname, eliminating the need to check and type IP address.
Unblock Wifi on Raspberry Pi
The Ubuntu ARM OS for Raspberry Pi blocks wireless interface by default. You need to unblock it with:
sudo rfkill unblock wifi
To unblock it at boot time, create a systemd service unit.
sudo nano /etc/systemd/system/unblock-wifi.service
Add the following lines to it.
[Unit] Description=RFKill Unblock WiFi Devices Requires=wpa_supplicant.service After=wpa_supplicant.service [Service] Type=oneshot ExecStart=/usr/sbin/rfkill unblock wifi ExecStop= RemainAfterExit=yes [Install] WantedBy=multi-user.target
Save and close the file. Enable auto-start at boot time.
sudo systemctl enable unblock-wifi
I found that the unblock-wifi.service
should run after the wpa_supplicant.service
starts, otherwise it can’t unblock wifi. Note that if you have installed a desktop environment, there’s probably a network manager running that can interfere with the connection. You need to disable it. For example, I use the lightweight LXQT desktop environment on Raspberry Pi (sudo apt install lubuntu-desktop
) and need to disable connman.service and NetworkManager.service.
sudo systemctl disable connman.service NetworkManager.service
Recommended Reading
Multiple Wi-Fi Networks
The /etc/wpa_supplicant.conf
configuration file can include multiple Wi-Fi networks. wpa_supplicant will automatically select the best network based on the order of network blocks in the configuration file, network security level, and signal strength.
To add a second Wi-Fi network, run
wpa_passphrase your-ESSID your-wifi-passphrase | sudo tee -a /etc/wpa_supplicant.conf
Note that you need to use the -a
option with the tee
command, which will append, instead of deleting the original content, the new Wifi-network to the file.
Wi-Fi Security
Do not use WPA2 TKIP or WPA2 TKIP+AES as the encryption method in your Wi-Fi router. TKIP is not considered secure anymore. You can use WPA2-AES as the encryption method.
You should use a very long password for WPA2 networks. I use the pwgen
command line tool to generate a random 63-character password.
sudo apt install pwgen pwgen -sy 63
pwgen
will print a list of random passwords. You need to choose one of the lines as your password.
PjF<OUz/W0`t[6!%mcP1?wLo&"y+iCF7_48nJjv.@>/qT:3/F\>4k:_>)1lKf:I o*S+CEKf]I~\MudHu9}r%cjv@wE&^*7Wpuf5#%6y8"SlsaHlJ9;lCMYO6d"LHzz 093=t.'$g[!#twvgrY[t"d?J0!j9c\|el,;HhieC<gETlT=AK(z^T["w@o*kLsI h&agCTMcjFQ<6NIk43&QP3'0N]wc;R1Nv=#)7cDlbdIl|or#3SM&nfU><~g;gb/ v`"<U=bkl0WJ\@~W5Gj*r?Khmgc_n@'`'qmRqg;"/Kz$$nP4G_/h%=MU|=ksp1" Q}p4UcN*4)JNLox?!b(~7znsKARI]j{N5v5s=DcUuVuE,_H}N):/^P@<eFxlqIP zsX#nkGWX]-GT1&-8g6E8$htcv_sq7V7DWTRg.^r].$w"=>vswoxcV_Yi#Ji=Pw PVhk7]=kBMO3]S;Bb<`\?]CC5=|Lt/t%Sb>PaLLC3>3u!zguCcd$1P!.a@CR/cB 4Lgi3ZB(pGaM+(X#f."A6HC3lSbJQPUTJ5NWCWlG3q9[nB9#Z##sR(<VPi&IsL| R]@klw4qRf&=(`/jcC6KcsQ~)*Mz7qJtfv.G7Ha}M@/hM]wv^=`nQAe$T.;{b}b (M0^bIXjGNHdXwH.\C(b8`f3T}mU?C_v+PCz6>bACEV'<p*7%bagbKbL?UxN$g7 L1]6EI=0}N[LF9OGk)|#fnaCMc@7o;?<5pQp;3nEKp/421Zd=`JZ"3=W{#m%Y>) "N*#43Nmf~R?i1<}vePGah;TU4_pJdg,tBSx-3T$;>dqYXA@1Hq3nwvAqX{dwgh ;Mhc7`G2ola&5FjoeiO9"$*%uE@i<}QL|";E2vkOY(Y4QNk5-<lI2`.}ZQ?lOXP eUV=}'h*08owz%?J"r+:j@V)*jDEZQ%:eK(j9w%L$e`T]`d6[\E-kWmLsClqO/c RY;2[88jqTjgg)gE5g[to8.$6rW45|cob~8i#jZt@Uf;wd0n`V2C#?Q}uL}i@@E 4jEZaxaw?rqFy8jVD@vlC(WE#Wxyu^aE#Y|x:=@yXk>A8utviqctR/D9Qe$VW[x cZ<yeyj&&h\'09mK}mS1JXV`;#0@c}rI&9`$Oz86Brd^kDmGokQy_pQQGR2gNEJ 2pmK"wLx<8]|*E*jEuYC]g-vaow-YJ,XR?0m"W|`^y"@7i~n47/#cunU:t3j/4M ;_"phXzS2YACUeJuX6c99l.H&tYOW(@Qoa1?BKg|dn`6C!S``POteF\)m\?p-J)
To make it easy for smartphone users to connect to your network, you can use the qrencode
command line utility to generate a QR code, which will be saved as wi-fi.png
file.
sudo apt install qrencode sudo qrencode -o wi-fi.png -s 10 'WIFI:S:your_ssid;T:WPA;P:your_password;;'
Then scan the QR code with your smartphone and you will be able to join the wireless network. I print this QR code with my printer and put it on my Wi-Fi router, so my guests can easily join my home network.
Wrapping Up
I hope this tutorial helped you connect Ubuntu 22.04/20.04 to Wi-Fi network from the command line with WPA Supplicant. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks 🙂
Nice tutorial!!
Are pass-phrases stored in clear on /etc/wpa_supplicant.conf?
Cheers!
The /etc/wpa_supplicant.conf file contains an encoded passphrase and a clear text passphrase, which is commented out. You can remove the line that contains your clear text passphrase.
So that’s how it’s done! I was using nmtui, which works great from my desktop machine, but wouldn’t work on a smaller Linux device running Ubuntu 18.04 headless server.
Thanks. It worked like a charm 🙂
Didn’t work for me! All good till I try to enable the service at start with
sudo systemctl enable wpa.supplicant.service
where I get the response
Failed to enable unit: File /etcsystemd/system/dbus-fi.wi.wpa_supplicant1.service already exists and is a smylink to /lib/systemd/system/wpa_supplicant.service
Comment out the following line in
/etc/systemd/system/wpa_supplicant.service
file.Reload systemd.
Then enable wpa_supplicant.
It works well for me, but in case I go to another place with Wi-Fi I have to do the same because, I try and I get the network of my house the name, what I want to know if I can connect to another Wi-Fi network that is not my home in this case the faculty and if that were the case I do the same or do I have to do something else?
I used the setup method described on this page (great instructions!) yesterday morning, then last night I wondered about connecting away from home — seemed to me that it would be cumbersome. This morning I looked at the Comments section here, and came upon [y]our question! (great minds, eh?)
OK, Googling “gui front end for wpa_supplicant”, I found this: wpa_gui — first, I read the write-up on the Arch Linux site (https://wiki.archlinux.org/index.php/WPA_supplicant), then I read the one on the Ubuntu site (http://manpages.ubuntu.com/manpages/bionic/man8/wpa_gui.8.html).
wpa_gui works like a champ! — with two provisos:
#1: Must be run as “root”
#2: Selecting “Disconnect” then “Connect” does not reacquire a DHCP address; for that, I had to manually run (as “root”) dhclient. Perhaps installing/running dhcpcd would eliminate the issue.
You can maintain the old-style naming of interfaces in many ways. The best is probably editing ‘/etc/default/grub’ and make sure that you change
to
and then run ‘update-grub’ with root privileges and then reboot. More details here:
https://askubuntu.com/questions/689070/network-interface-name-changes-after-update-to-15-10-udev-changes
It should be noted that the default service file in ubuntu 18 has wpa_supplicant set to start before dbus which is usually before the network card drivers are even loaded. If you have this problem and need your network card to start on boot, change the line that looks like:
After=dbus.service
to
After=network.service
and also remove (or add a # at the beginning of) the line that looks like:
#Before=network.target
That way the service will give your wifi network card a chance to start up before it tries to start wpa_supplicant.
Good tutorial. But doesn’t Ubuntu 18.04 and newer use netplan? Should netplan be used instead of running wpa_supplicant from systemd?
Hi, after struggling with netplan with my Wifi I found this guide.
Everything is working until i try to start dhclient at boot. Its not working. Any tips? (i am a newbee)
If I log in and go: sudo dhclient wlp4s0 i connect and everything is fine.
BR
Trond E
Check the logs of dhclient.service.
After boot it looks like this. Still no internet though. I see the server on router but no IP assigned.
When I manually start the DHCP Client everything is ok.
Just wondering. Can it be some kind of conflict with cloud-init and Network-Manager? Examening my start-up log the wlp5s0 looks to get an IP after wpa_supplicant is executed.
Cant figure this out. I still have to run dhclient manually after boot.
Can it also be some driver issues?
Cloud-init is intended to be used in cloud environments, which doesn’t have Wi-fi and NetworkManager. Why are you using the two at the same time? I did say that you need to stop and disable NetworkManager in this article.
I don’t know if cloud-init would conflict with WPA Supplicant.
From the journalctl log, your homeserver has successfully obtained an IP address.
FWIW, after purging clound-init and still having the auto-run of dhclient problem I took chance and added wlan0 device to the /etc/netplan/50-cloud-init.yaml file.
I only added
wlan0:
dhcp4: true
upon reboot the wifi interface had it’s IP address.
Makes me wonder if all that’s needed is the wpa_supplicant parts and adding to the netplan cloud-init yaml file.???
I had the same issue. The issue appears to be that the service stops (it seems to be connected to login in as a user) “ExecStop=/sbin/dhclient wlp4s0 -r” causes the IP to be released on the system. I don’t know if its good practice or not, but commenting out that line seems to have resolved the issue.
Thank you !!
You saved me, I was wondering what went wrong.
But I still want to understand though, if it causes an issue, why are we using ExecStop here ?
Bryan you are are life save man. I was also having the same issue.
Thank you Bryan.
Thanks for this great tutorial. I have followed the steps above and am able to connect to the wifi network. I am however running into issues getting the wifi adaptor to connect of boot.
The interface shows as up when an
is run but no IP address and it is not connected to the essid.
When I run
the ESSID is set to off/any and the Access Point is set to Not-associated.
Upon reboot I must run the following commands to get it to connect to the proper essid and get an IP address.
After this, all is up and running with no issues.
On reboot if I run
It shows as active (running) but shows the following failed messages in the log.
Additionally, on reboot, the dhclient.service status shows as loaded (dead) .
Thoughts?
Thanks so much mate super useful!
It didnt worked for me, stuck in this error
sudo wpa_supplicant -c /etc/wpa_supplicant.conf -i wlo1
Successfully initialized wpa_supplicant
Failed to open config file ‘/etc/wpa_supplicant.conf’, error: No such file or directory
Failed to read or parse configuration ‘/etc/wpa_supplicant.conf’
Make sure you have generated the /etc/wpa_supplicant.conf file with this command:
Hi,
It worked great in my Ubuntu Server 18.04.
Thank you.
I’m trying to connect a 19.10 program to my wifi without success. In going through these steps I receive error messages that include ifconfig (and rfkill) commands not found.
Just gone through this for Ubuntu Desktop LTS 18.04 with a Belkin USB adapter, and I am quite impressed (given my basic linux experience) that I got DHCP to connect to my BT hub with only one typo in my edits 😀
So all good with the ethernet cable disconnected, the system remains internet connected.
However after reboot I still need to manually reconnect DHCP.
The log file shows that my device is not recognized earlier in the sequence, but it is fine when the system comes up – connected to the router but no IP address until I prod it.
I am happy enough with that, although my daughter may object to opening a terminal and typing “sudo dhclient ….” before she can run Runescape !
Any suggestions on the possible sequencing change needed most welcome – I have already changed type=simple to type=forked and After=dbus.service to After=network.service.
I have two of these Belkin adapters so I also hope to get this running on my rpi3 running ubuntu MATE later.
Thanks for a great tutorial.
Update – this morning, without any further changes, the wi-fi connection has fully established from boot. So the only actual change was a power cycle – something I did not do yesterday after completing the edits. So, one happy daughter later on today 😀