Connecting to wifi linux terminal

How to Connect Wi-Fi from Linux Terminal Using Nmcli Command

There are several command-line tools for managing a wireless network interface in Linux systems. A number of these can be used to simply view the wireless network interface status (whether it is up or down, or if it is connected to any network), such as iw, iwlist, ip, ifconfig and others.

And some are used to connect to a wireless network, and these include: nmcli, is a command-line tool used to create, show, edit, delete, enable, and disable network connections, as well as control and display network device status.

First start by checking the name of your network device using the following command. From the output of this command, the device name/interface is wlp1s0 as shown.

Next, check the Wi-Fi device connection status using the following command.

From the output above the device is not connected to any network, run the following command to scan available Wi-Fi networks.

Considering the output of the above command, the network device/interface is DOWN, you can turn it On (UP) with the ip command as shown.

If you get the following error, that means your Wifi is hard blocked on Laptop or Computer.

To remove or unblock you need to run the following command to solve the error.

Then try to turn ON the network device once more, and it should work this time around.

If you know the ESSID of the Wi-Fi network you wish to connect to, move to the next step, otherwise issue the command below to scan available Wi-Fi networks again.

And lastly, connect to the wi-fi network using following command, where Hackernet (Wi-Fi network SSID) and localhost22 (password/pre-shared key).

Once connected, verify your connectivity by doing a ping to an external machine and analyze the output of the ping as shown.

That’s It! I hope this article helped you to setup your Wi-Fi network from the Linux command line. As always, if you found this article useful, share your thoughts in the comment section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

Читайте также:  Как поставить виндовс поверх линукс

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

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 проверить таблицы роутинга. Если шлюз по умолчанию отсутствует, то надо добавить его командой

Читайте также:  Как форматировать диск для системы mac os

Если адрес указан верно, то вы сможете получить доступ к Интернету. Но обычно DHCP-клиент получает шлюз по умолчанию автоматически

Изменение конфигурационных файлов

Теперь нам необходимо задать в конфигурационных файлах параметры беспроводной сети — название и ключ.

Записываем в файл /etc/network/interfaces следующее:

Источник

How to Connect to WiFi from the Terminal in Ubuntu Linux

Last updated August 31, 2021 By Abhishek Prakash 28 Comments

In this tutorial, you’ll learn how to connect to wireless network from the terminal in Ubuntu. This is particularly helpful if you are using Ubuntu server where you don’t have access to the regular desktop environment.

I primarily use desktop Linux on my home computers. I also have multiple Linux servers for hosting It’s FOSS and related websites and open source software like Nextcloud, Discourse, Ghost, Rocket Chat etc.

I use Linode for quickly deploying Linux servers in cloud in minutes. But recently, I installed Ubuntu server on my Raspberry Pi. This is the first time I installed a server on a physical device and I had to do extra stuff to connect Ubuntu server to WiFi via command line.

In this tutorial, I’ll show the steps to connect to WiFi using terminal in Ubuntu Linux. You should

  • not be afraid of using terminal to edit files
  • know the wifi access point name (SSID) and the password

Connect to WiFi from terminal in Ubuntu

It is easy when you are using Ubuntu desktop because you have the GUI to easily do that. It’s not the same when you are using Ubuntu server and restricted to the command line.

Ubuntu uses Netplan utility for easily configuring networking. In Netplan, you create YAML file with the description of network interface and with the help of the netplan command line tool, you generate all the required configuration.

Let’s see how to connect to wireless networking from the terminal using Netplan.

Step 1: Identify your wireless network interface name

There are several ways to identify your network interface name. You can use the ip command, the deprecated ipconfig command or check this file:

This should give you all the available networking interface (Ethernet, wifi and loopback). The wireless network interface name starts with ‘w’ and it is usually named similar to wlanX, wlpxyz.

Take a note of this interface name. You’ll use it in the next step.

Step 2: Edit the Netplan configuration file with the wifi interface details

The Netplan configuration file resides in /etc/netplan directory. If you check the contents of this directory, you should see files like 01-network-manager-all.yml or 50-cloud-init.yaml.

Читайте также:  Линукс для acer travelmate

If it is Ubuntu server, you should have cloud-init file. For desktops, it should be network-manager file. This is one of the several ways Ubuntu desktop differs from Ubuntu server.

The Network Manager on the Linux desktop allows you to choose a wireless network. You may hard code the wifi access point in its configuration. This could help you in some cases (like suspend) where connection drops automatically.

Whichever file it is, open it for editing. I hope you are a tad bit familiar with Nano editor because Ubuntu comes pre-installed with it.

YAML files are very sensitive about spaces, indention and alignment. Don’t use tabs, use 4 (or 2, whichever is already used in the YAML file) spaces instead where you see an indention.

Basically, you’ll have to add the following lines with the access point name (SSID) and its password (usually) in quotes:

Again, keep the alignment as I have shown or else YAML file won’t be parsed and it will throw an error.

Your complete configuration file may look like this:

I find it strange that despite the message that changes will not persist across an instance reboot, it still works.

Anyway, generate the configuration using this command:

And now apply this:

If you are lucky, you should have network connected. Try to ping a website or run apt update command.

However, things may not go as smooth and you may see some errors. Try some extra steps if that’s the case.

Possible troubleshooting

It is possible that when you use the netplan apply command, you see an error in the output that reads something like this:

It is possible that wpa_supplicant service is not running. Run this command:

Run netplan apply once again. If it fixes the issue well and good. Otherwise, shutdown your Ubuntu system using:

Start your Ubuntu system again, log in and generate and apply netplan once again:

It may show warning (instead of error) now. It is warning and not an error. I checked the running systemd services and found that netplan-wpa-wlan0.service was already running. Probably it showed the warning because it was already running and ‘netplan apply’ updated the config file (even without any changes).

It is not crtical and you may check that the internet is probably working already by running apt update.

I hope you were able to connect to wifi using the command line in Ubuntu with the help of this tutorial. If you are still facing trouble with it, do let me know in the comment section.

Like what you read? Please share it with others.

Источник

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