Find connected devices linux

How to Find What Devices are Connected to Network in Linux

Last updated September 30, 2019 By Abhishek Prakash 60 Comments

Brief: This quick trick shows you how to find devices connected to your local network in Linux.

Wireless networks have always been a desirable target for wannabe hackers. Wireless networks are also more vulnerable to hacking than the wired ones.

Forget hacking, do you ever wonder that someone might be leeching off your hard paid wifi network? Maybe a neighbor who once connected to your network and now uses it as his/her own?

It would be nice to check what devices are on your network. This way you can also see if there are some unwanted devices on your network.

So you might end up thinking, “how do I find what devices are connected to my network”?

I’ll show you how to do that in this quick tutorial. Not only it’s a good idea from security point of view, it is also a good little exercise if you have interest in networking.

We will use both, command line and GUI, way for finding out what devices are connected to your local network in Linux. The process is very simple and easy to use even for beginners.

A. Using Linux command to find devices on the network

Step 1: Install nmap

nmap is one of the most popular network scanning tool in Linux. Use the following command to install nmap in Ubuntu based Linux distributions:

You can easily install it in other Linux distributions as well. It should be in the official software repository.

Step 2: Get IP range of the network

Now we need to know the IP address range of the network. Use the ifconfig command to find the IP address in Linux. Look for wlan0 if you are using wifi or eth0 if you are using Ethernet.

$ ifconfig
wlan0 Link encap:Ethernet HWaddr 70:f1:a1:c2:f2:e9
inet addr:192.168.1.91 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::73f1:a1ef:fec2:f2e8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:2135051 errors:0 dropped:0 overruns:0 frame:0
TX packets:2013773 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1434994913 (1.4 GB) TX bytes:636207445 (636.2 MB)

The important things are highlighted in bold. As you see my IP is 192.168.1.91 and the subnet mask is 255.255.255.0 which means that the ip address range on my network varies from 192.168.1.0 to 192.168.1.255.

You may also use ip a command to know your IP address in Ubuntu and other Linux distributions.

At the same time, I’ll recommend you to read about basic Linux networking commands for more information.

Step 3: Scan to find devices connected to your network

It is advisable to use root privileges while scanning the network for more accurate information. Use the nmap command in the following way:

$ sudo nmap -sn 192.168.1.0/24
Starting Nmap 5.21 ( http://nmap.org ) at 2012-09-01 21:59 CEST

Nmap scan report for neufbox (192.168.1.1)
Host is up (0.012s latency).
MAC Address: E0:A1:D5:72:5A:5C (Unknown)
Nmap scan report for takshak-bambi (192.168.1.91)
Host is up.
Nmap scan report for android-95b23f67te05e1c8 (192.168.1.93)
Host is up (0.36s latency).

As you can see that there are three devices connected to my network. The router itself, my laptop and my Galaxy S2.

If you are wondering about why I used 24 in the above command, you should know a little about CIDR notation. It basically means that the scanning will be from 192.168.1.0 to 192.168.1.255.

B. Using GUI tool to find devices connected to network

When I first wrote this article, there was no GUI tool for this task. Then I saw a Google+ discussion about a new network monitoring tool being developed for elementary OS. I suggested including a periodic device scan feature in this tool and the developer readily agreed.

Читайте также:  How to uninstall jdk on windows

So, now we have a GUI tool that does this task. It’s called Nutty. Just run install this app and run it. It will periodically scan for new devices on the network and will notify you if there is a new device.

This application is only available for elementary OS, Ubuntu and hopefully, other Ubuntu based Linux distributions. You can find installation instructions on this detailed article on Nutty.

Oh, you can also log in to your router and see the devices connected to your devices. I let you figure the best way to find devices connected to your network.

Like what you read? Please share it with others.

Источник

How to find Devices connected to your Network using Debian Linux

Sometimes you need to find out which devices are connected to your network. There can be several reasons for this. Your Internet might be running slower than usual, you might notice some suspicious activity that someone is stealing your Wi-Fi, or you might be fixing a problem. Whatever the reason, it’s a good idea to check who else is connected to your network so that appropriate action can be taken.

Nmap is a great tool that can help you find devices attached to your network. It’s an open-source network exploration tool that tells you what other systems are on your network along with their IP addresses, what services they provide, what operating system version they are running, and more. It runs on almost all major operating systems, including Linux, Windows and Mac OS.

In this article, we describe how to install and use Nmap to find devices connected to your Internet.

We will use Debian10 to describe the procedure mentioned in this article. You can use the same procedure for older versions of Debian.

Step 1: Open the Debian Terminal

Launch the Terminal application in your system by going into the Activities tab in the top left corner of your Debian desktop. Then in the search bar, type terminal. When the Terminal icon appears, click on it to launch it.

Step 2: Install the network scanning tool Nmap

Now in the Terminal application, run the following command as sudo to install the network scanning tool Nmap.

When prompted for the password, enter the sudo password.

The system will provide you with a y/n option to confirm the installation. Press Y to confirm and then wait for a while until the installation is completed on your system.

Step 3: Get the IP range/subnet mask of your network

Nmap needs a network ID to scan for the connected device on a specific network. So in order to find network ID, we will need our IP address and the subnet mask.

Run the below command in Terminal to find the IP address and subnet mask of your system:

The above output indicates that our system is using the IP address 192.168.72.164 /24. /24 indicates our subnet mask is 255.255.255.0. It means our network ID is 192.168.72.0 and the network range from 192.168.72.1 to 192.168.72.255. Advertisement

(Note: Network ID is calculated by performing the AND operation of the IP address and the subnet mask. If you do not know how to perform AND operation, you can any online subnet calculator).

Step 4: Scan network for the connected device(s) with Nmap

Now we have our network ID, run the Nmap scan with –sn option using the following syntax:

In our scenario, it would be:

Using Nmap with –sn option does not scan the ports, it only returns a list of live hosts:

The above results show there are three active devices connected on our network including our system (192.168.72.164 )

That is all there is to it! We have learned how to find the connected devices connected to a network using the Nmap tool. It can help you to identify which unwanted users are connected to and using your network bandwidth.

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

Find Devices Connected to Your Network with nmap

As Ubuntu users, we might want to know if we are the only ones using our network, especially wi-fi, or are there any other unwanted users leeching on our network bandwidth. This skill also comes in handy when we want to be sure that any hacker is not accessing our system by being connected to our network.

Читайте также:  Поиск по названию папки linux

Scan your network with Nmap on Ubuntu 20.04 LTS

This article describes a step by step procedure to use the Nmap tool that gives you a list of all devices connected to your network.

We have run the commands and procedures mentioned in this article on a Ubuntu 20.04 LTS system.

Step 1: Open the Ubuntu command line

We will be using the Ubuntu command line, the Terminal, in order to view the devices connected to our network. Open the Terminal either through the system Dash or the Ctrl+Alt+T shortcut.

Step 2: Install the network scanning tool Nmap

When it comes to reliable network scanning, Nmap is a tool that you can totally depend on.

Enter the following command as sudo in the Terminal application in order to install the tool.

The system will ask you the password for sudo as only an authorized user can install/uninstall and configure software on Ubuntu.

The system will also prompt you with a y/n option to confirm the installation. Please enter Y and hit enter to begin the installation process.

Step 3: Get the IP range/subnet mask of your network

In order to know which devices are connected to your network, you first need to get the IP range or the subnet mask of your network. We will be using the ifconfig command in order to get this IP. In order to run the ifconfig command, we need to have net-tools installed on our Ubuntu. Use the following command in order to install net-tools if you already do not have it installed on your system:

The system will prompt you with a y/n option to confirm the installation. Please enter Y and hit enter to begin the installation process.

Once you have the net-tools utility available, run the following command in order to get information about the network(s) your system is connected to:

The highlighted IP from the output indicates that our system is using 192.168.100.0 subnet mask and the range is 255. Thus our network IP range is from 192.168.100.0 to 192.168.100.255.

Alternative (UI)

Instead of using the ifconfig tool, you can get the subnet mask IP through the Ubuntu GUI as well.

Access the Settings utility from the system Dash and check the details of your network either by clicking the settings icon against the wifi or ethernet network you are connected to.

In this example, we have checked the settings of a wi-fi network we are currently connected to.

The highlighted ipv4 address or the Default Route address indicates that we are connected to a subnet IP 192.168.100.0

Step 4: Scan network for connected device(s) with Nmap

Through the Nmap tool, you can scan the report of all devices connected to a network by providing the subnet mask IP as follows:

The output shows that there are 3 devices connected on the network; one is the router itself, one is the Linux system I am using on my laptop, and the third one is my phone.

Step 5: Exit the Terminal

Use the following command in order to exit the Terminal application after you are done with extracting the required information:

In this article, you have learned how an Ubuntu user can install and use the Nmap command. We showed you how to view which devices are connected to the network he/she is using. This way you can verify that no unauthorized device is connected to your network.

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

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

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

Перед началом работы убедитесь, что 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. Спешите заказать!

Источник

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