- Nmap — руководство для начинающих
- 29 Practical Examples of Nmap Commands for Linux System/Network Administrators
- How to Install NMAP in Linux
- 1. Scan a System with Hostname and IP Address
- 2. Scan using “-v” option
- Scan Multiple Hosts
- 4. Scan a whole Subnet
- 5. Scan Multiple Servers using last octet of IP address
- 6. Scan list of Hosts from a File
- 7. Scan an IP Address Range
- 8. Scan Network Excluding Remote Hosts
- 9. Scan OS information and Traceroute
- 10. Enable OS Detection with Nmap
- 11. Scan a Host to Detect Firewall
- 12. Scan a Host to check its protected by Firewall
- 13. Find out Live hosts in a Network
- 14. Perform a Fast Scan
- 15. Find Nmap version
- 16. Scan Ports Consecutively
- 17. Print Host interfaces and Routes
- 18. Scan for specific Port
- 19. Scan a TCP Port
- 20. Scan a UDP Port
- 21. Scan Multiple Ports
- 22. Scan Ports by Network Range
- 23. Find Host Services version Numbers
- 24. Scan remote hosts using TCP ACK (PA) and TCP Syn (PS)
- 25. Scan Remote host for specific ports with TCP ACK
- 26. Scan Remote host for specific ports with TCP Syn
- 27. Perform a stealthy Scan
- 28. Check most commonly used Ports with TCP Syn
- 29. Perform a tcp null scan to fool a firewall
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Related Posts
- 36 thoughts on “29 Practical Examples of Nmap Commands for Linux System/Network Administrators”
- Got something to say? Join the discussion. Cancel reply
Nmap — руководство для начинающих
Многие слышали и пользовались замечательной утилитой nmap. Ее любят и системные администраторы, и взломщики. Даже Голливуд знает про нее — в фильме «Матрица» при взломе используется nmap.
nmap — это аббревиатура от «Network Mapper», на русский язык наиболее корректно можно перевести как «сетевой картограф». Возможно, это не лучший вариант перевода на русский язык, но он довольно точно отображает суть — инструмент для исследования сети и проверки безопасности. Утилита кроссплатформенна, бесплатна, поддерживаются операционных системы Linux, Windows, FreeBSD, OpenBSD, Solaris, Mac OS X.
Рассмотрим использование утилиты в Debian. В стандартной поставке дистрибутива nmap отсутствует, установим его командой
# aptitude install nmap
Nmap умеет сканировать различными методами — например, UDP, TCP connect(), TCP SYN (полуоткрытое), FTP proxy (прорыв через ftp), Reverse-ident, ICMP (ping), FIN, ACK, SYN и NULL-сканирование. Выбор варианта сканирования зависит от указанных ключей, вызов nmap выглядит следующим образом:
Для опытов возьмем специальный хост для экспериментов, созданный самими разработчиками nmap — scanme.nmap.org. Выполним от root’а
Ключи сканирования задавать необязательно — в этом случае nmap проверит хост на наличие открытых портов и служб, которые слушают эти порты.
Запустим командой:
Через несколько секунд получим результат:
Interesting ports on scanme.nmap.org (74.207.244.221):
Not shown: 998 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
Ничего необычного, ssh на стандартном порту и http на 80. Nmap распознаёт следующие состояния портов: open, filtered, closed, или unfiltered. Open означает, что приложение на целевой машине готово для принятия пакетов на этот порт. Filtered означает, что брандмауэр, фильтр, или что-то другое в сети блокирует порт, так что Nmap не может определить, является ли порт открытым или закрытым. Closed — не связанны в данный момент ни с каким приложением, но могут быть открыты в любой момент. Unfiltered порты отвечают на запросы Nmap, но нельзя определить, являются ли они открытыми или закрытыми.
# nmap -O scanme.nmap.org
Хинт: Если во время сканирования нажать пробел — можно увидеть текущий прогресс сканирования и на сколько процентов он выполнен. Через несколько секунд получаем ответ, в котором пока что интересна строчка Device type:
Device type: general purpose|WAP|webcam|storage-misc
Running (JUST GUESSING) : Linux 2.6.X|2.4.X (93%), AXIS Linux 2.6.X (89%), Linksys Linux 2.4.X (89%)
Aggressive OS guesses: Linux 2.6.17 — 2.6.28 (93%), Linux 2.6.9 — 2.6.27 (93%), Linux 2.6.24 (Fedora 8) (92%), Linux 2.6.18 (Slackware 11.0) (92%), Linux 2.6.19 — 2.6.26 (92%), OpenWrt (Linux 2.4.32) (91%), Linux 2.6.22 (91%), Linux 2.6.22 (Fedora Core 6) (90%), Linux 2.6.13 — 2.6.27 (90%), Linux 2.6.9 — 2.6.18 (90%)
No exact OS matches for host (test conditions non-ideal).
Вообще, точную версию ядра средствами nmap определить невозможно, но примерную дату «свежести» и саму операционную систему определить можно. Можно просканировать сразу несколько хостов, для этого надо их перечислить через пробел:
# nmap -O example.com example2.com
Вернемся к нашему подопытному хосту. Хочется узнать поподробнее, какой используется софт. Попробуем уточнить полученные данные с помощью ключей -sV:
# nmap -sV example.com example2.com
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 5.3p1 Debian 3ubuntu7 (protocol 2.0)
80/tcp open http Apache httpd 2.2.14 ((Ubuntu))
Service Info: OS: Linux
Прогресс налицо — мы узнали точные названия используемых служб и даже их версии, а заодно узнали точно, какая операционная система стоит на сервере. С расшифровкой никаких проблем не возникает, все вполне понятно.
Агрессивное сканирование можно провести, указав ключ -A
# nmap -A scanme.nmap.org
Nmap выведет очень много информации, я не стану приводить пример. Сканирование может длится довольно долго, занимая несколько минут.
В локальных сетях или просто имея на руках диапазон ip адресов, удобно проверить их на занятость с помощью ключей -sP:
# nmap -sP 192.168.1.0/24
Сканирование проходит довольно быстро, так как по сути это обычный ping-тест, отвечает ли хост на ping. Следует учесть, что хост может не отвечать на ping из-за настроек фаерволла. Если нужный участок сети нельзя ограничить маской, можно указать диапазон адресов, с какого и по какой надо провести сканирование. Например, есть диапазон адресов с 192.168.1.2 до 192.168.1.5. Тогда выполним:
# nmap -sP 192.168.1.2-5
Ответ будет выглядеть так:
Host 192.168.1.2 is up (0.0023s latency)
Host 192.168.1.3 is up (0.0015s latency)
Host 192.168.1.4 is up (0.0018s latency)
Host 192.168.1.5 is up (0.0026s latency)
В моем случае все ip в данный момент были в сети.
Это далеко не все возможности nmap, но уместить их в рамках одной статьи несколько сложновато.
Если вам ближе GUI — есть замечательная утилита Zenmap — графическая оболочка для nmap, умеющая заодно и строить предполагаемую карту сети.
Хочу предупредить, что сканирование портов на удаленных машинах может нарушать закон.
UDPInflame уточнил, что сканирование портов все-таки не является противозаконным.
Источник
29 Practical Examples of Nmap Commands for Linux System/Network Administrators
The Nmap aka Network Mapper is an open source and a very versatile tool for Linux system/network administrators. Nmap is used for exploring networks, perform security scans, network audit and finding open ports on remote machine. It scans for Live hosts, Operating systems, packet filters and open ports running on remote hosts.
Nmap Commands and Examples
I’ll be covering most of NMAP usage in two different parts and this is the first part of nmap serious. Here in this setup, I have used two servers without firewall to test the working of the Nmap command.
- 192.168.0.100 – server1.tecmint.com
- 192.168.0.101 – server2.tecmint.com
Nmap command usage
How to Install NMAP in Linux
Most of the today’s Linux distributions like Red Hat, CentOS, Fedoro, Debian and Ubuntu have included Nmap in their default package management repositories called Yum and APT. The both tools are used to install and manage software packages and updates. To install Nmap on distribution specific use the following command.
Once you’ve install latest nmap application, you can follow the example instructions provided in this article.
1. Scan a System with Hostname and IP Address
The Nmap tool offers various methods to scan a system. In this example, I am performing a scan using hostname as server2.tecmint.com to find out all open ports, services and MAC address on the system.
Scan using Hostname
Scan using IP Address
2. Scan using “-v” option
You can see that the below command with “-v” option is giving more detailed information about the remote machine.
Scan Multiple Hosts
You can scan multiple hosts by simply writing their IP addresses or hostnames with Nmap.
4. Scan a whole Subnet
You can scan a whole subnet or IP range with Nmap by providing * wildcard with it.
On above output you can see that nmap scanned a whole subnet and gave the information about those hosts which are Up in the Network.
5. Scan Multiple Servers using last octet of IP address
You can perform scans on multiple IP address by simple specifying last octet of IP address. For example, here I performing a scan on IP addresses 192.168.0.101, 192.168.0.102 and 192.168.0.103.
6. Scan list of Hosts from a File
If you have more hosts to scan and all host details are written in a file , you can directly ask nmap to read that file and perform scans. Let’s see how to do that.
Create a text file called “nmaptest.txt” and define all the IP addresses or hostname of the server that you want to do a scan.
Next, run the following command with “iL” option with nmap command to scan all listed IP address in the file.
7. Scan an IP Address Range
You can specify an IP range while performing scan with Nmap.
8. Scan Network Excluding Remote Hosts
You can exclude some hosts while performing a full network scan or when you are scanning with wildcards with “–exclude” option.
9. Scan OS information and Traceroute
With Nmap, you can detect which OS and version is running on the remote host. To enable OS & version detection, script scanning and traceroute, we can use “-A” option with NMAP.
In above Output, you can see that nmap is came up with TCP/IP fingerprint of the OS running on remote hosts and being more specific about the port and services running on the remote hosts.
10. Enable OS Detection with Nmap
Use the option “-O” and “-osscan-guess” also helps to discover OS information.
11. Scan a Host to Detect Firewall
The below command will perform a scan on a remote host to detect if any packet filters or Firewall is used by host.
12. Scan a Host to check its protected by Firewall
To scan a host if it is protected by any packet filtering software or Firewalls.
13. Find out Live hosts in a Network
With the help of “-sP” option we can simply check which hosts are live and up in Network, with this option nmap skips port detection and other things.
14. Perform a Fast Scan
You can perform a fast scan with “-F” option to scans for the ports listed in the nmap-services files and leaves all other ports.
15. Find Nmap version
You can find out Nmap version you are running on your machine with “-V” option.
16. Scan Ports Consecutively
Use the “-r” flag to don’t randomize.
17. Print Host interfaces and Routes
You can find out host interface and route information with nmap by using “–iflist” option.
In above output, you can see that map is listing interfaces attached to your system and their respective routes.
18. Scan for specific Port
There are various options to discover ports on remote machine with Nmap. You can specify the port you want nmap to scan with “-p” option, by default nmap scans only TCP ports.
19. Scan a TCP Port
You can also specify specific port types and numbers with nmap to scan.
20. Scan a UDP Port
21. Scan Multiple Ports
You can also scan multiple ports using option “-p“.
22. Scan Ports by Network Range
You can scan ports with ranges using expressions.
23. Find Host Services version Numbers
We can find out service’s versions which are running on remote hosts with “-sV” option.
24. Scan remote hosts using TCP ACK (PA) and TCP Syn (PS)
Sometimes packet filtering firewalls blocks standard ICMP ping requests, in that case, we can use TCP ACK and TCP Syn methods to scan remote hosts.
25. Scan Remote host for specific ports with TCP ACK
26. Scan Remote host for specific ports with TCP Syn
27. Perform a stealthy Scan
28. Check most commonly used Ports with TCP Syn
29. Perform a tcp null scan to fool a firewall
That’s it with NMAP for now, I’ll be coming up more creative options of NMAP in our second part of this serious. Till then, stay tuned with us and don’t forget to share your valuable comments.
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.
Related Posts
36 thoughts on “29 Practical Examples of Nmap Commands for Linux System/Network Administrators”
I was doing udp port scanning on nmap .I have some udp ports open but in nmap it is showing open | filtered only. Please give me solution for this. Is there any other tool for this?
This article was very helpful! Thanks for taking the time to write this.
What is the best way to go about finding all ports being used by MySQL for clustering purposes?
I am on Linux platform with MySQL NDB 5.7. I am trying to monitor all traffic related to MySQL clustering – between data nodes, management node and sql nodes. To that end, I used netstat to list all open ports listening on my machine before starting MySQL cluster. Then, I started MySQL cluster and ran netstat again. I assumed that the ports that were listening the second time around, but not the first time, were related to MySQL clustering.
But there are two problems with this. First, there could be ports opened by other processes between the two netstat runs. Second, MySQL might open other ports after I ran the netstat command the second time.
What is the best way to go about finding all ports being used by MySQL for clustering purposes? I believe ephemeral ports are picked dynamically, so perhaps if I knew all the MySQL clustering related processes that would be running, I can figure out every port that they are using. Pointers will be very welcome.
very nice article thanks although i did already learned all this just by reading the man page supplied by nmap 🙂
Good article, but using a version of Nmap many versions behind. Also should review the NSE ( NMAP SCRIPTING ENGINE) , very powerful.
Version 7 of nmap brings a lot of interesting features to the table.
Thanks for updating about NSE (NMAP SCRIPTING ENGINE).. never heard about it…Let me check and see what kind of other features its provides than standard Nmap..
Got something to say? Join the discussion. Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Источник