How to connect to wifi linux
How to connect to wifi linux
How to Connect to WiFi from the Terminal in Ubuntu
Ubuntu is a Linux-based, multi-purpose operating system designed specifically for PCs, mobile phones, and network servers. It is one of the most popular Linux distributions because of its well-designed, powerful, and easy-to-use GUI.
Nevertheless, the Ubuntu NetworkManager can sometimes be tricky, and the Graphical interface makes it difficult for you to connect to WiFi or ethernet.
You’re likely to face an issue starting the network manager or even connecting to an already known WiFi network.
While this problem can be pretty annoying, luckily, there are several command-line utilities available for managing wireless network interface in Linux systems. To add to that, it’s relatively easy too. Read below to configure an internet connection in Ubuntu PC operating system.
Table of Contents
How Can I Connect to a Wireless Network through Ubuntu Terminal?
You can connect to a WiFi network using the Ubuntu terminal commands. But before we explain how to do that, you should bear two things in mind.
First, you shouldn’t hesitate to use terminals to edit files. Second, you should know the name of your WiFi access point (SSID) and, of course, the password.
Please read below to learn about a few command-line tools and how to use them.
NMCLI
NMCLI (NetworkManager Command-line) manages the network manager interface and identifies available internet connections. It can be used to activate, edit, and delete wireless network connections.
While connecting to a WiFi network through a terminal can be challenging (as some methods may require a PSK key and configuration files), NMCLI makes it easy.
All you need to know is your network’s SSID and password, and here’s what needs to be done.
Enable a Wireless Network Connection
You can only connect to your wireless network once you enable the connection. To check the status of your network interfaces, use the “nmcli dev status” command.
A list of available devices will be displayed along with their network information.
To check if your wi-fi is enabled or not, run the “nmcli radio wifi” command. If the result shows it as disabled, you can enable it by running the following command “nmcli radio wifi on”.
Spot Wi-Fi Access Point
At this step, you’d need to know the name of your wireless access point (WAP). If you do not know your SSID, run the following command, “nmcli dev wifi list.“
That’s it! A list with several networks will appear on display. You can note the one you want to connect to.
Connect Wi-Fi
Once you’ve identified your wireless network interface, you can connect to wifi by running the “sudo nmcli dev wifi connect network-ssid” command.
Remove the current SSID and enter the name of your network. If you have WiFi security on your network, you can enter the password, and you’re good to go.
After following the instructions above, your NetworkManager will save the connection, so you won’t have to run the command every time you need to get your WiFi working.
NMTUI
NMTUI (NetworkManager Text User Interface) is another handy tool that allows you to connect to a wireless interface without hassle.
While it lacks several features provided by the NMCI tool, it’s still wonderful to perform basic tasks. Follow the steps below to configure your network interface in the Ubuntu server.
Run NMTUI
To use NMTUI, run the “nmtui” command in your terminal. A new tab will open with Active a Connection right in the middle. Click on it and choose Ok.
Connect to WiFi
Next, a list with several network interfaces will appear. Here, you need to identify your network connection and connect.
If your Wi-Fi is protected, you’ll need to type the password, press enter, and you’re all set! You can select Quit after you’re done with the steps.
The new network will be saved to your device. Hence, you won’t have to go through the command process every time you connect to WiFi.
Netplan
You can easily configure a WiFi connection with Netplan. It generates the required connection for you by creating a YAML file that specifies the interface details. Here’s how you can use Netplan to connect to a WiFi terminal
Identify the Wireless Network Interface Name
There are various ways to know the wireless interface name. For instance, you can run the “ifconfig” command.
The available interfaces will appear on display. Typically, the name begins with “w” and can be iwconfig wlan0 or wlp3so (depends on your Ubuntu system)
Remember this name for the next step.
Navigate the Config File
Next, you need to find out the correct configuration files. Remember that the configuration file is located in /etc/
The name of the configuration file might be: “0.1-network-manager-all.yaml”, or it can be “50-cloud-init-yaml”.
Modify Netplan Configuration File
Once you navigate the Netplan configuration file, you’ll need to edit it. First, you have to replace ESSID with your SSID and enter the password. You’ll need to enter the following lines.
However, make sure that you keep the alignment similar; otherwise, the output might turn out wrong.
Connect to WiFi
Once you’ve followed the steps above, you can connect to the wireless interface by running the command sudo netplan apply in the command prompt.
If you get stuck by some unfortunate output, you can establish a “sudo netplan – debug apply”, or you can restart your Ubuntu system and generate Netplan again.
If your system is already running the Netplan service, you probably may come across a warning sign (if you apply Netplan again) as it will update the config file.
You can run the IP command and check to confirm that you’ve successfully connected to a WiFi network.
The primary purpose of the ping command is to troubleshoot the connectivity and reachability of a particular connection. Here’s how you can use this software to check your Wi-Fi network.
Ifconfig
Ifconfig is yet another command used to configure a network interface. You can use it at boot time to set up an internet connection. Also, it can check the given IP address of a particular server.
If you own an older Linux distribution, you’ll use the Ifconfig command; otherwise, you’ll run the IP command.
Iwconfig
You can use the iwconfig command for network configuration on your Ubuntu server. Follow the instructions below.
Wrap Up
There are several command lines that you can utilize to connect a wireless network on Ubuntu. Hopefully, you’ll be able to configure your WiFi interface by following the instructions above.
Linux WiFi из командной строки с wpa_supplicant
В этой статье я расскажу, как можно настроить WiFi с помощью wpa_supplicant, без всяких Xorg/X11 утилит. Это необходимо для того, чтобы базовые службы ОС исправно работали с минимальным набором технических средств удаленного доступа. Программа будет исполняться как служба, настройки сделаны правкой конфиг файлов.
По-быстрому, установить соединение с открытой точкой доступа можно таким образом.
Если же надо всерьез и надолго, то прошу внутрь.
Общие сведения о wpa_supplicant
Что из себя представляет wpa_supplicant?
Как wpa_supplicant устанавливает связь с точкой доступа?
Установка
Если не выбирать графический фронтенд, то программа почти не тянет за собой никаких зависимостей. Для Gentoo Linux сгодится установка с выставленными флагами как показано.
Подключение без конфиг файла
Если вам нужно подключиться только один раз, то необходимости создавать файл конфигурации и вникать во все тонкости настройки, нет. Достаточно набрать несколько инструкций из командной строки.
Пример для открытой сети был показан в самом начале. Для закрытой WPA сети быстрое подключение выгладит так:
Для закрытой WPA2 сети:
В конце необходимо вручную запустить демон DHCP.
Подключение к Ad-Hoc сети
Никогда с такой не сталкивался, но готовым нужно быть ко всему. Подключение к открытой ad-hoc.
Настройка для домашней сети
Теперь самое интересное — настройка. Этот процесс задокументирован для Arch Wiki, Debian Wiki и Gentoo Wiki, но всех деталей там естественно нет.
Возьмем типовой конфиг из документации. Например такой.
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.
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.
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 :
Все готово, чтобы создать конфиг сети. Итоговый файл должен выглядеть как-то так.
Настройка 802.1X для офиса
Стандарт IEEE 802.1X определяет более строгую модель подключения к WiFi сети. Вместо psk пароля необходимо предъявить серверный сертификат.
Так может выглядеть блок, настроенный для подключения к сети в режиме WPA-Enterprise с аутентификацией 802.1X PEAP, в котором требуется ввод данных учетной записи пользователя:
А это пример блока, настроенного для подключения к сети в режиме WPA-Enterprise с аутентификацией 802.1X EAP-TLS, в котором требуются серверный и клиентский сертификаты:
Привязка wpa_supplicant к сетевой карте
Следует также добавить wpa_supplicant в автозапуск.
Пользователи RedHat добавляют в /etc/sysconfig/wpa_supplicant
а в файл /etc/sysconfig/network-scripts/ifcfg-wlan0
Отладка
После того как wpa_supplicant успешно подключилась к точке доступа, в dmesg можно увидеть протокол установки соединения.
Если же вместо этого вы увидите ошибку:
Configure WiFi Connections
This section explains how to establish a WiFi connection. It covers creating and modifying connections as well as directly connecting.
Establish a Wireless Connection
This section will show how to establish a wifi connection to the wireless network. Note that directly connecting will implicitly create a connection (that can be seen with “nmcli c”). The naming of such will follow “SSID N” pattern, where N is a number.
First, determine the name of the WiFi interface:
Make sure the WiFi radio is on (which is its default state):
Then, list the available WiFi networks:
As an example, to connect to the access point ‘my_wifi’, you would use the following command:
is the password for the connection which needs to have 8-63 characters or 64 hexadecimal characters to specify a full 256-bit key.
Connect to a Hidden Network
A hidden network is a normal wireless network that simply does not broadcast it’s SSID unless solicited. This means that its name cannot be searched and must be known from some other source.
Issue the following command to create a connection associated with a hidden network :
Now you can establish a connection by typing:
is an arbitrary name given to the connection and is the password to the network. It needs to have between 8-63 characters or 64 hexadecimal characters in order to specify a full 256-bit key.
Further Information
You will find further information and more detailed examples on following pages:
Connecting to wifi network through command line
I am trying to connect to my WEP network just using the command-line (Linux).
Then I try to obtain an IP with
without success (tried to ping google.com).
I know that the keyword is right, and I also tried with the ASCII key using ‘s:key’, and again, the same result.
I get the message below when running dhclient:
I have no problem connecting with WICD or the standard Ubuntu tool.
8 Answers 8
Option 1
Just edit /etc/network/interfaces and write:
After that write and close file and use command:
Replace and with your respective WiFi SSID and password.
Option 2
Provided you replace your Wireless network card, Wi-Fi Network name, and Wi-FI Password this should also work.
First, get your WiFi card up and running:
Now scan for a list of WiFi networks in range:
This will show you a list of wireless networks, pick yours from the list:
To obtain the IP address, now request it with the Dynamic Host Client:
You should then be connected to the WiFi network. The first option is better, because it will be able to run as a cron job to start up the wifi whenever you need it going. If you need to turn off your WiFi for whatever reason, just type:
I have also seen people using alternative commands. I use Debian, Solaris and OSX, so I’m not 100% sure if they are the same on Ubuntu. But here they are:
sudo ifup wlan0 is the same as sudo ifconfig wlan0 up
sudo ifdown wlan0 is the same as sudo ifconfig wlan down
How to connect to WiFi from the command line?
Other posts seems to be addressing more complicated network connection issues from the command line.
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 ( )
To see list of available WiFi hotspots ( )
To see list of interfaces ( )
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:
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:
If you want to connect to a network called PrettyFlyForAWiFi-5G
You could append 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
which will output something like
To see a list of all saved connections
You can use nmcli connection instead of nmcli c 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: