Linux connect to wifi from command line

How to Connect to WiFi from Terminal on Ubuntu 20.04

If you have a wireless-enabled computer or laptop, you can connect to the internet. On Ubuntu you can connect to a Wi-Fi network on the terminal using the following command-line tools:

Let’s see how each of these tools can be used to connect to WiFi from the terminal on Ubuntu 20.4

1) Connect to a WiFi network on the terminal using nmtui

Nmtui — Network Manager Text User Interface — is a command-line tool that is used for network configuration on Linux systems. When executed, it invokes a graphical text interface that helps users to configure network interfaces in a simple and effective manner.

It can also be used to connect to a Wireless network in these easy steps:

Step 1: Launch nmtui

To launch nmtui, simply open your terminal and run the command below:

A graphical interface will be launched. Select ‘Activate a connection‘ as shown and use the TAB key to select ‘OK‘.

Step 2: Connect to a wireless network

The next interface displays the network interfaces and the wireless networks that are available. As you can see, we have 2 wireless networks within range. Select the WiFi network that you want to connect to and hit ENTER. In this case, we have selected ‘Milky_Way‘.

Provide the password for the wireless network in the pop-up dialogue box that appears and, once again, use the TAB key to select the ‘OK‘ option.

Once you have successfully connected to your wireless network, select the ‘Back’ option to get back to the home screen of the nmtui interface, and finally select ‘Quit‘.

To test your internet connectivity, you can ping Google’s DNS on the terminal as shown:

2) Connect to a WiFi network on the terminal using nmcli

The nmcli command-line tool is yet another utility you can use to connect to a wireless or WiFi network. Follow the steps below to connect to a wireless network on the terminal.

Step 1: Find out the name of your WiFi adapter and wireless network

Before anything else, use the iwconfig command to display the wireless interfaces on your system and check their status

From the output above, we can see that we have a wireless interface labeled wlxc4e9840c3fce . This may be something else for your case. Also, from the output, we can see that we are not connected to any wireless network.

To list wireless interfaces only run the command:

You can also check whether the interface is connected to any wireless device using the command:

In this case, the command will be:

The output confirms that we are not connected to any wireless network. Let’s now proceed to the next step and connect to a WiFi network.

Step 2: Connect to WiFi on the terminal

Before connecting to a WiFi network, it’s prudent to perform a scan on the terminal to search the available Wireless networks. To achieve this, run the command:

The output indicates that we have 2 wireless networks at our disposal which we can connect to. We are going to connect to the ‘Milky_Way‘ network using the nmcli command :

After running the command, you should get the output that confirms that you have successfully connected to the WiFi network. Thereafter, confirm that your interface is connected using the iwconfig command as shown above.

Читайте также:  Iso windows 10 содержимое

Also, you can verify this using :

Conclusion

Usually, most users would rather use the graphical means to select and connect to their preferred wireless network. However, for terminal geeks, connecting to a WiFi network is also a viable option and only takes a few simple steps.

For earlier versions on Ubuntu such as Ubuntu 16.04 and Ubuntu 17.10, you can use the wpasupplicant tool to connect to a WiFi network on the terminal. We hope that you can now connect to your preferred wireless network with ease. Your feedback is most welcome.

Источник

How to connect to wifi from command line?

I’m using latest version of Debian-based Linux Kali. Maybe it is an XY problem, as the main problem is after I log in to the system I get a blank screen and mouse pointer. Somebody on the Internet recommend me to change window manager.

But I’m unable to do this as I can’t connect to wifi.

I found tutorial how to do this here

And I tried to do it step by step, but it doesn’t work for me. In that tutorial that author wrote that I need use the command ip link set wlan0 ip to bring up the wifi interface. In his example the output looks like this:

On the other hand when I call:

and after running wpa supplicant with valid network details

iw wlan0 link still returns Not connected.

How do I solve this problem and what shall I do next?

2 Answers 2

I’m assuming wpa_supplicant and iw is installed.

To connect to wifi through wpa_supplicant you need to create a wpa_supplicant.conf file

with the following lines:

Or you can use wpa_passphrase to create the configuration file (copy and past):

Also you can write the wpa_supplicant.conf directly through:

to connect type the following command:

Note: Multiple comma separated driver wrappers in option -Dnl80211,wext makes wpa_supplicant use the first driver wrapper that is able to initialize the interface (see wpa_supplicant(8)). This is useful when using mutiple or removable (e.g. USB) wireless devices which use different drivers.

You can connect through wpa_supplicant without wpa_supplicant.conf file:

You can visit the official documentation of Arch-linux to get more information about the configuration file and arguments.

you can connect through nmcli

  1. Also you can connect through wpa_cli :

Open the terminal and type wpa_cli

Create a network:

This will output a number, which is the network ID, for example 0 Next, we need to set the SSID and PSK for the network.

Once the wireless has connected, it should automatically get an IP address. if it doesn’t you can run the dhclient to get an IP address via DHCP.

The dhclient command ca be replaced with 2 ip commands:

  1. iwctl command line tools.

Источник

Linux WiFi из командной строки с wpa_supplicant

В этой статье я расскажу, как можно настроить WiFi с помощью wpa_supplicant, без всяких Xorg/X11 утилит. Это необходимо для того, чтобы базовые службы ОС исправно работали с минимальным набором технических средств удаленного доступа. Программа будет исполняться как служба, настройки сделаны правкой конфиг файлов.

По-быстрому, установить соединение с открытой точкой доступа можно таким образом.

Если же надо всерьез и надолго, то прошу внутрь.

Общие сведения о wpa_supplicant

Что из себя представляет wpa_supplicant?

  • Кросс-платформенная открытая реализация стандарта IEEE 802.11 для Linux, *BSD, Windows, Mac OS X и прочих систем.
  • Полная поддержка WPA2, WPA и более старых протоколов безопасности беспроводной LAN сети.
  • Приложение пользовательского пространства, выполняющее функции саппликанта и SME оператора, исполняющего MLME инструкции.

  • WPA и полностью IEEE 802.11i/RSN/WPA2.
  • WPA-PSK и WPA2-PSK (pre-shared key) («WPA-Personal»).
  • WPA вместе с EAP (т.е., сервером аутентификации RADIUS) («WPA-Enterprise») управление ключами CCMP, TKIP, WEP (104/128 и 40/64 бит).
  • Кэширование RSN, PMKSA: предварительную аутентификацию.

Как wpa_supplicant устанавливает связь с точкой доступа?

  • Cетевой интерфейс должен исправно функционировать с установленным драйвером, прежде чем wpa_supplicant запустится.
  • Wpa_supplicant запрашивает драйвер ядра сканировать доступные Basic Service Set (BSS).
  • Wpa_supplicant производит выбор BSS в соответствии с настройками.
  • Wpa_supplicant запрашивает драйвер ядра установить соединение с выбранной BSS.
  • Для WPA-EAP: аутентификацию EAP производит встроенный IEEE 802.1X Supplicant, либо же внешний Xsupplicant с сервером аутентификации.
  • Для WPA-EAP: получен мастер-ключ от IEEE 802.1X Supplicant.
  • Для WPA-PSK wpa_supplicant использует пароль PSK в качестве мастер-ключа сессии.
  • Wpa_supplicant производит с аутентификатором точки доступа 4-х этапное согласование [1] и групповое согласование ключей.
  • Wpa_supplicant производит шифрование однонаправленных и широковещательных пакетов [2] , после чего начинается обычный обмен данными.
Читайте также:  Вечная установка обновления windows

Главный и большой плюс wpa_supplicant — его юниксвейность, то есть соответствие принципу Unix Way, когда программа делает что-то одно, но делает это хорошо. В каком-то смысле wpa_supplicant также Gentoo Way. Она требует некоторого внимания и терпения вначале, но затем о ней можно напрочь забыть. После того как программа настроена и пущена в дело, она полностью выпадает из потока событий, превращаясь в пару строк из ps -ef . Она не сверкает и не мигает в системном трее, не оповещает о разведанных, подключенных и отключенных беспроводных сетях. Ее просто нет, пока вы сами ее не поищите.

Из минусов — сложность настройки и конфигурации. Много возни по сравнению с тырк-тырк-тырк в окне Network Manager , не говоря уже о WiFi подключении с любого Андроид устройства. Если вы собираетесь в поездку с Linux ноутбуком, то наверняка предпочтете более дружественный фронтенд настройки беспроводной сети, чтобы быстро подключаться к бесплатным точкам доступа WiFi в аэропорту, гостинице или в рабочей обстановке. Для домашнего же беспроводного интернета — самое то.

Установка

Если не выбирать графический фронтенд, то программа почти не тянет за собой никаких зависимостей. Для Gentoo Linux сгодится установка с выставленными флагами как показано.

  • emerge -av wpa_supplicant #Gentoo
  • aptitude install wpasupplicant #Debian
  • yum install wpa_supplicant #Redhat
  • pacman -S wpa_supplicant #Arch

Подключение без конфиг файла

Если вам нужно подключиться только один раз, то необходимости создавать файл конфигурации и вникать во все тонкости настройки, нет. Достаточно набрать несколько инструкций из командной строки.

Пример для открытой сети был показан в самом начале. Для закрытой WPA сети быстрое подключение выгладит так:

В начале надо запустить саму программу wpa_supplicant и сопутствующую wpa_cli .

Затем настройка из интерактивного интерфейса wpa_cli .

Для закрытой WPA2 сети:

В конце необходимо вручную запустить демон DHCP.

Подключение к Ad-Hoc сети

Никогда с такой не сталкивался, но готовым нужно быть ко всему. Подключение к открытой ad-hoc.

То же самое с помощью iw .

Настройка для домашней сети

Теперь самое интересное — настройка. Этот процесс задокументирован для Arch Wiki, Debian Wiki и Gentoo Wiki, но всех деталей там естественно нет.

Программа обычно ставится в директорию /etc/wpa_supplicant/ , и наша задача — правильно настроить конфигурационный файл wpa_supplicant.conf , и привязать его к автозапуску беспроводного сетевого интерфейса.

Начнем с wpa_supplicant.conf . Если вы подключаетесь из дома к WPA/WPA2, то скорее всего используете пароль для WiFi соединения, что соответствует режиму WPA-PSK («WPA-Personal») . Мы не будет рассматривать варианты с WEP шифрованием, так как оно ненамного лучше открытой сети.

Возьмем типовой конфиг из документации. Например такой.

Первая строка необходима, без ctrl_interface программа даже не запустится. GROUP=wheel нужно для того, чтобы запускать из под обычного пользователя в графическом интерфейсе wpa_gui, но это не наш путь. Поэтому меняем на рутовый GROUP=0 .

Каждой сети в файле настроек должен соответствовать блок network <> . Покопавшись в исходниках, обнаружил нашел годное писание переменной ap_scan в файле config.h , а в мануале и руководстве пользователя ее описание очень скудное.

ap_scan — AP scanning/selection

By default, wpa_supplicant requests driver to perform AP scanning and then uses the scan results to select a suitable AP. Another alternative is to allow the driver to take care of AP scanning and selection and use wpa_supplicant just to process EAPOL frames based on IEEE 802.11 association information from the driver.

1: wpa_supplicant initiates scanning and AP selection (default).
0: Driver takes care of scanning, AP selection, and IEEE 802.11 association parameters (e.g., WPA IE generation); this mode can also be used with non-WPA drivers when using IEEE 802.1X mode;
do not try to associate with APs (i.e., external program needs to control association). This mode must also be used when using wired Ethernet drivers.

2: like 0, but associate with APs using security policy and SSID (but not BSSID); this can be used, e.g., with ndiswrapper and NDIS drivers to enable operation with hidden SSIDs and optimized roaming;
in this mode, the network blocks in the configuration are tried one by one until the driver reports successful association; each network block should have explicit security policy (i.e., only one
option in the lists) for key_mgmt, pairwise, group, proto variables.

Читайте также:  Sound blaster 0220 драйвер windows 10

Note: ap_scan=2 should not be used with the nl80211 driver interface (the current Linux interface). ap_scan=1 is optimized work working with nl80211. For finding networks using hidden SSID, scan_ssid=1 in the network block can be used with nl80211.

  • bssid — The Basic Service Set Identifier (BSSID), физический адрес точки доступа.
  • key_mgmt — Протоколы аутентификации.
  • pairwise — Для WPA2 укажите CCMP, а для WPA — TKIP.
  • proto — WPA/WPA2.
  • psk — Хэш пароля PreShared Key.

group: list of accepted group (broadcast/multicast) ciphers for WPA
CCMP = AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0]
TKIP = Temporal Key Integrity Protocol [IEEE 802.11i/D7.0]
WEP104 = WEP (Wired Equivalent Privacy) with 104-bit key
WEP40 = WEP (Wired Equivalent Privacy) with 40-bit key [IEEE 802.11]
If not set, this defaults to: CCMP TKIP WEP104 WEP40

pairwise: list of accepted pairwise (unicast) ciphers for WPA
CCMP = AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0]
TKIP = Temporal Key Integrity Protocol [IEEE 802.11i/D7.0]
NONE = Use only Group Keys (deprecated, should not be included if APs support pairwise keys)

proto: list of accepted protocols
WPA = WPA/IEEE 802.11i/D3.0
RSN = WPA2/IEEE 802.11i (also WPA2 can be used as an alias for RSN)
If not set, this defaults to: WPA RSN

key_mgmt: list of accepted authenticated key management protocols
WPA-PSK = WPA pre-shared key (this requires ‘psk’ field)
WPA-EAP = WPA using EAP authentication (this can use an external program, e.g., Xsupplicant, for IEEE 802.1X EAP Authentication
IEEE8021X = IEEE 802.1X using EAP authentication and (optionally) dynamically generated WEP keys
NONE = WPA is not used; plaintext or static WEP could be used
If not set, this defaults to: WPA-PSK WPA-EAP

Создаем хэш пароля для psk :

Все готово, чтобы создать конфиг сети. Итоговый файл должен выглядеть как-то так.

Верные значения для bssid , group , proto и pairwise можно определить, сканируя беспроводную сеть.

Команда iwlist из набора Wireless Tools устарела, вместо нее сейчас iw .

Настройка 802.1X для офиса

Стандарт IEEE 802.1X определяет более строгую модель подключения к WiFi сети. Вместо psk пароля необходимо предъявить серверный сертификат.

  • ca_cert — Абсолютный путь к CA-сертификату в формате PEM или DER, необходим для возможности подтверждения сертификата сервера.
  • ca_path — Абсолютный путь к директории, где хранятся файлы CA-сертификатов (в формате PEM), которые вы хотите добавить в список доверенных.
  • client_cert — Абсолютный путь к клиентскому сертификату в формате PEM или DER.
  • eap — Разделенный пробелами список поддерживаемых методов EAP: MD5, MSCHAPV2, OTP, GTC, TLS, PEAP, или TTLS.
  • identity — Идентификации EAP, например имя пользователя.
  • password — Пароль EAP.

Так может выглядеть блок, настроенный для подключения к сети в режиме WPA-Enterprise с аутентификацией 802.1X PEAP, в котором требуется ввод данных учетной записи пользователя:

А это пример блока, настроенного для подключения к сети в режиме WPA-Enterprise с аутентификацией 802.1X EAP-TLS, в котором требуются серверный и клиентский сертификаты:

Привязка wpa_supplicant к сетевой карте

Для Gentoo Linux надо добавить 2 строки в /etc/conf.d/net .

Список поддерживаемых -D драйверов. Для современных чипов и версий ядра подойдет nl80211 . На старом железе может взлететь wext .

  • nl80211 — New driver.
  • wext — Linux wireless extensions (generic).
  • wired — wpa_supplicant wired Ethernet driver.
  • roboswitch — wpa_supplicant Broadcom switch driver.
  • bsd — BSD 802.11 support (Atheros, etc.).
  • ndis — Windows NDIS driver.

Сетевая карта wlan0 должна быть залинкована с lo0 .

Следует также добавить wpa_supplicant в автозапуск.

Пользователи Debian добавляют запись в файл /etc/network/interfaces .

Пользователи RedHat добавляют в /etc/sysconfig/wpa_supplicant

а в файл /etc/sysconfig/network-scripts/ifcfg-wlan0

Отладка

После того как wpa_supplicant успешно подключилась к точке доступа, в dmesg можно увидеть протокол установки соединения.

Если же вместо этого вы увидите ошибку:

то скорее всего, надо использовать драйвер wext вместо nl80211 . А с ошибкой:

наоборот, вместо wext надо подставить nl80211 .
В ситуации, когда вы не можете определить ошибку, запустите wpa_supllicant напрямую с ключем -dd .

Источник

Оцените статью