Connection with internet in linux

9 commands to check if connected to internet with shell script examples

Table of Contents

In this article I will share multiple commands and examples to check if connected to internet for your Linux machine. At the end of the article I will also share some example to test internet connection from the Linux to external network using shell script.

But before we do that there are certain things you must take care of, such as

  • You have IP Address assigned to your network interface (static or dhcp)
  • Your gateway is reachable from the Linux system
  • If you are on virtual machine then make sure your VM is configured to be able to connect external network
  • Your DNS is properly configured

Now there are multiple commands which are available in Linux which can be used to check if connected to internet, we will try to discuss some of them here in brief.

1. Ping Test

The very first tool I use to check if connected to internet is via ping utility . But do you know how to check ping or perform ping check to check if connected to internet? Ping is part of iputils rpm so make sure iputils is installed on your setup

To perform ping check, try to ping any page on internet such as google.com

Here we use -c 1 with ping tool to send only one packet . Now check the statistics section, we see 1 packet was transmitted and received and there was 0% packet loss so it means we are connected to internet.

If you plan to check if connected to internet via shell script then you can use below, anything in the output other than «0» means not connected to internet.

2. Check port availability using cat, echo..

There are various tools which can be used to check port availability which I will share in this article. But many of them are not installed by default so you may have to install them manually. Alternatively you can use below command to check if connected to internet without installing any additional rpm

If the output is 0 then it means you are connected to internet, but if the output is something like below

Then your linux node is not connected to internet.

Alternatively you can also use

3. DNS lookup using nslookup, host etc..

You can perform a DNS lookup any web page address to check if connected to internet. With a successful DNS lookup you should get a response something like below.

For a failed DNS lookup you should get something like

There are many more commands to perform DNS lookup such as host, dig etc

4. Curl

curl is a tool to transfer data from or to a server, using one of the many supported protocols such as HTTP, FTP etc. We can also use this tool to query a webpage and test internet connection in Linux.

Here if you receive anything other than 200 OK then it means the server failed to connect to the provided page. So unless you provide an invalid webpage, your node is connected to internet

5. Telnet

Telnet is another tool to check port connectivity so you can check port availability of any webpage from the Linux node to check if connected to internet. We can try connecting port 53 of Google DNS to check internet connection.

Читайте также:  Как снять нагрузку с оперативной памяти windows 10

As you see the session was » connected «. If you get an output like below

then it means there is a problem with internet connectivity.

6. Nmap

nmap is normally a port scanner to check the list of open ports on a system. We will use this to connect to external network to scan the port. If it is able to connect to the external network for port scanning then we can check if connected to internet.

Here I am scanning google.com on port 443. As you see highlighted section, nmap was able to establish connection with google.com

7. netcat or nc

In some variant of Linux you will find netcat while in others nc , you can use either of these tools for port scanning. nc or ncat is part of nmap-ncat rpm. Here we use nc command to check connection to google.com on port 443

8. wget

GNU Wget is a free utility for non-interactive download of files from the Web. But we can also use this to check if connected to internet.

Here with —spider Wget will behave as a Web spider, which means that it will not download the pages, just check that they are there
With echo $? we check the exit status, anything other than 0 in the output means your system is not connected to internet

9. Traceroute

The traceroute command shows every step taken on the route from your machine to a specified host. Assuming you are having problems connecting to www.google.com so you can use traceroute to check all the hubs taken to reach the destination server. This will also test internet connection.

Here we were able to trace the route to google.com upto a certain point.

What do those * * * mean?

Each one indicates a five-second timeout at that hop. Sometimes that could indicate that the machine simply doesn’t understand how to cope with that traceroute packet due to a bug, but a consistent set of * indicates that there’s a problem somewhere with the router to which 216.239.43.239 hands off packets.

On a Linux system with no internet connection, you would face problem with DNS resolution itself

How To check if connected to internet using shell script?

You can easily use any or all the above commands/methods to check if connected to internet using bash/shell script.

For example by using wget you can test internet connection in the below shell script:

Here this script will print the status of the internet, similarly for other scripts you can check the exit status and perform tasks accordingly.

Lastly I hope the steps from the article to check if connected to internet (test internet connection) on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Управляем сетевыми подключениями в Linux с помощью консольной утилиты nmcli

Используйте все возможности инструмента управления сетевыми подключениями NetworkManager в командной строке Linux c помощью утилиты nmcli.

Утилита nmcli напрямую обращается к API для доступа к функциям NetworkManager.

Она появилась в 2010 году и для многих стала альтернативным способом настройки сетевых интерфейсов и соединений. Хотя кто-то до сих пор использует ifconfig. Так как nmcli — это инструмент интерфейса командной строки (CLI), предназначенный для использования в окнах терминалов и скриптах, он идеально подходит для системных администраторов, работающих без GUI.

Синтаксис команд nmcli

В общем виде синтаксис выглядит так:

  • options — это параметры, которые определяют тонкости работы nmcli,
  • section (секция) — определяет, какими возможностями утилиты пользоваться,
  • action (действие) — позволяет указать, что, собственно, нужно сделать.

Всего существует 8 секций, каждая из которых связана с каким-то набором команд (действий):

  • Help выдаёт справку о командах ncmcli и их использовании.
  • General возвращает статус NetworkManager и глобальную конфигурацию.
  • Networking включает команды для запроса состояния сетевого подключения и включения / отключения подключений.
  • Radio включает команды для запроса состояния подключения к сети WiFi и включения / отключения подключений.
  • Monitor включает команды для мониторинга активности NetworkManager и наблюдения за изменениями состояния сетевых подключений.
  • Connection включает команды для управления сетевыми интерфейсами, для добавления новых соединений и удаления существующих.
  • Device в основном используется для изменения параметров, связанных с устройствами (например, имени интерфейса) или для подключения устройств с использованием существующего соединения.
  • Secret регистрирует nmcli в качестве «секретного агента» NetworkManager, который прослушивает тайные сообщения. Эта секция используется редко, потому что nmcli при подключении к сетям по дефолту работает именно так.
Читайте также:  Windows для видеокарты radeon hd 5770

Простые примеры

Перед началом работы убедитесь, что NetworkManager запущен и nmcli может общаться с ним:

Часто работу начинают с просмотра всех профилей сетевых подключений:

Это команда использует действие show для секции Connection.

На тестовой машине крутится Ubuntu 20.04. В данном случае мы нашли три проводных подключения: enp0s3, enp0s8, and enp0s9.

Управление подключениями

Важно понимать, что в nmcli под термином Connection мы подразумеваем сущность, которая содержит всю информацию о соединении. Другими словами, это конфигурация сети. Connection инкапсулирует всю информацию, связанную с соединениями, включая канальный уровень и информацию об IP-адресации. Это уровень 2 и уровень 3 в сетевой модели OSI.

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

Добавление сетевых соединений

Утилита nmcli позволяет быстро добавлять и сразу же настраивать соединения. Например, чтобы добавить Wired connection 2 (с enp0s8), нужно от имени суперпользователя запустить следующую команду:

В опции type мы указываем, что это будет Ethernet-соединение, а в опции ifname (interface name) указываем сетевой интерфейс, который хотим использовать.

Вот что будет после запуска команды:

Создано новое соединение, ethernet-enp0s8. Ему был назначен UUID, тип подключения — Ethernet. Поднимем его с помощью команды up:

Ещё раз проверяем список активных соединений:

Добавлено новое соединение ethernet-enp0s8, оно активно и использует сетевой интерфейс enp0s8.

Настройка подключений

Утилита nmcli позволяет легко менять параметры уже существующих подключений. Например, вам нужно сменить динамический (DHCP) на статический IP-адрес.

Пусть нам нужно установить IP-адрес равным 192.168.4.26. Для этого используем две команды. Первая непосредственно установит IP-адрес, а вторая переключит метод установки IP-адреса на значение «вручную» (manual):

Не забудьте также задать маску подсети. Для нашего тестового подключения это 255.255.255.0, или с /24 для бесклассовой маршрутизации (CIDR).

Чтобы изменения вступили в силу, нужно деактивировать и затем активировать соединение вновь:

Если вам наоборот нужно установить DHCP, вместо manual используйте auto:

Работа с устройствами

Для этого мы используем секцию Device.

Проверка статуса устройств

Запрос информации об устройстве

Для этого используем действие show из секции Device (нужно обязательно указать имя устройства). Утилита показывает достаточно много информации, часто на нескольких страницах.
Давайте посмотрим на интерфейс enp0s8, который использует наше новое соединение. Убедимся, что оно использует ровно тот IP-адрес, который мы установили ранее:

Информации достаточно много. Выделим главное:

  • Имя сетевого интерфейса: enp0s8.
  • Тип соединения: проводное Ethernet-соединение.
  • Мы видим MAC-адрес устройства.
  • Указан Maximum transmission unit (MTU) — максимальный размер полезного блока данных одного пакета, который может быть передан протоколом без фрагментации.
  • Устройство в данный момент подключено.
  • Имя соединения, которое использует устройство: ethernet-enp0s8.
  • Устройство использует тот IP-адрес, который мы установили ранее: 192.168.4.26/24.

Другая информация относится к дефолтным параметрам маршрутизации и шлюза соединения. Они зависят от конкретной сети.

Интерактивный редактор nmcli

У nmcli также имеется простенький интерактивный редактор, в котором кому-то работать может быть комфортнее. Чтобы запустить его, например, для соединения ethernet-enp0s8, используйте действие edit:

У него также есть небольшая справка, которая, правда, уступает по размеру консольной версии:

Если вы введёте команду print и нажмёте Enter, nmcli отобразит все свойства соединения:

Например, чтобы задать для подключения свойство DHCP, введите goto ipv4 и нажмите Enter:

Затем пропишите set method auto и нажмите Enter:

Если вы хотите очистить статический IP-адрес, нажмите Enter. В противном случае введите no и нажмите Enter. Вы можете сохранить его, если думаете, что он понадобится вам в будущем. Но даже с сохраненным статическим IP-адресом будет использован DHCP, если method установлен в значение auto.

Используйте команду save, чтобы сохранить изменения:

Введите quit, чтобы выйти из Интерактивного редактора nmcli. Если передумали выходить — используйте команду back.

И это далеко не всё

Откройте Интерактивный редактор nmcli и посмотрите, сколько существует настроек и сколько свойств имеет каждая настройка. Интерактивный редактор — отличный инструмент, но, если вы хотите использовать nmcli в однострочниках или скриптах, вам понадобится обычная версия для командной строки.

Читайте также:  Универсальный драйвер для принтеров canon lbp 1120 для windows 10 x64

Теперь, когда у вас есть основы, ознакомьтесь со справочной страницей nmcli, чтобы узнать, чем ещё она может вам помочь.

На правах рекламы

Эпичные серверы — это виртуальные серверы на Windows или Linux с мощными процессорами семейства AMD EPYC и очень быстрыми NVMe дисками Intel. Спешите заказать!

Источник

How to Connect to the Internet Using the Linux Command Line

Troubleshoot a broken network install through a series of shell commands

If you installed a headless distribution—a distribution that doesn’t run a graphical desktop—then you won’t have network management tools to help you connect to the internet using a Wi-Fi network. Likewise, if you accidentally deleted key components from your desktop or installed a buggy distribution, the only way to connect to the internet requires using the Linux terminal.

The instructions in this article apply generally to all Linux distributions, however, it’s possible that some distributions won’t act exactly as described here.

Determine Your Wireless Network Interface

From within the terminal enter the following command:

The command outputs a list of active network interfaces.

The most common wireless network interface is wlan0 but can be other things as well, depending on the nature of your hardware and how well optimized your distributions wireless drivers are.

Turn On the Wireless Interface

Ensure that the wireless interface is turned on. Use the following command:

Replace the wlan0 with the name of your network interface.

Scan for Wireless Access Points

Search for networks. Type the following command:

A list of available wireless access points appears. The results look something like this:

Look at the ESSID, which is the name of a wireless network. Find open networks by looking for items that have the Encryption Key set to off.

It’s best to look for a trusted Wi-Fi network ESSID that you know the password to, rather than looking for open ones when possible. Open wi-fi networks generally have no encryption and data transferred could be transmitted insecurely.

Create a WPA Supplicant Configuration File

The most common tool for connecting to WPA-secured wireless networks is WPA Supplicant. Most distributions come with this tool installed by default. Type the following into the shell:

If you see an error that the command cannot be found, then it isn’t installed. You are now in a chicken-and-egg scenario whereby you need this tool to connect to the internet but can’t connect to the internet because you don’t have this tool.

Use an Ethernet connection instead to install wpasupplicant. Without this tool, you cannot proceed.

To create the configuration file for wpa_supplicant, run the following command:

The ESSID will be the ESSID you noted from the iwlist scan command. This command stops without coming back to the shell prompt. Enter the security required for the network and press Enter. To check that the command worked, open the .config folder using the cd and tail commands:

Type the following:

You should see something like this:

Find the Name of Your Wireless Driver

There is one more piece of information you need before connecting to the internet—the driver for your wireless network card.

To find it, run the following command:

The output lists a section called drivers. The list will look something like this:

Generally, wext is a catchall driver if nothing else is available. In this sample listing, the appropriate driver is the nl80211. The listing appears in priority order.

Connect to the Internet

The first step to getting connected is running the wpa_supplicant command:

Replace driver with the driver that you found in the previous section and interface with the device name (e.g., wlan0).

This command runs wpa_supplicant with the specified driver, using the targeted network interface and the configuration file. The -B switch runs the command in the background so the shell prompt returns to the foreground.

Run this one final command:

The DCHP client—dhclient—establishes networking routing on the local network. When it’s active, you’re free to use the internet as normal.

Источник

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