Cylabs
  • 😊Welcome to CyLabs
  • 101 Series
    • Cyber Security 101
      • Introduction to Cyber Security and core concepts
      • Getting Started into Cyber Security Career
      • Online Cybersecurity Practice Labs to Sharpen Your Skills
      • Cyber Security Interview Q&A
        • Careers in Cybersecurity
      • Stay Tuned : Cyber Resources
        • Blogs for Cyber Security
          • Blogs
            • Penetration Testing Automation
            • Security
              • Metasploit Framework
              • Jenkins Servers: Identifying Vulnerabilities and Exploiting Unauthenticated Access with Groovy Scrip
              • Securing Your Network: Printer Vulnerabilities, LDAP Exploits, and Defense Strategies
              • SSH for Red Teaming and Security Analysis
              • Operating Systems for Penetration Testing: Enhancing Your Cybersecurity Arsenal
              • Hacking Notes
                • Phineas Fisher
        • Cyber News
        • Leading Cybersecurity Companies to follow
        • Cybersecurity Courses and Certifications: Trends in 2024
        • ISACs: Enhancing Cybersecurity through Collaboration and Information Sharing
        • Global and National Cybersecurity Agencies: Guardians of the Digital Realm
        • Cyber Security News Feed Resources
    • Kubernetes 101
    • Web 101
    • Operating Systems
      • Linux 101
        • Linux Kernel
        • Basic Commands and Usage
          • Shell Commands
        • Linux File System
        • apt
        • su and sudo
        • File Search
        • Linux Services
        • Networking
          • Netcat
        • Corn Jobs
        • Shell Scripting
        • Linux OS API's
      • Windows 101
        • Windows system calls
        • Windows Event Logs and IDs
        • Windows UAC
        • Windows Registry
        • Windows Bit Locker
        • Volume Shadow Copy Service
        • Windows OS API's
    • Building the Security Lab
      • Virtualization with Virtual Box
        • Installing and setting Virtual Box
        • Vritual Box Networking
      • Home Lab Setup
        • PF Sense Installation
        • Ubuntu Installation
        • Metasploit Installation
        • Kali Linux Installation
    • Fundamentals of Programming
      • Python 101
      • Powershell 101
      • SQL 101
    • AI/ML and Data Science for Cyber Security and Analytics
    • IT Infrastructure and Hardware
    • Governance, Risk and Compliance
    • Networking 101
      • Network Packets and Frames
      • Network Switches and Routers: The Backbone of Connectivity
      • Network Security Devices and Strategies
      • Network Design and Architecture: A Foundation for Robust Connectivity
      • Specialized Network Equipment and Functions
      • Network Traffic Management and Analysis
      • Advanced Networking Concepts
      • ARP and RARP
      • How DNS, HTTP and HTTPS works
      • Understanding the Basics of Networking
  • Introduction to Cyber Security Operations
    • Security Architecture and Engineering
      • Security Controls
        • Preventive
        • Deterrent
        • Detective
        • Corrective
        • Compensating
        • Directive
    • GRC
      • Information Security and Risk Management
        • Risk Management
        • Supply Chain Risk Management
        • Governance
        • Asset Management
        • Cyber Security Road Map
        • Cyber Security Controls
        • Cyber Security Strategy and Architecture
        • Cyber Security Architecture
        • Risk Assessment and Security Questionnaire
        • Ransomware Prevention
        • Gap Assessment
        • Principle of Least Privilege
      • Governance
      • Asset Security
      • Communication and Network Security
      • Identity and Access Management
      • Security Assessment and Testing
      • Security Operations
      • Software Development Security
      • Security Baselines
      • Security Reporting
      • Data Loss Prevention
      • Zero Trust
      • MFA
      • Compliance
    • Security Policies and Procedures
    • Offensive Security
      • Stages of Penetration Testing
    • Cyber Defense
      • Security Operations Center (SOC)
        • SOC Architecture Development with ELK Stack:
      • Different Classes of Threat Actor
    • Security Principles, Controls and Strategies
      • Defense in Depth
      • Least Privilege
      • Zero Trust
  • Cyber Security Assessment
    • Planning and Scoping
      • Security Engagement
      • Security Assessment Questionaire
      • Who Targeting you
    • Reconnaissance
      • Active Recon
        • Tools
          • NMAP
          • Maascan
          • Recon-NG
          • Maltego
          • Spider Foot
          • Whois
          • TraceRoute
          • Amass
          • The Harvester
          • Nslookup
          • DNS Dumpster
          • BloodHound
          • Relay Attacks
          • Packet Crafting
          • NMAP+Proxychains+TOR
      • Passive Reconnaissance
        • Network Sniffing
          • Wireshark
          • TCPDump
        • Whois (online services)
        • EMail Account Enumeration
          • Hunter.io
        • Search Engine Analysis
          • Google Hacking Database
          • Shodan
          • Censys.io
        • Information Disclousre
        • Banner Grabbing
        • HTML Scrapping
        • Certificate Transparency Logs
        • Open Source Intelligence (OSINT)
          • Ship OSINT
          • Social Media
          • Code Repositories
          • Darkweb Analysis
          • DNS
          • Cached Pages
          • Password Dumps
          • Anonymity
    • Enumeration
      • OS Finger Printing
      • Service Discovery
      • Protocol Enumeration
      • DNS Enumeration
      • FTP Service
      • HTTP/HTTPS
      • WMI
      • DCOM
      • RPC Remote Procedure Call
      • Directory Enumeration
      • Host Discovery
      • Share Enumeration
        • SMB
      • Local User Enumeration
      • Email Account Enumeration
      • SSH Service
      • Wireless Enumeration
        • Wigle.net
        • InSSIDer
        • Aircrack-ng
      • Permission Enumeration
      • Secrets Enumeration
        • Passwords
        • Session Tokens
        • Cloud Access Keys
      • Attack Path Mapping
      • VNC
      • Web Application Firewall
      • Wordpress Scan
      • Remote Desktop Protocol
      • SNMP
      • SMTP
      • Web Crawling
        • Platform Plugins
        • Sitemap
        • Robots.txt
      • Active Directory Enumeration
    • Vulnerability Assessment and Management
      • Terminology
      • Vulnerability Database
      • Vulnerability Scoring
        • CWE
        • CVSS
        • CVE
        • EPSS
      • Vulnerability Scan
        • Authenticated vs Unauthenticated Scans
        • OS Security Assessment
        • Tenable
        • Nikto
        • Open VAS
      • Exploit Databases
      • Tools
        • Tenable.IO
        • Open VAS
    • Exploitation
      • Attack Surface and Target Prioritization
        • High Valued Assets and Identification
        • Vulnerability Metrics
        • End of Life Softwares
        • Default Configuration
        • Running Services
        • Vulnerable Encryption Methods
        • Defensive Capabilities
        • Attack Path
      • Attack Types
        • Network Attacks
          • Virtual LAN Hopping
          • Packet Crafting
            • Attacks Scenario
          • Default Credentials
          • On-Path / Man in the Middle Attacks
          • Certificate Services Attacks
      • Host Based Attacks
        • Privilege Escalation
        • Credential Dumping
        • Shell Escape
        • UAC Bypass
        • Payload Obfuscation
        • Endpoint Security Bypass
        • Process Hallowing
        • Log Tampering
        • DLL Injection
        • Service Path Injection
      • Authentication Attacks
        • LDAP Injection
        • SAML Attacks
        • Open ID Connect Attacks
        • Dictionary Attacks
        • Credential Stuffing
        • MFA Fatigue
        • Pass the Hash attacks
        • Kerberos Attacks
        • Pass the Ticket Attacks
      • Vulnerable Encryption Methods
      • Tools
        • Metsploit
        • Netcat
        • LOLbins
        • Mimikatz
        • Rubeus
        • Certify
        • AD Search
        • Powerview
        • SeaBelt
        • Evil winRM
        • PSEXEC
        • Powersploit
        • Metasploit
        • Impacket
        • Responder
        • CrackMapExec
        • Msfvenom
        • Responder
        • Searhsploit
        • Powersploit
      • Password Attacks
        • Password Cracking
        • Password Spraying
        • Tools
          • Medusa
          • Burpsuite
          • John the Ripper
          • Hydra
          • Hashcat
        • Password Attacks
    • Lateral Movement
      • Relay Creation
      • String Searches
      • Service Discovery
      • Tunneling
        • SSH Tunneling
      • Pivoting
      • Exfiltration
        • DNS
        • HTTPS
        • EMail
        • Cloud Storage
      • Tools
        • sshuttle
        • Page 1
    • Post Exploitation
      • Persistance
        • Scheduled Taks
        • Bind Shell
        • Registry Keys
        • C2 Frameworks
        • Tampering Security Controls
        • Back Door
          • Trojan
          • Root Kit
          • Web Shell
        • Searching Valid Account Credetials
        • New Account Creation
        • Reverse Shell
        • Service Creation
        • Cron Jobs
      • Command and Control
    • Reporting
  • Cybersecurity Frameworks and Standards
    • CREST
    • CIS
    • NIST Publications
      • NIST SP 800-171
      • NIST CSF
      • NIST SP 800-115
    • MITRE
      • MITRE D3FEND
      • MITRE ATT&CK
    • Penetration Testing Execution Standard (PTES)
    • OWASP Top 10
    • Purdue Model
    • Open Source Security Testing Methodology Manual (OSSTMM)
    • Council of Registered Ethical Security Testers (CREST)
    • Zero Trust
    • CMMC
    • Threat Modeling Frameworks
      • STRIDE
      • OCTAVE
      • DREAD
    • Mitigation Strategies
      • Network Segmentaion
      • Access Control
      • Application Control
      • Isolation Techniques
      • Default Password Changes
      • Host based firewall
      • Protocol blocking
      • Port blocking
      • Host based intrusion prevention
      • Endpoint Management
      • Decommissioning
      • Configuration Management
      • Least Privilege
      • Logging
      • Monitoring
      • Encryption
      • Patching
    • Security Governance
      • Data and System: Roles and Responsiblities
      • Security Policies
        • Access Use Policy
      • Security Standards
        • Access Control
        • Encryption
        • Password
      • Security Procedures
        • Change Management
  • Security Domains
    • Security Designing
    • Application Security
      • Cryptographic Attacks
      • Password Attacks
      • Web Application Security
        • Enumeration
          • Cookie and Header Security Review
        • Bruteforce Attack
        • Directory Traversal
        • Insecure Direct Object Reference (IDOR)
        • Session Hijacking
        • File Inclusion Attacks
          • LFI
          • Webshell
          • RFI
        • Server-Side Request Forgery (SSRF)
        • Deserialization Attacks
        • Command Injection
        • Server Side Template Injection
        • Cross Site Scripting (XSS)
        • SQL Injection
          • Union Based SQL Injection
          • Blind SQL Injection
        • Cross-Site Request Forgery (CSRF)
        • XML External Entity (XXE)
        • File Upload Vulnerabilites
        • Remote Code Execution (RCE)
        • Tools
          • Hetty
      • OWASP TOP 10 API
        • API Abuse
        • JWT Token manipulation
        • Graph QL security
        • API security
      • OWASP Top 10 Mobile
      • OWASP Top 10 IOT
      • Web Application Security
        • Getting Started in BugBounty Hutning
        • Subdomain Enumeration
        • Subdomain Takeover: Understanding the Risks and Prevention
        • Tools and Technologies
      • Microservices
      • WPscan
        • Burpsuite
        • Ffuf
        • Gobuster
        • Postman
        • Dirbuster
        • Wfuzz
        • ZAP
      • Tools
        • BurpSuite
        • SQLmap
    • Cloud Security
      • Metadata Service Attacks
      • IAM misconfigurations
      • Tools
        • Pacu
        • Prowler
        • Scoutsuite
        • Docker Bench
      • Container Escape
      • Workload Runtime Attacks
      • Supply Chain Attacks
      • Misconfigurations
        • Network Segmentation
        • Network Controls
        • IAM Credentials
        • Public Access to Services
        • Exposed Storage Buckets
        • Logging Information Exposure
      • Azure Security : Components and Assessment Guide
        • Azure Security Assessment Tools : Installation and usuage
    • Identity and Access Management
    • Cloud Security
      • Cloud Engineering and Architecture concepts
      • Cloud Data Security
      • Cloud Platform and Infrastructure Security
      • Cloud Application Security
      • Cloud Security Operations
      • Cloud Legal, Risk and Compliance
      • Azure Security
      • Azure Pentest
    • DevSecOps
      • Static Application Security Testing (SAST)
        • Code Quality
        • CheckMarx
        • Sonarqube
          • Sonarqube Installation using Helm Chart on AKS
      • Interactive Application Security Testing (IAST)
      • Dynamic Application Security Testing (DAST)
      • SCA
      • Wazuh SIEM and XDR
        • Wazuh on Azure AKS
        • Azure + Argo
      • DevSecOps
    • Social Engineering
      • Vishing
      • Spearphishing
      • Smishing
      • Eavesdropping
      • Impersonation
      • Watering Hole
      • Shoulder Surfing
      • Whaling
      • Phishing
      • Tools
        • GoPhish
        • Beef
        • Evilginx
        • SET social engineering toolkit
    • DevOps
      • Kubernetes
        • Kubernetes Architecture and Components
        • Mastering kubectl: The Command Line Interface for Kubernetes
        • Overview of Kubernetes Tools and Utilities
        • Container vs Pod vs Deployment
        • Kubernetes and Docker Swarm
        • Deploying a Kubernetes Cluster Using Minikube
        • Deploying a Kubernetes Cluster Using Kind
        • Integrating Kubernetes with Azure Key Vault
        • Containers vs Virtual Machines
        • Comprehensive Guide to Kubernetes Security and Analysis Tools
        • Monitoring Kubernetes with Prometheus and Grafana
        • Introduction to Azure Kubernetes Service (AKS) and Deploying Your First Cluster
        • Kubernetes Persistence with Backend Databases
        • Kubernetes StatefulSet vs. Deployment
        • DevSecOps Architecture for Kubernetes
      • Docker
      • Helm
        • Scenario : Configuring Azure Key Vault and Using Secrets in Helm Deployments
      • Git Ops
        • Argo CD
      • Git and Versioning
      • Terraform
      • Virtualization
    • Mobile Security
      • Android Mobile App Security Assessment
      • Suspicious Malware App Analysis
      • Android App Penetration Testing
      • Permission Abuse
      • Jailbreak/Rooting
      • Tools
        • MobSF
        • Drozer
        • Frida
    • IOT/OT/SCADA
      • Power Supply
        • Juice Jacking
      • RFID
      • Bluetooth
        • BlueJacking
        • Bluetooth Spamming
      • Ports and Services
      • Port Mirroring
      • Modbus Attack
      • CAN Bus Attack
      • Replay Attack
      • Memory Registry Attacks
      • Tools
        • BlueCrack
        • Scapy
        • TCP Replay
    • Network Security
      • Network Attacks
        • DNS Attacks
        • DDOS
      • Network Assessment
      • Wireshark
      • Zeek
      • Snort
      • TCPDump
      • Defensive Network
        • Firewalls
        • Intrusion Detection System
    • Wireless Attacks
      • Service Set Identifier (SSID)
      • Wardriving
      • Evil Twin Attack
      • Deauthentication Attacks
      • Signal Jamming
      • Channel Scanning
      • Signal Strength Scanning
      • Tools
        • WiFi Pumpkin
        • AirCrack Ng
        • Kismet
    • Purple Teaming
      • Tools
        • Infection Monkey
        • Atomic RedTeam
        • Caldera
    • Kubernetes Security
      • AKS Security
      • Kube-Hunter
      • KubeEscape
    • Hardware Security
    • Container Security
      • Grype
      • Trivy
      • Clair
    • AI
      • LLM (Large Language Models)
      • Prompt Engineering
      • AI Cyber Security Risk Management
        • AI Policies
      • AI Security
      • AI Attacks
        • Prompt Injection
        • Model Manipulation
      • Security Frameworks
        • MITRE ATLAS
        • OWASP Top 10 LLMs
        • NIST AI Risk Management Framework
    • Reverse Engineering
      • Scenarios
        • Browser Plugin
        • PDF document
        • Word Doc
        • Windows Binary File
        • Mobile App
      • Buffer Overflow
  • Operational Security
    • Identity and Access Management
      • Identity
      • Authentication
      • Accountability
      • Access Management
      • Authorization
      • Access Controls
    • Deception Technology
      • Honeypot
      • Honeynet
      • Honeyfile
      • Honey Token
    • Cryptography
      • Data at Rest
      • Data at Transit
      • Hashing
      • BlockChain
      • Digital Signatures
      • Certificates
      • Encryption
        • Public Key Infrastructure (PKI)
          • Public Key
          • Private Key
        • Tools
      • Certification Preparation
        • Penetration Testing
        • GRC and Audit
    • File Integrity Monitoring
    • Data Security
      • DLP
    • Change Management
      • Impact Analysis
    • Malware Analysis
      • Malware Analysis Tool
      • Malware Analysis Books
      • university courses and resources related to malware analysis
      • Binary Analysis
    • Data Loss Prevention
    • Threat Modeling
      • Attack Surface Management
        • Introduction
      • Threats, Technologies, Procedures
        • Threat Actors
      • Threat Hunting
        • Indicators of Compromise
      • Threat Assessment
        • Threat Modeling
          • OCTAVE
          • DREAD
          • STRIDE
        • Threat Hunting
          • Threat Hunting Blogs
          • Ransomware: An Overview
          • Threat Hunting and Incident Response Q&A
          • Network Traffic Analysis: Wireshark
          • Threat Hunting Questionnaire
          • KQL
          • Email Header Analysis
          • TH
          • Windows Process Exploration
        • Threat Intelligence
          • Threat Intelligence Tools and Techniques
            • Yara
      • Malware Attacks
    • Digital Forensics
      • Network Forensics
      • Forensic Tool Analysis
      • Data Recovery
    • Endpoint Management
    • SOC/SOAR
      • Threat hunting scenarios
      • Log Management
        • AWS VPC flow log analysis
        • Linux Logs
        • Windows Logs
    • Ransomware Prevention
      • APT Groups
    • Security Automation
      • C
      • Powershell
      • Python
      • C++
      • GO
      • Rust
    • Incident Response
      • Scenarios
        • Windows : No Event Logs
      • Tools
        • Chainsaw
    • Defensive Security Controls
    • Physical Security
      • Physical Attacks
        • USB (Universal Serial Bus)
        • Tailgating
        • Lock Picking
        • RFID Cloning
          • Badge Cloning
    • Personal Security
    • Security Awareness and Training
    • Firewall
    • Network Access Control
    • Intrusion Detection System
    • Intrusion Prevention System
    • Operating System Security
    • Secure Protocol Usuage
    • Business Continuity
    • Email Security
    • DNS Filtering
    • user behaviour analytics
    • Host Security
    • Mobile Device Security
    • Change Management
    • Vulnerability Management
      • Vulnerability Assessment
        • Vulnerability Analysis
      • Types of Vulnerabilites
    • Penetration Testing/Red Teaming
    • Disaster Recovery
    • Logging and Monitoring
      • Monitoring
        • Systems
        • Infrastructure
        • Applications
      • Logging
        • Log Data
          • Application Logs
          • Network Logs
          • WAF Logs
          • IDS/IPS logs
          • OS logs
          • Endpoint Logs
          • Firewall Logs
        • Alerting
        • Log Aggregation
      • Tools
    • Endpoint
    • Security Metrics
  • Industry Specific Security:Case Studies
    • Aviation Security
      • The Integral Role of Airports in National Security : Operations Perspective
      • Cyber Attacks on Airports
      • Navigating the Complex Web of Airport Operations: Key Components and Leading Industry Providers
    • Aviation Security
  • Computational Science
    • Quantum Computing
      • Quantum Computing: Unleashing the Power of Qubits
    • Probability
  • Data Engineering
  • AI/ML and Data Science
    • Installation
      • Ollama
    • Machine Learning
    • Large Language Models (LLM)
    • Security Analytics
    • Untitled
      • Roles and Responsibilites
      • Azure AI Services
        • AI Services Security
        • Monitoring Azure AI Services
        • AI services on containers
  • Application Development
    • Django
  • Radom Topics :)
    • CSA WAI
  • CISSP
Powered by GitBook
On this page

Was this helpful?

  1. 101 Series
  2. Operating Systems
  3. Linux 101

Shell Scripting

Shell scripting is a powerful method to automate tasks on Unix-like operating systems. A shell script is a text file with a series of commands that the shell can execute. It is often used for repetitive tasks, for instance, backups, system monitoring, and file manipulation, so that you don't have to enter each command manually.

Variables: In shell scripting, variables are placeholders or references to data that can change. Variables in shell scripts don't need to be declared and can store strings, integers, or the output of commands.

MY_VARIABLE="Hello, World!"
echo $MY_VARIABLE

Accepting Input from User: You can accept input from the user using the read command.

echo "Enter your name:"
read USER_NAME
echo "Hello, $USER_NAME!"

Showing Output: To show output in shell scripting, you typically use the echo or printf commands.

echo "This will display on the console."
printf "This will %s on the console.\n" "also display"

Standard Streams:

  • stdin (standard input) is the stream where a program reads its input data. It's typically connected to the keyboard, but can also be redirected to read from a file or another command.

  • stdout (standard output) is the stream where a program writes its output data. It's typically displayed on the screen but can be redirected to files or other programs.

  • stderr (standard error) is the stream where a program writes its error messages. It's separate from stdout to allow users to separate regular output from error messages.

Redirecting Streams:

  • > redirects stdout to a file, overwriting the file.

  • >> redirects stdout to a file, appending to the file.

  • 2> redirects stderr to a file.

  • < redirects a file to stdin.

Conditions: Conditional statements allow you to perform different actions based on conditions.

if [ $USER_NAME == "admin" ]; then
    echo "Welcome, admin."
else
    echo "Access denied."
fi

Loops: Loops are used for executing a series of commands repeatedly.

  • For loop:

for i in 1 2 3; do
    echo "Number $i"
done
  • While loop:

while [ $i -lt 5 ]; do
    echo "i is less than 5"
    i=$((i+1))
done
  • Until loop:

until [ $i -ge 5 ]; do
    echo "i is less than 5"
    i=$((i+1))
done

Shell scripting is versatile and can include advanced features like functions, arrays, and signal trapping. It's a critical skill for system administrators and developers working in a Unix-like environment. Below is an example of a shell script that demonstrates core features of shell scripting in the context of a cybersecurity assessment scenario. This script will simulate the following:

  1. Check if a list of domains is accessible.

  2. Download the homepage of each domain.

  3. Search for a specific pattern within the downloaded page that may indicate a security vulnerability (like an exposed admin panel or a specific software version).

  4. Log the results and errors for review.

Please note that this script is for educational purposes only and should not be used without permission on any domain.

#!/bin/bash

# Define a list of domains to check
DOMAINS=("example.com" "testsite.com" "demo.org")

# Pattern to search for in the downloaded content
PATTERN="AdminPanel"

# Directory where we will store the results
RESULT_DIR="scan_results"
mkdir -p "$RESULT_DIR"

# Function to check domain availability and search for a pattern
check_domain() {
    local domain=$1

    # Use wget to download the homepage
    if wget -q -O - "$domain" > "$RESULT_DIR/$domain.html"; then
        echo "[+] Successfully downloaded homepage for $domain"
        
        # Use grep to search for the pattern
        if grep -q "$PATTERN" "$RESULT_DIR/$domain.html"; then
            echo "[!] Found the pattern '$PATTERN' in $domain!"
            echo "$domain" >> "$RESULT_DIR/pattern_found.txt"
        else
            echo "[-] Pattern not found in $domain."
        fi
    else
        echo "[!] Failed to download the homepage for $domain" >&2
        echo "$domain" >> "$RESULT_DIR/errors.txt"
    fi
}

# Loop through the list of domains and call the check_domain function
for domain in "${DOMAINS[@]}"; do
    echo "Checking $domain..."
    check_domain "$domain"
done

echo "Scan completed. Results and errors stored in $RESULT_DIR directory."

To run this script:

  1. Save the script to a file, for example, domain_check.sh.

  2. Make the script executable with chmod +x domain_check.sh.

  3. Run the script with ./domain_check.sh.

This script showcases variable usage, function definitions, conditional statements, loops, pattern searching with grep, and network communication with wget. The logging is split into standard output for successful checks and standard error for issues, demonstrating stream redirection.

Port Scanning Script

Below is a shell script that accepts an IP range as input and scans for open ports 21 (FTP), 22 (SSH), 80 (HTTP), and 443 (HTTPS) using nc (Netcat). This script assumes that Netcat is installed on the system where it's executed. It uses a simple loop and timeout strategy to quickly check if the ports are open.

#!/bin/bash

# Function to scan ports using Netcat
scan_ports() {
    local ip=$1
    local ports=(21 22 80 443)
    for port in ${ports[@]}; do
        nc -zv -w 1 $ip $port 2>&1 | grep succeeded
    done
}

# Read the IP range from the user
read -p "Enter the IP range (e.g., 192.168.1.1-192.168.1.255): " ip_range

# Validate IP range input
if [[ ! $ip_range =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+-[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "Invalid IP range format."
    exit 1
fi

# Extract start and end IP from the range
IFS='-' read -r start_ip end_ip <<< "$ip_range"
IFS='.' read -r s1 s2 s3 s4 <<< "$start_ip"
IFS='.' read -r e1 e2 e3 e4 <<< "$end_ip"

# Convert IPs to integers for comparison
start_ip_int=$(printf "%03d%03d%03d%03d" $s1 $s2 $s3 $s4)
end_ip_int=$(printf "%03d%03d%03d%03d" $e1 $e2 $e3 $e4)

if [[ $start_ip_int -gt $end_ip_int ]]; then
    echo "Start IP cannot be greater than end IP."
    exit 1
fi

# Begin the scanning loop
current_ip=$start_ip
while [[ $start_ip_int -le $end_ip_int ]]; do
    echo "Scanning $current_ip..."
    scan_ports $current_ip

    # Increment IP
    ((s4++))
    if [ $s4 -gt 255 ]; then
        s4=0
        ((s3++))
    fi
    if [ $s3 -gt 255 ]; then
        s3=0
        ((s2++))
    fi
    if [ $s2 -gt 255 ]; then
        s2=0
        ((s1++))
    fi
    if [ $s1 -gt 255 ]; then
        echo "Finished scanning the IP range."
        break
    fi

    current_ip="$s1.$s2.$s3.$s4"
    start_ip_int=$(printf "%03d%03d%03d%03d" $s1 $s2 $s3 $s4)
done

echo "Port scanning completed."

To use this script:

  1. Save the script to a file, for instance, port_scan.sh.

  2. Make the script executable: chmod +x port_scan.sh.

  3. Run the script and enter the IP range when prompted: ./port_scan.sh.

The script prompts for an IP range, calculates the integer equivalents of the start and end IPs for iteration, and uses a while loop to scan each IP address in the range. The nc (Netcat) command is used with the -z flag to scan without sending data, and the -w 1 flag to set a timeout of 1 second for faster scans. The results will show only the connections that succeeded.

References:

PreviousCorn JobsNextLinux OS API's

Last updated 1 year ago

Was this helpful?

Unix / Linux - System Logging
25 Common Linux Bash Script Examples to Get You StartedHostinger Tutorials
LinuxCommand.org: Writing shell scripts.
Bash scripting cheatsheetDevhints.io cheatsheets
Logo
Logo
Logo
Logo