Bird
Raised Fist0
Bash Scriptingscripting~15 mins

Port scanning basics in Bash Scripting - Deep Dive

Choose your learning style10 modes available
Overview - Port scanning basics
What is it?
Port scanning is a way to check which doors (ports) on a computer or server are open and ready to communicate. Each port is like a door to a specific service or application. By scanning ports, you learn what services a machine offers and if it might be vulnerable. This helps in security testing and network management.
Why it matters
Without port scanning, you would not know which services are running on a computer or if any doors are accidentally left open. This could lead to security risks or network problems. Port scanning helps find weak spots before attackers do, making networks safer and more reliable.
Where it fits
Before learning port scanning, you should understand basic networking concepts like IP addresses and ports. After mastering port scanning, you can learn about network security, firewall rules, and vulnerability assessment tools.
Mental Model
Core Idea
Port scanning is like knocking on every door of a house to see which ones are open and who answers.
Think of it like...
Imagine a big apartment building where each apartment door is a port. Port scanning is like walking down the hallway and knocking on each door to find out which apartments are occupied and what activities are happening inside.
┌───────────────┐
│ Target Host   │
│               │
│  Ports:       │
│  [22] Open   ←┐
│  [80] Open   ←┤  Port Scanner knocks
│  [443] Closed │
│  [8080] Open ←┘
└───────────────┘

Port Scanner → Knocks on each port to check if open or closed
Build-Up - 6 Steps
1
FoundationUnderstanding IP and Ports
🤔
Concept: Learn what IP addresses and ports are and how they identify computers and services.
Every device on a network has an IP address, like a street address. Each device can have many ports, like doors to different rooms. Ports are numbered from 0 to 65535. Common ports include 22 for SSH, 80 for web, and 443 for secure web.
Result
You know that IP is the device location and ports are entry points to services on that device.
Understanding IP and ports is essential because port scanning targets these entry points to find active services.
2
FoundationWhat is Port Scanning?
🤔
Concept: Port scanning is the process of checking which ports on a device are open or closed.
When you scan a port, you send a small message to see if the port responds. If it responds, the port is open and a service is listening. If not, the port is closed or filtered by a firewall.
Result
You can tell which ports are open and which are closed on a target device.
Knowing which ports are open helps identify what services the device offers and if it might be vulnerable.
3
IntermediateBasic Bash Port Scan Script
🤔Before reading on: do you think a simple bash script can scan all ports quickly or will it be slow? Commit to your answer.
Concept: Use bash scripting with tools like 'nc' (netcat) to scan ports by trying to connect to them.
A simple bash script loops through a range of ports and uses 'nc -zv' to check if the port is open. For example: for port in {20..25}; do nc -zv 192.168.1.1 $port done This tries to connect to each port and reports if it is open.
Result
The script outputs which ports are open or closed on the target IP.
Using bash and netcat is a straightforward way to scan ports without installing complex tools.
4
IntermediateInterpreting Scan Results
🤔Before reading on: do you think a port that doesn't respond is always closed? Commit to your answer.
Concept: Learn how to read the output of port scans and understand open, closed, and filtered ports.
Open ports respond positively to connection attempts. Closed ports reject connections. Filtered ports do not respond because a firewall blocks them. For example, 'Connection refused' means closed, 'timed out' means filtered.
Result
You can distinguish between open, closed, and filtered ports from scan output.
Knowing the difference helps you understand network security and firewall behavior.
5
AdvancedScanning with Timeout and Parallelism
🤔Before reading on: do you think scanning ports one by one is efficient or slow? Commit to your answer.
Concept: Improve bash port scanning by adding timeouts and running scans in parallel to speed up results.
By adding a timeout option to 'nc' and running multiple scans in the background, you can scan many ports faster. Example: for port in {1..100}; do nc -z -w 1 192.168.1.1 $port & done wait This runs scans in parallel with a 1-second timeout.
Result
The scan completes faster and avoids hanging on unresponsive ports.
Optimizing scan speed is important for practical use on large networks.
6
ExpertLimitations and Detection Risks
🤔Before reading on: do you think port scanning is always invisible to the target? Commit to your answer.
Concept: Understand that port scanning can be detected and blocked, and learn about stealth scanning techniques.
Port scans generate network traffic that can be logged or blocked by firewalls and intrusion detection systems. Some scans use slow timing or special packet types to avoid detection. Bash scripts are simple and easy to detect, so advanced tools like Nmap use stealth methods.
Result
You realize port scanning can alert defenders and that stealth requires specialized tools.
Knowing detection risks helps you choose the right tools and methods for ethical scanning.
Under the Hood
Port scanning works by sending network packets to specific ports on a target IP address and waiting for responses. The type of response or lack thereof reveals the port's state: open, closed, or filtered. Tools like 'nc' open TCP connections to test ports. The operating system's network stack handles these packets and replies accordingly.
Why designed this way?
Port scanning was designed to map network services and security holes efficiently. Early network tools needed a simple way to check service availability. The approach balances speed and information detail. Alternatives like banner grabbing or vulnerability scanning build on port scanning but are more complex.
┌───────────────┐       ┌───────────────┐
│ Port Scanner  │──────▶│ Target Host   │
│ Sends packet  │       │ Receives packet│
│ to port N     │       │ on port N     │
└───────────────┘       └───────────────┘
         ▲                      │
         │                      ▼
         │             ┌───────────────────┐
         │             │ Responds if open  │
         │             │ Rejects if closed │
         │             │ No response if    │
         │             │ filtered          │
         └─────────────┴───────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does a non-responding port always mean it is closed? Commit to yes or no.
Common Belief:If a port does not respond, it is always closed.
Tap to reveal reality
Reality:A non-responding port may be filtered by a firewall, not necessarily closed.
Why it matters:Assuming non-response means closed can cause you to miss hidden services or security controls.
Quick: Can port scanning be completely hidden from the target? Commit to yes or no.
Common Belief:Port scanning is invisible and cannot be detected by the target.
Tap to reveal reality
Reality:Port scanning generates network traffic that can be logged and detected by security systems.
Why it matters:Believing scans are invisible can lead to unintentional detection and blocking.
Quick: Does scanning all 65535 ports always give useful information? Commit to yes or no.
Common Belief:Scanning every port is always necessary and useful.
Tap to reveal reality
Reality:Most services use common ports; scanning all ports wastes time and may trigger alarms.
Why it matters:Blindly scanning all ports can slow down scans and increase detection risk.
Quick: Does a port scan tell you exactly what software is running? Commit to yes or no.
Common Belief:Port scanning reveals the exact software and version running on a port.
Tap to reveal reality
Reality:Port scanning only shows if a port is open; identifying software requires additional techniques.
Why it matters:Misunderstanding this can lead to overconfidence in scan results and missed vulnerabilities.
Expert Zone
1
Some ports may appear open but are actually protected by honeypots designed to trap attackers.
2
Timing and packet types in scans affect detection; slow scans reduce noise but take longer.
3
Network devices like load balancers can alter scan results by distributing connections.
When NOT to use
Avoid port scanning on networks without permission as it can be illegal or unethical. Use passive network monitoring or authorized vulnerability scanners instead.
Production Patterns
In real systems, port scanning is automated in security audits, combined with vulnerability scanners and firewall rule checks. Scripts are integrated into CI/CD pipelines to detect exposed services early.
Connections
Firewall Rules
Port scanning tests which firewall rules allow or block traffic to ports.
Understanding port scanning helps you design firewall rules that effectively protect services.
Network Intrusion Detection Systems (NIDS)
NIDS monitor for port scanning activity as a sign of potential attacks.
Knowing how port scanning works helps in tuning detection systems to reduce false alarms.
Medical Diagnostics
Port scanning is like running tests on different organs to find issues without opening the body.
This connection shows how probing external signs can reveal internal states, a principle across fields.
Common Pitfalls
#1Scanning ports too quickly without timeouts causes the script to hang or miss results.
Wrong approach:for port in {1..100}; do nc -zv 192.168.1.1 $port done
Correct approach:for port in {1..100}; do nc -zv -w 1 192.168.1.1 $port done
Root cause:Not setting a timeout causes the scanner to wait indefinitely on unresponsive ports.
#2Running scans sequentially on many ports takes too long and is inefficient.
Wrong approach:for port in {1..1000}; do nc -zv -w 1 192.168.1.1 $port done
Correct approach:for port in {1..1000}; do nc -zv -w 1 192.168.1.1 $port & done wait
Root cause:Not using parallelism wastes time by scanning ports one after another.
#3Assuming no response means the port is closed leads to wrong conclusions.
Wrong approach:Ignoring ports that do not respond and marking them closed without considering filtering.
Correct approach:Treat non-responding ports as filtered and investigate firewall rules or network blocks.
Root cause:Misunderstanding network behavior and firewall effects on scan results.
Key Takeaways
Port scanning is a method to discover open doors (ports) on a computer to understand what services it offers.
Using simple bash scripts with tools like netcat allows you to scan ports and interpret their states.
Open, closed, and filtered ports behave differently and understanding these helps in network security.
Port scanning can be detected and should be done ethically with permission to avoid legal issues.
Optimizing scan speed and interpreting results correctly are key skills for effective port scanning.

Practice

(1/5)
1. What is the main purpose of port scanning in network security?
easy
A. To install software remotely
B. To delete files on a remote server
C. To speed up internet connection
D. To find open ports on a computer

Solution

  1. Step 1: Understand port scanning basics

    Port scanning is used to check which network ports on a computer are open and accepting connections.
  2. Step 2: Identify the correct purpose

    Among the options, only finding open ports matches the purpose of port scanning.
  3. Final Answer:

    To find open ports on a computer -> Option D
  4. Quick Check:

    Port scanning = find open ports [OK]
Hint: Port scanning checks open ports, not files or speed [OK]
Common Mistakes:
  • Confusing port scanning with file operations
  • Thinking it improves internet speed
  • Assuming it installs software
2. Which of the following bash commands correctly scans if port 80 is open on host 192.168.1.1?
easy
A. nc -zv 192.168.1.1 80
B. nc -xv 192.168.1.1 80
C. nc -z 192.168.1.1 -p 80
D. nc -v 192.168.1.1

Solution

  1. Step 1: Recall correct netcat syntax for port scanning

    The option '-z' tells nc to scan without sending data, and '-v' enables verbose output. The host and port follow these flags.
  2. Step 2: Check each option

    Only nc -zv 192.168.1.1 80 uses the correct flags '-z' for scanning and '-v' for verbose, followed by host and port. Other options either lack necessary flags, use incorrect flags like -xv or misuse -p for source port, or omit the port specification.
  3. Final Answer:

    nc -zv 192.168.1.1 80 -> Option A
  4. Quick Check:

    Correct nc flags = -zv [OK]
Hint: Use nc -zv host port to scan a port [OK]
Common Mistakes:
  • Using wrong flags like -xv
  • Misplacing port with -p flag
  • Omitting port number
3. What will be the output of this bash snippet scanning ports 22 and 80 on localhost?
for port in 22 80; do
  nc -zv localhost $port
 done
medium
A. It will produce a syntax error
B. It will show if ports 22 and 80 are open or closed on localhost
C. It will scan ports 22 and 80 on a remote host
D. It will scan all ports from 22 to 80

Solution

  1. Step 1: Analyze the for loop and command

    The loop iterates over ports 22 and 80, running 'nc -zv localhost $port' for each port.
  2. Step 2: Understand the command effect

    Netcat checks if each specified port on localhost is open, printing the result.
  3. Final Answer:

    It will show if ports 22 and 80 are open or closed on localhost -> Option B
  4. Quick Check:

    Loop scans specified ports on localhost [OK]
Hint: Loop scans listed ports on localhost, not a range [OK]
Common Mistakes:
  • Thinking it scans a range of ports
  • Assuming remote host scanning
  • Expecting syntax errors
4. Identify the error in this bash script intended to scan ports 20 to 25 on 127.0.0.1:
for port in {20..25} do
  nc -zv 127.0.0.1 $port
 done
medium
A. The loop syntax is incorrect; it should use parentheses
B. The loop variable $port is not referenced correctly
C. The script is missing a semicolon after the for statement
D. The loop block is missing a 'do' keyword

Solution

  1. Step 1: Check for correct bash for-loop syntax

    Bash requires a semicolon or newline after the for statement before 'do'. Here, 'for port in {20..25}' is not followed by a semicolon or newline before 'do'.
  2. Step 2: Verify other syntax elements

    The loop variable and block are correct, and 'do' is present. The missing semicolon causes a syntax error.
  3. Final Answer:

    The script is missing a semicolon after the for statement -> Option C
  4. Quick Check:

    Missing semicolon after for statement causes error [OK]
Hint: Add semicolon or newline after for statement before do [OK]
Common Mistakes:
  • Omitting semicolon after for line
  • Misplacing 'do' keyword
  • Incorrect variable usage
5. You want to scan all ports from 80 to 85 on host 10.0.0.5 and save only open ports to a file named open_ports.txt. Which bash script snippet achieves this?
hard
A. for port in {80..85}; do nc -zv 10.0.0.5 $port 2>&1 | grep 'succeeded' >> open_ports.txt; done
B. for port in 80 81 82 83 84 85; do nc -zv 10.0.0.5 $port > open_ports.txt; done
C. nc -zv 10.0.0.5 80-85 > open_ports.txt
D. for port in {80..85}; do nc -zv 10.0.0.5 $port | grep 'failed' >> open_ports.txt; done

Solution

  1. Step 1: Understand the scanning and filtering requirements

    The script must scan ports 80 to 85, detect open ports, and save only those results to a file.
  2. Step 2: Analyze each option

    for port in {80..85}; do nc -zv 10.0.0.5 $port 2>&1 | grep 'succeeded' >> open_ports.txt; done loops over ports 80 to 85, runs nc with verbose and zero-I/O flags, redirects stderr to stdout, filters lines containing 'succeeded' (indicating open ports), and appends to open_ports.txt. for port in 80 81 82 83 84 85; do nc -zv 10.0.0.5 $port > open_ports.txt; done overwrites the file each time and does not filter open ports. nc -zv 10.0.0.5 80-85 > open_ports.txt uses invalid port range syntax. for port in {80..85}; do nc -zv 10.0.0.5 $port | grep 'failed' >> open_ports.txt; done filters 'failed' ports, opposite of requirement.
  3. Final Answer:

    for port in {80..85}; do nc -zv 10.0.0.5 $port 2>&1 | grep 'succeeded' >> open_ports.txt; done -> Option A
  4. Quick Check:

    Loop + grep 'succeeded' + append to file = correct [OK]
Hint: Filter 'succeeded' lines and append output to file [OK]
Common Mistakes:
  • Overwriting output file inside loop
  • Using invalid port range syntax
  • Filtering 'failed' instead of 'succeeded'
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard