Содержание
- Описание
- Замечания о переводе
- Сводка опций
- Определение цели сканирования
- Обнаружение хостов
- Основы сканирования портов
- Различные приемы сканирования портов
- Определение портов и порядка сканирования
- Обнаружение служб и их версий
- Определение ОС
- Скриптовый движок Nmap(NSE — Nmap Scripting Engine)
- Опции управления временем и производительностью
- Обход Брандмауэров/IDS
- Вывод результатов
- Различные опции
- Взаимодействие во время выполнения
- Примеры
- Ошибки
- Автор
- Юридические уведомления
- Unofficial Translation Disclaimer / Отречение неофициального перевода
- Авторское право и лицензия Nmap
- Creative Commons License для этого справочного руководства Nmap
- Доступность исходного кода и общественные вклады
- Отсутствие гарантии
- Несоответствующее использование
- Стороннее программное обеспечение
- Классификация по контролю экспорта Соединенных Штатов
Название
nmap — Утилита для исследования сети и сканер портов
Синтаксис
nmap [
<Тип сканирования>
…] [
<Опции>
] {
<цель сканирования>
}
Описание
| Примечание | |
|---|---|
|
Этот документ описывает версию Nmap 4.22SOC8. Последняя документация |
Nmap («Network Mapper») — это утилита с открытым исходным кодом для исследования сети и
проверки безопасности. Она была разработана для быстрого сканирования больших сетей, хотя прекрасно справляется
и с единичными целями. Nmap использует «сырые» IP пакеты оригинальным способом, чтобы определить какие хосты
доступны в сети, какие службы (название приложения и версию) они предлагают, какие операционные системы (и версии
ОС) они используют, какие типы пакетных фильтров/брандмауэров используются и еще множество других характеристик.
В то время, как Nmap обычно используется для проверки безопасности, многие системные администраторы находят ее
полезной для обычных задач, таких как контролирование структуры сети, управление расписаниями запуска
служб и учет времени работы хоста или службы.
Выходные данные Nmap это список просканированных целей с дополнительной информацией по каждой из них в зависимости
от заданных опций. Ключевой информацией является «таблица важных портов».
Эта таблица содержит номер порта, протокол, имя службы и состояние. Состояние может иметь значение
open (открыт), filtered (фильтруется),
closed (закрыт) или unfiltered (не
фильтруется).
Открыт
означает, что приложение на целевой машине готово для установки соединения/принятия пакетов на этот порт.
Фильтруется
означает, что брандмауэр, сетевой фильтр, или какая-то другая помеха в сети блокирует порт, и Nmap не может установить
открыт этот порт или закрыт.
Закрытые
порты не связаны ни с каким приложением, но могут быть открыты в любой момент. Порты расцениваются как
не фильтрованные, когда они отвечают на запросы Nmap, но Nmap не может определить открыты они или закрыты. Nmap выдает комбинации
открыт|фильтруется
и закрыт|фильтруется, когда не может определить, какое из этих двух
состояний описывает порт. Эта таблица также может предоставлять детали о версии программного обеспечения, если это
было запрошено. Когда осуществляется сканирование по IP протоколу (-sO), Nmap предоставляет
информацию о поддерживаемых протоколах, а не об открытых портах.
В дополнение к таблице важных портов Nmap может предоставлять дальнейшую информацию о целях: преобразованные
DNS имена, предположение об используемой операционной системе, типы устройств и MAC адреса.
Типичное сканирование с использованием Nmap показано в Пример 1. Единственные аргументы, использованные в этом примере — это -A, для определения версии ОС,
сканирования с использованием скриптов и трассировки; -T4 для более быстрого выполнения; затем
два целевых хоста.
Пример 1. Типичный пример сканирования с помощью Nmap
# nmap -A -T4 scanme.nmap.org playground Starting Nmap ( https://nmap.org ) Interesting ports on scanme.nmap.org (64.13.134.52): (The 1663 ports scanned but not shown below are in state: filtered) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 3.9p1 (protocol 1.99) 53/tcp open domain 70/tcp closed gopher 80/tcp open http Apache httpd 2.0.52 ((Fedora)) 113/tcp closed auth Device type: general purpose Running: Linux 2.4.X|2.5.X|2.6.X OS details: Linux 2.4.7 - 2.6.11, Linux 2.6.0 - 2.6.11 Interesting ports on playground.nmap.org (192.168.0.40): (The 1659 ports scanned but not shown below are in state: closed) PORT STATE SERVICE VERSION 135/tcp open msrpc Microsoft Windows RPC 139/tcp open netbios-ssn 389/tcp open ldap? 445/tcp open microsoft-ds Microsoft Windows XP microsoft-ds 1002/tcp open windows-icfw? 1025/tcp open msrpc Microsoft Windows RPC 1720/tcp open H.323/Q.931 CompTek AquaGateKeeper 5800/tcp open vnc-http RealVNC 4.0 (Resolution 400x250; VNC port: 5900) 5900/tcp open vnc VNC (protocol 3.8) MAC Address: 00:A0:CC:63:85:4B (Lite-on Communications) Device type: general purpose Running: Microsoft Windows NT/2K/XP OS details: Microsoft Windows XP Pro RC1+ through final release Service Info: OSs: Windows, Windows XP Nmap finished: 2 IP addresses (2 hosts up) scanned in 88.392 seconds
Самую новую версию Nmap можно скачать с https://nmap.org. Самая новая версия страницы справки Nmap
(man page) расположена по адресу https://nmap.org/book/man.html.
Are you overwhelmed by the countless Nmap commands and their descriptions in the official documentation? We hear you, and we’ve got you covered. The good news is no one needs to master every element of Nmap to start using it effectively day-to-day.
We’re here to share the top 20 Nmap commands you’ll use in your career. Whether you’re an ethical hacker, a student learning the trade, or a fan of capture-the-flag events, these top 20 basic Nmap commands will get you through almost every situation.
No longer will Nmap’s complex ins and outs burden you. Let’s scroll down and start scanning our targets for vulnerabilities now.
What Is Nmap?
Network Mapper (Nmap) is a command-line-based multi-platform (Windows, Mac OS X, Linux, etc.) network scanning application designed to detect hosts and services on a computer network.
Nmap is a vital tool for any student or professional in cyber security. This free and open-source utility helps you gather network information and assess the security posture of devices in the networks you scan with it. Nmap can identify a host’s operating system, running applications, open ports, firewall information, and more.
If you don’t have it yet, install Nmap here.
How To Use Nmap
The Nmap command syntax is the “nmap” keyword followed by at least two arguments:
nmap <flag(s)> <target/file>
All flags begin with one (-) or two (—) hyphens, and a single Nmap command may contain multiple flags. A target is typically an IPv4/IPv6 address or address range.
Some flags apply to files instead of targets; those are for Nmap commands that read from a file or write Nmap scan results to files.
Now that you know how to operate Nmap, we’re showing you 20 Nmap commands that’ll come in handy.
All 20 Commands at a Glance
The following table lists our top 20 Nmap commands:
For more Nmap commands, refer to our Nmap cheat sheet.
Nmap Command Generator
Say goodbye to the hassle of trying to remember the exact syntax for your Nmap commands! With our Nmap Command Generator, you can simply say what you need Nmap to do and we will generate the command for you.
1. List all hosts on a network
nmap -sL <target>
This type of scan (list scan) is a version of host discovery that only lists each host on the selected network (s) and doesn’t send any packets to the target hosts. By default, Nmap does a reverse DNS lookup to get host names.
2. Disable port scanning and only discover active hosts
nmap -sn <target>
nmap -sP <target>
With this option, Nmap will only print the names of hosts that have responded to the host discovery probes without any port scan. By default, this option is slightly more intrusive than the list scan. Use this option as a “ping sweep” to count available machines on a network or monitor server availability.
3. Discover the network path to a host
nmap --traceroute <target>
A packet may traverse several hosts before reaching its destination. This option allows you to trace this packet’s journey from host to host.
4. Scan for open ports and version information of services
nmap -sV <target>
When preparing for and doing pentesting, the command above helps you find open ports and determine the versions of running processes. Having accurate version numbers enables you to assess a device’s vulnerabilities.
5. Scan the ports specified
nmap -p <port number or numbers> <target>
Use this option to tell Nmap which ports you want to scan. It admits individual port numbers and ranges separated by a hyphen (e.g., 1-1023). Nmap can also scan port zero, but you must specify it explicitly.
When scanning a combination of protocols (e.g., TCP and UDP), you can specify a particular protocol by preceding the port numbers using a single-letter qualifier:
T: for TCP,U: for UDP,S: for SCTP, andP: for IP Protocol.
The qualifier lasts until you specify another qualifier. For example, the argument -p U:53,111,137,T:21-25,80,139,8080 would scan UDP ports 53, 111, and 137, and the listed TCP ports.
6. Scan all ports on a target
nmap -p- <target>
This command will scan ports numbered 1 through 65535.
7. Scan for open ports on the target
nmap --open <target>
Only show hosts with open or likely open ports, and list those ports. Here, “open ports” refer to any ports that may be open, which includes the port states “open,” “open|filtered (open or filtered),” and “unfiltered.” The Nmap official documentation has more on port states.
8. Scan for the specified number of most common ports
nmap --top-ports <number> <target>
Specify an arbitrary number of the most commonly open ports for Nmap to scan. Nmap scans the <number> highest-ratio ports found in nmap-services file after excluding all ports specified by —exclude-ports. <number> must be at least 1.
9. Perform a TCP connect scan
nmap -sT <target>
A TCP connect scan is where Nmap asks the underlying operating system to establish a connection with the target machine and port by issuing the “connect” system call. The “connect” system call is the same high-level system call that web browsers, P2P clients, and most other network-enabled applications use to establish a connection.
10. Scan for UDP ports
nmap -sU <target>
In a UDP scan, Nmap sends a UDP packet to every targeted port, usually without extra data, except for ports where a payload would increase the response rate, such as 53 and 161. If Nmap receives an error message, the port is unavailable. Avoid rushing UDP scans, as operating systems such as Linux and Solaris impose strict rate limits.
11. Enable OS detection, version detection, script scanning, and traceroute
nmap -A <target>
This option turns on operating system detection and the advanced and aggressive functions mentioned above.
12. Scan for remote operating system
nmap -O <target>
Perform remote operating system detection using TCP/IP stack fingerprinting: Nmap sends a series of TCP and UDP packets to the remote host, examines every bit in the responses, compares its nmap-os-db database of more than 2,600 known operating system fingerprints, and prints out the operating system details if there is a match.
13. Scan a target with a specific timing template
nmap -T<timing template: 0-5> <target>
Timing templates allow users to specify how aggressive they wish to be, leaving Nmap to pick the exact timing values. The template names are paranoid (0), sneaky (1), polite (2), normal (3), aggressive (4), and insane (5). Polite mode slows the scan to use less bandwidth and target machine resources to evade intrusion detection systems.
14. Increase the verbosity of the output (second level)
nmap -vv <target>
A single -v flag increases the verbosity level, causing Nmap to print more information about the scan in progress, such as open ports found in real-time and completion time estimates for scans that may take considerable time. Use it twice or more for even greater verbosity: -vv, or give a verbosity level directly, for example -v3.
15. Scan for commonly used ports and services
nmap -sC <target>
This command is equivalent to nmap --script=default <target>. It uses Nmap’s default Nmap Scripting Engine (NSE) scripts to scan for individual ports and protocols, including HTML and POP3. The scripts are mostly safe but contain intrusive processes. For example, the default script “jdwp-info” tries to exploit Java’s remote debugging port.
16. Run a script on the target
nmap --script <script type> <target>
Nmap runs a script scan using the comma-separated list of filenames, script categories, and directories.
17. Run all vulnerability scans on the target
nmap --script vuln <target>
The vuln scripts check for specific known vulnerabilities, and Nmap generally only reports results when it finds any. Examples include realvnc-auth-bypass and afp-path-vuln.
18. Read targets from a text file
nmap -iL <file>
Nmap reads a list of targets from a file as input. Entries can be in any format Nmap accepts on the command line (IP address, hostname, CIDR, IPv6, or octet ranges). Each entry must have spaces, tabs, or newlines as delimiters. The input file may contain comments that start with # and extend to the end of the line.
19. Save scan results in normal, XML, and grepable formats at once
nmap -oA <file>
Store Nmap scan results as three separate files, with <file> as the base file name and file extensions .nmap (normal), .xml (XML), and .gnmap (grepable). Like most programs, <file> may include a directory path, such as ~/folder1/foo/ on Unix or c:\folder2\bar on Windows.
20. Save the scan results to a normal format
nmap -oN <file>
Write the Nmap scan results to the given file name. Only use this command together with a valid Nmap scan command containing some <target> as shown in the example below (nmap --top-ports 10 192.168.1.1-10 -oN tenports.txt):
Conclusion
We hope this brief guide to the top 20 Nmap commands helps you in your IT or cyber security journey. Don’t forget to share this article with someone who needs it. To learn more about Nmap, check out our other articles on Nmap and courses on Nmap below:
Frequently Asked Questions
How do I do a fast scan in Nmap?
Use the flag -T5 followed by your target IP address or address range. The -T part refers to “timing template,” and 5 is the highest speed offered.
Is it okay to Nmap scan a website?
You must have explicit permission from the website owner (for example, you own the website) to avoid violating the law. Check out our article “Is Port Scanning Legal?” for details.
How do I scan all ports with Nmap?
Use the flag -p- followed by your target IP address or address range.
How do I fully scan a target with Nmap?
What you want to do is find out as much information about a target as Nmap can. Use the flag -p- to scan all ports and -A for operating system detection, version detection, script scanning, and traceroute, followed by your target IP address or address range.
-
Cassandra is a writer, artist, musician, and technologist who makes connections across disciplines: cyber security, writing/journalism, art/design, music, mathematics, technology, education, psychology, and more. She’s been a vocal advocate for girls and women in STEM since the 2010s, having written for Huffington Post, International Mathematical Olympiad 2016, and Ada Lovelace Day, and she’s honored to join StationX. You can find Cassandra on LinkedIn and Linktree.
Nmap (Network Mapper) — это мощный инструмент для сетевого сканирования, который используется для обнаружения хостов и служб в сети. В этом руководстве мы подробно разберем его основные функции, команды и возможности, чтобы помочь начинающим пользователям освоить Nmap.
Содержание
- Что такое Nmap?
- Установка Nmap
- Основные команды Nmap
- Продвинутые функции Nmap
- Выводы
Nmap — это бесплатное, открытое программное обеспечение для сетевого сканирования, разработанное Гордоном Лайоном. Оно широко используется администраторами безопасности для обнаружения устройств в сети, проверки доступных портов, идентификации служб и поиска уязвимостей.
«Знание — это сила. А Nmap — это инструмент, который дает вам это знание.» — Gordon Lyon
Выделенные серверы и VPS/VDS в Нидерландах
Оффшорные, доступные, стабильные. Оплата в крипто.
Подробнее
Nmap может использоваться как в локальных сетях, так и в глобальных для анализа состояния сетевых узлов и служб. Он поддерживает различные типы сканирования, такие как TCP-синхронизация (SYN), UDP, и другие типы анализа сетей.
Установка Nmap
Для начала работы с Nmap его необходимо установить на ваш компьютер. В зависимости от вашей операционной системы процесс установки может отличаться. Рассмотрим установку на различных платформах.
Установка Nmap на Linux
На Linux Nmap можно установить с помощью пакетного менеджера.
sudo apt install nmap
Для пользователей других дистрибутивов, таких как Fedora или Arch Linux:
sudo dnf install nmap
sudo pacman -S nmap
Установка Nmap на macOS
На macOS вы можете установить Nmap с помощью Homebrew. Если у вас не установлен Homebrew, его можно скачать и установить с официального сайта Homebrew.
brew install nmap
Установка Nmap на Windows
Для установки на Windows, вам необходимо скачать установочный файл с официального сайта Nmap и следовать инструкциям установщика.
Основные команды Nmap
Рассмотрим несколько ключевых команд, которые помогут вам начать работу с Nmap. Вот основные команды для простого сканирования хостов и сетей:
Сканирование одного IP-адреса
nmap 192.168.1.1
Эта команда выполняет базовое сканирование IP-адреса 192.168.1.1, выявляя активные порты.
Сканирование диапазона IP-адресов
nmap 192.168.1.1-254
Используйте эту команду, чтобы сканировать целую сеть или диапазон адресов, например, от 192.168.1.1 до 192.168.1.254.
Сканирование по доменному имени
nmap google.com
Также Nmap может сканировать доменные имена, что особенно полезно для аудита внешних сайтов.
Продвинутые функции Nmap
Nmap предоставляет множество продвинутых функций, которые могут быть полезны для глубокого анализа сетей. Рассмотрим некоторые из них:
Сканирование операционной системы
Nmap может определять операционную систему удаленного хоста с использованием флага -O.
nmap -O 192.168.1.1
Сканирование конкретных портов
Чтобы отсканировать определенные порты, используйте параметр -p с указанием портов:
nmap -p 22,80,443 192.168.1.1
Анализ версий служб
Для того чтобы узнать, какие версии служб работают на обнаруженных портах, можно использовать ключ -sV:
nmap -sV 192.168.1.1
Сканирование без создания записей (Stealth Scan)
Nmap также может проводить скрытое сканирование, чтобы минимизировать риски обнаружения с помощью флага -sS (TCP SYN scan):
nmap -sS 192.168.1.1
Выводы
В этой статье мы разобрали, что такое Nmap и как его можно использовать для сетевого сканирования. Мы узнали, как установить Nmap на разные операционные системы, как выполнять основные и продвинутые сканирования. Nmap — это мощный инструмент для сетевых администраторов и специалистов по безопасности, и его возможности практически безграничны при правильном использовании. Ваша безопасность в сети во многом зависит от того, насколько глубоко вы понимаете, что происходит в вашей инфраструктуре, и Nmap предоставляет вам это знание.
Не забывайте, что для более глубокого изучения Nmap существует множество официальных ресурсов и мануалов, которые помогут вам стать экспертом в этой области.
Попробуйте ScaniteX бесплатно!
Автоматизированная платформа для сканирования открытых портов и обнаружения активных сервисов в режиме онлайн.
Начните 24ч пробный период (промокод FREE10), чтобы протестировать все функции сканирования для безопасности вашего бизнеса.
Получить бесплатный триал
Просмотров: 439
For a cybersecurity enthusiast or professional, mastering network scanning tools is very important to comprehend and assess the security position of networks and systems. Nmap, an influential and versatile Network Mapper, is the network reconnaissance and vulnerability detection go-to tool. As you begin your journey in ethical hacking or work towards developing your penetration testing skills, it is imperative to learn the key Nmap commands. The following 30 Nmap basic commands will provide a good starting point for scanning networks efficiently, finding live hosts, discovering opened ports, as well as obtaining useful details on services hosted on those machines. With Nmap in your toolbox, you will be armed with the necessary tools not just to understand the intricacies of network exploration but also to uncover any possible vulnerabilities that could breach security within the digital landscape.
What is NMAP ?
Nmap (Network Mapper) is a powerful tool that helps you discover and gather information about devices and services running on a network. In simple terms, Nmap is like a special tool that lets you see which computers or devices are connected to a network and what programs or applications are running on them. It’s like having a special pair of glasses that can see which houses have people living in them and what kinds of activities are happening inside each house.
Nmap allows you to:
- 1. Find live devices on a network.
- 2. Check which ports or doors are open on those devices.
- 3. Identify the services or applications running on those open ports.
It’s an essential tool for network administrators, cybersecurity professionals, and ethical hackers to understand and test the security of networks and systems they have permission to access.
Top 30 Basic NMAP Commands for Beginners
- 1. Perform a basic TCP scan on the specified target
- 2. Perform a ping scan to determine which hosts are online
- 3. Probe open ports to determine service/version info
- 4. Perform a ping scan
- 5. Perform a Don’t ping scan
- 6. Scan only the specified port or port range
- 7. Perform a stealthy SYN scan to find open TCP ports
- 8. Try to detect the target operating system
- 9. Enable OS detection, version detection, script scanning, and traceroute
- 10. Use default Nmap scripts for deeper probing
- 11. Run a specific Nmap script
- 12. Save output to a text file
- 13. Save output in XML format
- 14. Scan targets from a list and save output
- 15. Scan ports 1 through 100
- 16. Fast scan mode (only scans 100 most common ports)
- 17. Scan ports consecutively instead of randomly
- 18. Ping scan using ICMP echo requests
- 19. Ping scan using TCP timestamp requests
- 20. Ping scan using TCP netmask requests
- 21. TCP Window scan to bypass some packet filters
- 22. Xmas scan to map out firewall rulesets
- 23. TCP NULL scan to map out firewall rulesets
- 24. TCP FIN scan to map out firewall rulesets
- 25. Idle/bounced scan to disguise source
- 26. Scan using tiny fragmented IP packets
- 27. Use decoy IP addresses to obscure the source
- 28. Display the reason why a port is in a particular state
- 29. Display detailed information about packet transmissions
- 30. Set the intensity level for version detection
1. Perform a basic TCP scan on the specified target
The following command is used to perform a basic TCP scan on the specified target using the Nmap tool. When you run this command, Nmap will scan the most common 1,000 TCP ports on the specified target(s) to see which ones are open and accepting connections.
Command :
nmap <target>
Output :
2. Perform a ping scan to determine which hosts are online
The following command is used to perform a ping scan on a target system or network. This type of scan is often referred to as a «host discovery» or «ping sweep» scan. When you run this command Nmap will sends ICMP echo request packets (commonly known as «pings«) to the specified target IP address(es) or network range, and identifies which hosts are alive (responding to the ping requests) and which hosts are not responding.
Command :
nmap -sn <target>
Output :
3. Probe open ports to determine service/version info
The following command is used to perform a version detection scan on the specified target system(s). When you run this command, nmap will first scan the target system(s) for open ports. For any open ports found, it will then try to determine the version of the service or application running on that port.
Command :
nmap -sV <target>
Output :
4. Perform a ping scan
The following command is used to perform a ping scan or host discovery scan on the specified target system(s) or network range. When you run this command will list the IP addresses of the hosts that responded to the various packets sent by nmap, indicating that they are active and reachable on the network.
Command :
nmap -sP <target>
Output :
5. Perform a Don’t ping scan
The following command is used to perform a TCP connect scan on the specified target system(s) or network range, without sending any ICMP echo requests (pings) beforehand. When you run this command, nmap will attempt to establish a full TCP connection with the target system(s) on various ports, without first checking if the host is alive using pings. If a connection is successfully established, it means that the port is open on the target system.
Command :
nmap -PN <target>
Output :
6. Scan only the specified port or port range
The following command is used to perform a TCP port scan on the specified target system(s) or network range, but only for the specified port(s). When you run this command, nmap will scan the specified port(s) on the target system(s) to determine if they are open (listening for incoming connections) or closed (not listening).
Command :
nmap -p<port> <target>
7. Perform a stealthy SYN scan to find open TCP ports
The following command is used to perform a SYN scan, also known as a «stealth» or «half-open» scan, on the specified target system(s). When you run this command, nmap will send a SYN packet (the first step in establishing a TCP connection) to the target system(s) on various ports. If the target system responds with a SYN-ACK packet (indicating the port is open), nmap will immediately send a RST (reset) packet to tear down the connection, without completing the full handshake.
Command :
nmap -sS <target>
8. Try to detect the target operating system
The following command is used to perform remote operating system detection on the specified target system(s). When you run this command, nmap will scan the target system(s) and analyze various characteristics, such as the TCP/IP stack behavior, open ports and services, and other network traffic patterns. It then compares these observations against its database of known operating system fingerprints to determine the most likely operating system running on the target.
Command :
nmap -O <target>
9. Enable OS detection, version detection, script scanning, and traceroute
The following command is used to perform an aggressive scan on the specified target system(s). When you run this command The output of this command will provide a comprehensive report including the detected operating system, open ports, service versions, script scan results, and any other relevant information gathered during the scan.
Command :
nmap -A <target
10. Use default Nmap scripts for deeper probing
The following command is used to perform a script scan on the specified target system(s) using the default set of Nmap scripts. When you run this command, nmap will first scan the target system(s) for open ports and services. Then, for each open port or service, it will run the relevant scripts from the default script databases.
Command :
nmap -sC <target>
11. Run a specific Nmap script
The following command is used to run a specific Nmap script or a set of scripts against the specified target system(s). When you run this command, Nmap will first scan the target system(s) for open ports and services. Then, for each open port or service, it will run the specified script(s) against the target.
Command :
nmap --script=<script> <target>
12. Save output to a text file
The following command is used to save the output of an Nmap scan to a plain text file. When you run this command, Nmap will perform the specified scan (e.g., TCP connect scan, SYN scan, version detection, etc.) on the target system(s) or network range. Instead of displaying the scan output in the terminal, it will save the entire output in the specified text file.
Command :
nmap -oN <output.txt> <target>
13. Save output in XML format
The following command is used to save the output of an Nmap scan in an XML (Extensible Markup Language) format. When you run this command, Nmap will perform the specified scan (e.g., TCP connect scan, SYN scan, version detection, etc.) on the target system(s) or network range. Instead of displaying the scan output in plain text format, it will save the entire output in an XML file with the specified filename.
Command :
nmap -oX <output.xml> <target>
14. Scan targets from a list and save output
The following command is used to perform an Nmap scan on a list of targets specified in a text file, and save the output of the scan to another text file. When you run this command, Nmap will perform its default TCP connect scan on each target listed in the hosts.txt file. The scan results for all targets will be saved in the output.txt file, with each target’s scan output separated by a line break or other delimiter.
Command :
nmap -iL <hosts.txt> -oN <output.txt>
15. Scan ports 1 through 100
The following command is used to perform a TCP port scan on the specified target system(s), but only for ports in the range of 1 to 100. When you run this command, nmap will scan the specified port range (1-100) on the target system(s) to determine if any of those ports are open (listening for incoming connections) or closed (not listening).
Command :
nmap -p1-100 <target>
16. Fast scan mode (only scans 100 most common ports)
The following command is used to perform a fast scan on the specified target system(s) or network range. When you run this command, nmap will scan a predefined set of approximately 100 commonly used ports on the target system(s). These ports are associated with popular services like HTTP, HTTPS, FTP, SSH, SMTP, and others.
Command :
nmap -F <target>
17. Scan ports consecutively instead of randomly
The following command is used to perform a sequential port scan on the specified target system(s). When you run this command, nmap will scan the ports on the target system(s) in the order of port 1, port 2, port 3, and so on, until the highest port number is reached (typically 65535 for TCP ports).
Command :
nmap -r <target>
18. Ping scan using ICMP echo requests
The following command is used to perform a ping scan with host discovery using ICMP echo requests (pings) and TCP SYN packets on the specified target system(s) or network range. When you run this command, nmap will send both ICMP echo requests (pings) and TCP SYN packets to the specified target IP addresses. If a target system responds to either type of packet, it is considered alive and reachable on the network.
Command :
nmap -sn -PE <target>
19. Ping scan using TCP timestamp requests
The following command is used to perform a ping scan with host discovery using TCP SYN packets on the specified target system(s) or network range. When you run this command, nmap will send TCP SYN packets to the specified target IP addresses. If a target system responds to the TCP SYN packets, it is considered alive and reachable on the network.
Command :
nmap -sn -PP <target>
20. Ping scan using TCP netmask requests
The following command is used to perform a ping scan with host discovery using ICMP netmask request packets on the specified target system(s) or network range. When you run this command, nmap will send ICMP netmask request packets to the specified target IP addresses. If a target system responds to these packets, it is considered alive and reachable on the network.
nmap -sn -PM <target>
21. TCP Window scan to bypass some packet filters
The following command is used to perform a Windows scan on the specified target system(s). When you run this command, nmap will send specially crafted packets and analyze the responses from the target system(s) to determine which ports are open. The Windows scan leverages the fact that the Windows TCP/IP stack and network services have certain unique behaviors and responses when handling certain types of packets or connection requests.
Command :
nmap -sW <target>
22. Xmas scan to map out firewall rulesets
The following command is used to perform an idle/zombie scan on the specified target system(s). When you run this command, Nmap first identifies an idle system on the network that meets certain criteria. Then, it spoofs packets from the idle system to scan the target system(s). The responses from the target system(s) are sent back to the idle system, allowing Nmap to infer which ports are open or closed based on the changes in the idle system’s behavior.
Command :
nmap -sX <target>
23. TCP NULL scan to map out firewall rulesets
The following command is used to perform a TCP NULL scan on the specified target system(s). When you run this command, Nmap will send TCP packets with no flags set (NULL packets) to various ports on the target system(s). The responses from the target system(s) are then analyzed to determine which ports are open, closed, or filtered.
Command :
nmap -sN <target>
24. TCP FIN scan to map out firewall rulesets
The following command is used to perform a TCP FIN scan on the specified target system(s). When you run this command, Nmap will send TCP packets with the FIN flag set to various ports on the target system(s). The responses from the target system(s) are then analyzed to determine which ports are open, closed, or filtered.
Command :
nmap -sF <target>
25. Idle/bounced scan to disguise source
The following command is used to perform an idle/zombie scan on the specified target system(s) using the provided zombie host. When you run this command, Nmap first verifies that the specified <zombie host> meets the criteria for an idle system (i.e., it has no active connections and has not sent any packets recently). Then, it spoofs packets from the idle system to scan the target system(s). The responses from the target system(s) are sent back to the idle system, allowing Nmap to infer which ports are open or closed based on the changes in the idle system’s behavior.
Command :
nmap -sI <zombie host> <target>
26. Scan using tiny fragmented IP packets
The following command is used to instruct Nmap to fragment the packets during a TCP connect scan on the specified target system(s). When you run this command, Nmap will fragment the TCP packets it sends during the scan into smaller pieces. This can help bypass certain firewalls or intrusion detection/prevention systems (IDS/IPS) that may be configured to block or filter out larger packets.
Command :
nmap -f <target>
27. Use decoy IP addresses to obscure the source
The following command is used to perform a decoy scan on the specified target system(s) using the provided decoy IP addresses. When you run this command, Nmap will send spoofed packets from the specified decoy IP addresses along with the real scan packets. This can make it more difficult for the target system(s) or network devices (such as firewalls or intrusion detection systems) to determine the true source of the scan, as they will see traffic coming from multiple IP addresses.
Command :
nmap -D <decoy1,decoy2,...> <target>
28. Display the reason why a port is in a particular state
The following command is used to display the reason codes for the port states reported by Nmap during a scan on the specified target system(s). When you run this command, Nmap will perform its default TCP connect scan on the target system(s). However, in addition to the standard output displaying open, closed, and filtered ports, it will also include a reason code for each port state.
Command :
nmap --reason <target>
29. Display detailed information about packet transmissions
The following command is used to display a detailed trace of the packets sent and received by Nmap during a scan on the specified target system(s). When you run this command, Nmap will perform its default TCP connect scan on the target system(s). However, instead of just displaying the standard output of open, closed, and filtered ports, it will also print a detailed trace of the packets sent and received during the scan.
Command :
nmap --packet-trace <target>
30. Set the intensity level for version detection
The following command is used to set the intensity level for version detection when scanning the specified target using Nmap. When you run this command, Nmap will scan the target(s) and attempt to determine the versions of services or applications running on any open ports it finds. The <intensity> level you set will determine how much effort Nmap puts into trying to accurately identify the service versions.
Command :
nmap --version-intensity <intensity> <target>
Conclusion
As a beginner in cybersecurity or ethical hacking, mastering Nmap is crucial for understanding and assessing networks and systems. Nmap allows you to discover live devices, open ports, and services running on a network, providing valuable information for identifying potential security vulnerabilities. With practice and understanding of these fundamental commands, you’ll be well-equipped to perform effective network reconnaissance and uncover potential vulnerabilities, ultimately enhancing your cybersecurity skills as a beginner.
Время на прочтение5 мин
Количество просмотров431K
Вы когда-нибудь интересовались откуда атакующий знает какие порты открыты в системе? Или как узнать, какие приложения запущены на сервере, не спрашивая об этом администратора? Вы можете сделать все это и даже больше вместе с небольшим инструментом под названием Nmap.
Что такое Nmap? Название Nmap это сокращение от “network mapper”, сам nmap это набор инструментов для сканирования сети. Он может быть использован для проверки безопасности, просто для определения сервисов запущенных на узле, для идентификации ОС и приложений, определения типа фаерволла используемого на сканируемом узле.
Nmap это знаменитый инструмент. Как только вы узнаете больше о Nmap, вы поймете, что он делает в эпизодах таких фильмов как Матрица Перезагрузка, Ультиматум Борна, Хоттабыч, и других.
В этом руководстве будут описаны основы использования Nmap и приведены некоторые примеры, которые вы сможете использовать.
Где взять Nmap?
Если Вы используете Linux, то можете найти пакеты Nmap в репозиториях для большинства дистрибутивов. Последний релиз Nmap вышел в начале 2010, поэтому самой свежей версии может не быть в текущих стабильных ветках. Найти исходники и некоторые бинарные сборки можно на странице загрузки.Там есть и windows версия.
Основы использования Nmap.
Синтаксис Nmap следующий:
nmap Опции_сканирования Цель_сканирования.
Допустим Вы хотите сканировать узел и узнать какая операционная система на нем работает. Чтобы сделать это выполните следующее:
nmap -O target.host.com
Заметим что Nmap требует привилегий суперпользователя для запуска подобного типа сканирования. Процесс сканирования может занять около минуты, так что будьте терпеливы. Когда процесс закончится вы увидите что то похожее на это:
Starting Nmap 5.21 ( nmap.org ) at 2010-02-27 23:52 EST
Nmap scan report for 10.0.0.1
Host is up (0.0015s latency).
Not shown: 997 closed ports
PORT STATE SERVICE
53/tcp open domain
5009/tcp open airport-admin
10000/tcp open snet-sensor-mgmt
MAC Address: 00:11:24:6B:43:E2 (Apple Computer)
Device type: WAP|printer
Running: Apple embedded, Canon embedded, Kyocera embedded, Xerox embedded
OS details: VxWorks: Apple AirPort Extreme v5.7 or AirPort Express v6.3; Canon imageRUNNER printer (5055, C3045, C3380, or C5185); Kyocera FS-4020DN printer; or Xerox Phaser 8860MFP printer
Network Distance: 1 hop
Как вы видите Nmap предоставляет множество информации. Здесь он отображает предположение об операционной системе, которая была запущена на узле. В данном случае выполнялось сканирование маршрутизатора Apple Airport Extrime. В качестве дополнительного бонуса Nmap сообщил, что устройство на расстоянии одного прыжка, а также MAC адрес устройства и производителя сетевой карты, открытые порты и сколько времени выполнялось сканирование.
Ниже приведены результаты другого сканирования, домашнего компьютера с запущенной Ubuntu 9.10:
Starting Nmap 5.21 ( nmap.org ) at 2010-02-28 00:00 EST
Nmap scan report for 10.0.0.6
Host is up (0.0039s latency).
Not shown: 999 closed ports
PORT STATE SERVICE
22/tcp open ssh
MAC Address: 00:17:08:2A:D6:F0 (Hewlett Packard)
Device type: general purpose
Running: Linux 2.6.X
OS details: Linux 2.6.19 - 2.6.31
Network Distance: 1 hop
OS detection performed. Please report any incorrect results at nmap.org/submit .
Nmap done: 1 IP address (1 host up) scanned in 3.40 seconds
Здесь мы видим, что система имеет сетевую карту HP, запущено Linux между версиями 2.6.19 и 2.6.31. Кстати, Вы не сможете явно идентифицировать дистрибутив, только версию Linux ядра.
Сканирование чужих узлов.
В примерах выше для сканирования были выбраны локальный маршрутизатор и одна из рабочих станций, потому что мы имели право на их сканирование. Однако, будет плохой идеей запуск множественного сканирования чужого узла, если вы их не контролируете или не имеете прав для сканирования. Для экспериментов Nmap имеет общедоступный тестовый сервер scanme.nmap.org который Вы можете использовать.
Многие администраторы не любят несанкционированного сканирования их серверов, так что лучшим вариантом будет ограничение сканирования узлов своей локальной сети или тех для которых у вас есть права на сканирование. Также в некоторых случаях вы можете нарушить договор с вашим провайдером, при использовании некоторых особо агрессивных методов сканирования Nmap, поэтому будьте осторожны.
Сканирование нескольких узлов.
Вы можете сканировать больше чем один узел за раз, используя nmap. Если вы производите сканирование по IP-адресу вы можете определить диапазон 10.0.0.1-6 или 10.0.0.0/24.Используя диапазон 10.0.0.1-6 будут сканироваться узлы от 10.0.0.1 до 10.0.0.6. Используя определение /24 будет сканироваться весь диапазон узлов от 10.0.0.0 до 10.0.0.255. Для примера, если нужно просканировать узлы от 10.0.0.1 до 10.0.0.42 и узнать какая ОС вероятно запущена используйте:
nmap –O 10.0.0.1-42
Если у вас есть некоторый список доменных имен вместо IP адресов, вы можете разделить их в командной строке, вот так:
nmap -O host1.target.com host2.target.com
Проверка открытых портов
Если вы запустите nmap вообще без опций и укажите какой то узел, то он будет сканировать порты и покажет все найденные открытые порты и сервисы запущенные на них. Например запустите:
nmap target.hostname.com
после чего он должен выдать что то похожее на это:
Interesting ports on target.hostname.com (10.0.0.88):
Not shown: 1711 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
3306/tcp open mysql
Nmap done: 1 IP address (1 host up) scanned in 0.228 seconds
Nmap выдаст больше информации если использовать опцию -v (verbose).
Сканирование запущенных сервисов
Если вы хотите узнать какой сервис возможно запущен попробуйте опцию –sV. Эта опция произведет более агрессивное сканирование и попытается выяснить какая версия сервисов запущена на данном узле, а также может помочь более точно определить какая ОС запущена. Для пример запустим nmap –sV на тестовый сервер и получим следующий ответ:
Starting Nmap 5.21 ( nmap.org ) at 2010-02-28 00:15 EST
Nmap scan report for test.host.net (XX.XXX.XXX.XX)
Host is up (0.090s latency).
Not shown: 965 closed ports, 33 filtered ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1.2 (protocol 2.0)
80/tcp open http Apache httpd 2.2.8 ((Ubuntu) PHP/5.2.4-2ubuntu5.10 with Suhosin-Patch)
Service Info: OS: Linux
Service detection performed. Please report any incorrect results at nmap.org/submit .
Nmap done: 1 IP address (1 host up) scanned in 11.43 seconds
Как вы видите, Nmap может проанализировать пакеты и определить версию запущенного приложений на SSH и HTTP портах. Здесь вы можете увидеть что опрашиваемая система это Ubuntu с Apache 2.2.8 и OpenSSH 4.7p1. Эта информация может быть полезна по ряду причин. Nmap сканирование может идентифицировать систему под управлением устаревших сервисов которые могут быть уязвимы для известных эксплойтов.
Кто в моей сети?
Не знаете сколько онлайн узлов находятся в вашей сети? Попробуйте использовать nmap –sP который запустит ping сканирование указанной сети. Для примера, nmap –sP 10.0.0.0/24 сканирует 256 узлов от 10.0.0.0 до 10.0.0.255 проверит доступны ли они и доложит об этом. Так же вы можете использовать диапазон, например:
nmap –sP 10.0.0.1-15
Zenmap
Наконец, если все эти радости командной строки не для вас, nmap имеет GUI который вы можете использовать для построения и выполнения команд. Называется Zenmap. Он позволит выбрать цель, запустить сканирование, отобразить результаты, а также сохранить их и сравнить с другими.
GUI Zenmap это хороший способ познакомиться с Nmap, но лучше знать как использовать Nmap в командной строке, если вы собираетесь работать с ним часто.
В будущем руководстве мы более глубоко познакомимся с Nmap и конкретными задачами которые вы сможете решить.
Данный пост это вольный перевод статьи Beginner’s Guide to Nmap. Спасибо за внимание.
