Connect to Wi-Fi From Terminal on Debian 11/10 with WPA Supplicant
This tutorial is going to show you how to connect to Wi-Fi network from the command line on Debian 11/10 server and desktop using wpa_supplicant, which is an implementation of the supplicant component for the WPA protocol. 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 Debian will ship wpa_supplicant out of the box.
Step 1: Find The Name of Your Wireless Interface And Wireless Network
Run iwconfig command to find the name of your wireless interface.
wlan0 is a common name for a wireless network interface on Linux systems. On systemd-based Linux distros, you might have a wireless interface named wlp4s0 .
As you can see, the wireless interface isn’t associated with any access point right now. Then run the following command to bring up the wireless interface.
If you encounter the following error,
you need to unblock Wi-Fi with the following command.
Next, 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.

Step 2: Connect to Wi-Fi Network With WPA_Supplicant
Now install wpa_supplicant on Debian 11/10 from the default software repository.
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 (network name) and Wi-Fi passphrase with your own.

If your ESSID contains whitespace such as ( linuxbabe WiFi ), you need to wrap the ESSID with double-quotes ( «linuxbabe WiFi» ) in the above command.
The output of wpa_passphrase command will be piped to tee , and then written to the /etc/wpa_supplicant/wpa_supplicant.conf file. Now use the following command to connect your wireless card to the wireless access point.
The following output indicates your wireless card is successfully connected to an access point.
Note that if you are using Debian desktop edition, then you need to stop Network Manager with the following command, otherwise it will cause a connection problem when using wpa_supplicant.
And disable NetworkManager auto-start at boot time by executing the following command.
By default, wpa_supplicant runs in the foreground. If the connection is completed, then open up another terminal window and run
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.
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:
Now your wireless interface has a private IP address, which can be shown with:

Now you can access the Internet. To release the private IP address, run
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/wpa_supplicant.conf file.
Step 3: Auto-Connect At System 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.
Edit the file with a command-line text editor, such as Nano.
Find the following line.
Change it to the following. Here we added the configuration file and the wireless interface name to the ExecStart command.
It’s recommended to always try to restart wpa_supplicant when failure is detected. Add the following right below the ExecStart line.
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.
Enable wpa_supplicant service to start at boot time.
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 .
Put the following text into the file.
Save and close the file. Then enable this service.
How to Obtain a Static IP Address
If you want to obtain a static IP address, then you need to disable dhclient.service .
Create a network config file.
Add the following lines.
Save and close the file. Then create a .link file for the wireless interface.
Add the following lines in this file. You need to use your own MAC address and wireless interface name. This is to prevent the system from changing the wireless interface name.
Save and close the file. Then disable the networking.service and enable systemd-networkd.service , which will take care of networking.
You can now restart systemd-networkd to see if your configuration works.
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.
Recommended Reading:
Multiple Wi-Fi Networks
The /etc/wpa_supplicant.conf configuration file can include multiple Wi-Fi networks. wpa_supplicant automatically selects 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:
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.
Wrapping Up
I hope this tutorial helped you connect Debian 11/10 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
How to connect to WiFi from the command line?
Other posts seems to be addressing more complicated network connection issues from the command line.
The Unity panel Network indicator/button doesn’t respond too well sometimes — it keeps trying to connect to a network even when i click on «disconnect», stuff like that.
So I want to go command line for the control. I don’t like GUIs anyway.
Is there not some simple command line tool which can do something like the following?
![]()
4 Answers 4
I think you want to keep using managed interface (by NetworkManager). nmcli is a command‐line tool for controlling NetworkManager.
To see list of saved connections, use ( <SavedWiFiConn> )
To see list of available WiFi hotspots ( <WiFiSSID> )
To see list of interfaces ( <WifiInterface> )
Just change <WifiInterface> , <WiFiSSID> , <WiFiPassword> in the following commands to reflect your setup. If WiFi info already saved, easier way using <SavedWiFiConn> name of connection as it was saved in NetworkManager.
Ubuntu 16.04
Ubuntu 15.10 & previous
If your password isn’t automatically recognized type this:
Reference: man nmcli
![]()
nmtui ncurses solution
Great interactive ncurses network manager option:
If for some reason it is not installed, the Debian package is:
Comes in the same package as nm-applet (the default top bar icon thing) and nm-cli , and is therefore widely available.

Tested in Ubuntu 17.10.
![]()
If your wi-fi access point is saved, it will auto-connect. Turn wireless on or off with a simpler command:
on newer version:
For reference, see man nmcli .
![]()
If you want to connect to a network called PrettyFlyForAWiFi-5G
-a (or —ask ) means it will ask you for the password. The connection will be saved and should connect automatically if you restart your computer.
You could append password <your password> to the end (the literal word password followed by the actual password)
but maybe run unset HISTFILE beforehand, so that your WiFi password isn’t saved to your
To see all the WiFi networks around you ( —rescan yes is optional, the list of networks might be up to 30 seconds old without it)
which will output something like
To forget a connection (that was saved after you ran nmcli -a d wifi connect <name> )
To see a list of all saved connections
You can use nmcli connection instead of nmcli c <whatever> and nmcli device instead of nmcli d
nmcli is the command line interface for NetworkManager (which is part of GNOME, Ubuntu’s default desktop environment) and is already installed on Ubuntu.
Don’t forget to set up your country code for using the perfect regulations:
Подключаемся к WiFi(WPA2) через консоль в Debian Linux

Надоели в последнее время мне проблемы с wicd и wifi-radar для подключения к Wi-Fi в Linux, и я решил что пора бы подключаться через консоль, минуя все эти надстройки в виде программ для подключения. На самом деле все оказалось еще проще чем я предполагал. И сейчас я покажу как это делается. А тем кому пока не надоело подключатся через программы стоит добавить эту заметку в Избранное, в дальнейшем пригодиться.
Подключаемся к роутеру/точке доступа
Итак, предполагаем что подключение происходит с шифрованием WPA2, так как сейчас это самое популярное и наиболее безопасное решение, чем к примеру устаревший WPA.
Для начала посмотрим все ли в порядке с нашими устройствами:
# ifconfig
eth0 Link encap:Ethernet HWaddr e4:11:5b:f2:cc:4a
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:1131 errors:0 dropped:0 overruns:0 frame:0
TX packets:1131 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:299033 (292.0 KiB) TX bytes:299033 (292.0 KiB)
Никакого wlan не видим, смотрим, может он отключен:
# ifconfig -a
eth0 Link encap:Ethernet HWaddr e4:11:5b:f2:cc:4a
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:816 errors:0 dropped:0 overruns:0 frame:0
TX packets:816 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:209884 (204.9 KiB) TX bytes:209884 (204.9 KiB)
wlan0 Link encap:Ethernet HWaddr e4:d5:3d:9e:97:bb
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:26410
TX packets:0 errors:882 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Interrupt:23
Ага, вот и он, наш wlan0, в некоторых исключительных случаях система его может обозначить как eth2, но не в нашем случае. Если ifconfig -a не вывел вам информации о беспроводном интерфейсе, значит система не видит устройство, либо оно отключено хардварно(на панели ноутбука), либо нет драйвера и устройство не определилось. В таком случае либо включите ваше устройство и повторите команду, либо переходите к установке драйвера. Установку я описывал в статьях:
Debian GNU\Linux: Broadcom Wi-Fi drivers в Compaq Presario CQ57
Broadcom драйвера wifi в Linux ядрах версий 3.4 и 3.5
Итак, зная наш интерфейс мы находим наш роутер или точку подключения:
#iwlist wlan0 scanning | grep -i essid
ESSID:»TP-LINK_985188″
ESSID:»Beryozka»
ESSID:»Tenda_18B2F8″
Видим наш «TP-LINK_985188».
Дальше, для WPA2 нам нужно создать запись соответствующую ESSID и Пароль доступа, для этого используем пакет программ wpasupplicant, если у вас не установлен, нужно установить:
# apt-get install wpasupplicant
Используем ее для генерации записи подключения:
# wpa_passphrase TP-LINK_985188 наш_пароль_установленный_на_роутере
Получаем сгенерированную запись:
network= <
ssid=»TP-LINK_985188″
psk=b8530ddba3a3625b9336be805da8cfb5f2d67d0e776d5ffd2f38b3f11b18a404
>
Открываем файл где храняться такие записи и добавляем нашу сгенерированную в него:
nano /etc/wpa_supplicant/wpa_supplicant.conf
Сохраняем и закрываем.
Осталось только подключиться, что мы и делаем:
wpa_supplicant -D wext -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf -B
В дальнейшем нам нужно только использовать последнюю команду для подключения к этому роутеру.
Настройки сети
Подключиться по Wi-Fi не сложно, но это еще не все, нужно получить/указать свои клиентские настройки для использования сети. Если ваш роутер раздает настройки автоматически то просто введите команду:
#dhclient wlan0
Если же не раздает, пропишем их вручную, введите команды:
ifconfig wlan0 ip-адресс netmask сетевая_маска
И добавляем шлюз:
route add default gw 192.168.1.1 последний IP адрес стоит по умолчанию для большинства роутеров, если у вас другой то введите его.
MNorin.com
Блог про Linux, Bash и другие информационные технологии
Настройка WiFi из командной строки
Если вы пользуетесь какой-либо операционной системой на базе ядра linux, то скорее всего уже видели графические приложения для подключения к беспроводными сетям. Но если графического приложения еще нет, и для установки его требуется наличие сети, а для получения доступа к Интернету необходимо подключиться к беспроводной точке, то выход тогда только один — настройка WiFi из командной строки. Или еще пример — настроить сервер по ssh, чтобы он мог работать с беспроводным контроллером.
Установка необходимых пакетов
В первую очередь необходимо проверить, установлены ли пакет wpasupplicant и wireless-tools. Эти пакеты позволят вам подключаться к беспроводным сетям с WPA и WPA2 аутентификацией. В Debian и Ubuntu это делается командами
Если пакеты не установлены, то, возможно, поднять беспроводную сеть не получится, если у вас нет другого носителя. Пакеты устанавливаются следующей командой:
Кроме того, может понадобиться поставить микрокод (firmware) для устройства, установив соответствующий производителю пакет. Микрокод также называют прошивкой, но это не совсем правильно. Микрокод загружается в устройство перед началом работы с ним, а прошивка в устройстве находится постоянно. Для Intel это может быть, например, пакет firmware-iwlwifi из репозитория non-free. Микрокод часто лежит именно в этой ветке репозиториев. Либо это может быть пакет firmware-realtek, либо firmware-linux-free.
Проверка беспроводного контроллера
Перед тем, как пытаться подключаться, нужно убедиться, что система видит WiFi-контроллер и правильно его распознает, для просмотра списка устройств можно использовать команду lspci, в ее выводе должна быть строчка наподобие этой:
А в списке интерфейсов должен присутствовать соответствующий сетевой интерфейс, обычно это wlan0. Просмотреть список можно командой
Настройка WiFi из командной строки
Если устройство в системе найдено, можно переходить к настройке сети. Для начала просмотрим список доступных локальных сетей:
На экран будет выведен список доступных сетей в виде записей такого вида:
Из этой информации нам понадобится поле «ESSID», представляющее название точки доступа, в данном случае «wireless-net», а также строчки «IEEE 802.11i/WPA2 Version 1» и «Authentication Suites (1) : PSK». Эти два значения дают нам понимание того, что используется WPA2-PSK аутентификация.
Создаем файл /etc/wpa_supplicant/wpa_supplicant.conf:
И затем даем команду
После этого, если адрес не получен автоматически, вызываем DHCP-клиент:
После получения адреса Интернет может быть недоступен. Необходимо командой route проверить таблицы роутинга. Если шлюз по умолчанию отсутствует, то надо добавить его командой
Если адрес указан верно, то вы сможете получить доступ к Интернету. Но обычно DHCP-клиент получает шлюз по умолчанию автоматически
Изменение конфигурационных файлов
Теперь нам необходимо задать в конфигурационных файлах параметры беспроводной сети — название и ключ.