Please check your connection to the internet 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

Читайте также:  Css if firefox windows

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.

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!!

Источник

ERROR: It seems that you are offline. Please check your internet connection. #306

Comments

nikior9 commented Jun 12, 2018 •

Checklist for submitting an issue to KickThemOut :

  • I have carefully read the README file and haven’t managed to resolve my issue.
  • I have searched the issues of this repo and believe that this is not a duplicate.
  • I am running the latest version of KickThemOut.
  • OS name & version: macOS Sierra 10.12.6
  • Python version: 3.6
  • Scapy version: 2.4
  • Nmap version: 7.70
  • Link of Gist: https://gist.github.com/nikior9/e11cbea186b9746caebd16921346486b

ERROR: It seems that you are offline. Please check your internet connection.

Google opens perfectly. Changing google to any other website didn’t help

The text was updated successfully, but these errors were encountered:

MrdotSpock commented Jun 20, 2018 •

You can fix it using a little hack.

  1. Open kickthemout.py
  2. Find this line of code def checkInternetConnection(): . In my editor it’s line 128
  3. Replace function body with this return True . (delete everything from line 129 to line 135)
Читайте также:  Xerox b1025 driver linux

Note: This is just a temporary fix and it should be solved in better way.
The problem is probably with function urlopen.

Hope this helps

nikior9 commented Jun 21, 2018

Tried it before, didn’t help. It’s like loading but infinitely and uses a lot of CPU

k4m4 commented Jun 25, 2018 •

Hi there. Thank you for bringing this to our attention; I will try to reproduce this issue locally. For now, you can delete lines 738-745:

in order for the script to run normally. Thanks again.

k4m4 commented Nov 7, 2018

This issue should be resolved in PR #341. If not, please don’t hesitate to re-open it. Thanks!

N0va1 commented Apr 11, 2019

make sure there is an internet connection

def checkInternetConnection():
try:
urlopen(‘https://github.com’, timeout=0)
return False
except URLError as err:
return True
except KeyboardInterrupt:
shutdown()

Flori201 commented Apr 23, 2019

make sure there is an internet connection

def checkInternetConnection():
try:
urlopen(‘https://github.com’, timeout=0)
return False
except URLError as err:
return True
except KeyboardInterrupt:
shutdown()

guinevereperez commented May 12, 2019

You can fix it using a little hack.

  1. Open kickthemout.py
  2. Find this line of code def checkInternetConnection(): . In my editor it’s line 128
  3. Replace function body with this return True . (delete everything from line 129 to line 135)

Note: This is just a temporary fix and it should be solved in better way.
The problem is probably with function urlopen.

This fixed the problem for me thank you!

Upanori7 commented Nov 16, 2019

You can fix it using a little hack.

  1. Open kickthemout.py
  2. Find this line of code def checkInternetConnection(): . In my editor it’s line 128
  3. Replace function body with this return True . (delete everything from line 129 to line 135)

Note: This is just a temporary fix and it should be solved in better way.
The problem is probably with function urlopen.

l cant run any command like those aboved, this is the output results :

/kickthemout#bash kickthemout.py
kickthemout.py: line 8:
Copyright (C) 2017-18 Nikolaos Kamarinakis (nikolaskam@gmail.com) & David Schütz (xdavid@protonmail.com)
See License at nikolaskama.me (https://nikolaskama.me/kickthemoutproject)
: No such file or directory
kickthemout.py: line 10: import: command not found
kickthemout.py: line 11: from: command not found
kickthemout.py: line 12: BLUE,: command not found
kickthemout.py: line 14: try:: command not found
kickthemout.py: line 16: syntax error near unexpected token !=’ kickthemout.py: line 16: if os.geteuid() != 0

l am using «bash» command instead «Open»
l am using Termux and its always end up with : its seems you are offline. Please check your internet connection

Источник

Управляем сетевыми подключениями в 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 при подключении к сетям по дефолту работает именно так.
Читайте также:  Loop hero mac os

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

Перед началом работы убедитесь, что 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 в однострочниках или скриптах, вам понадобится обычная версия для командной строки.

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

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

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

Источник

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