Skip to content

Latest commit

 

History

History
583 lines (431 loc) · 15.4 KB

File metadata and controls

583 lines (431 loc) · 15.4 KB

Lab 3.3: PowerShell and Python for Network Tasks

Overview

As a network engineer, you'll work in mixed environments - Windows infrastructure requires PowerShell, while network devices and cross-platform automation favor Python. This lab shows you the same networking tasks in both languages so you can work effectively in either environment.

In this lab, you'll learn:

  • PowerShell networking cmdlets and pipeline concepts
  • Python equivalents for the same tasks
  • When to use PowerShell vs Python
  • Network connectivity testing and API interactions

Prerequisites:

  • Windows machine with PowerShell 5.1+ or PowerShell Core 7+
  • Basic understanding of networking (IP addresses, DNS, ports)

Note: This lab runs on Windows. PowerShell examples use native cmdlets. Python examples work cross-platform.


Part 1: Understanding PowerShell Basics

Before diving into networking, let's understand how PowerShell differs from Python.

Step 1: PowerShell Fundamentals

Open PowerShell (not Command Prompt!):

# PowerShell returns OBJECTS, not text
Get-Process | Get-Member

# Pipeline passes objects, not strings
Get-Process | Where-Object CPU -gt 10 | Select-Object Name, CPU

# Everything is a .NET object
$text = "hello"
$text.GetType()
$text.ToUpper()

Key concept: PowerShell works with objects (properties/methods). Python works with data structures (dicts/lists/objects).

Step 2: Python Comparison

Open Python (in PowerShell terminal):

pip install psutil
python
>>> # Python uses data structures
>>> import psutil
>>> 
>>> # Get processes - returns list of objects
>>> processes = [p.info for p in psutil.process_iter(['name', 'memory_percent'])]
>>> 
>>> # Filter with comprehension - find high memory usage
>>> high_mem = [p for p in processes if p['memory_percent'] and p['memory_percent'] > 1]
>>> high_mem[:5]  # Show top 5
>>> exit()

The difference:

  • PowerShell: Object-oriented shell with pipeline (cmdlets pass objects)
  • Python: Object-oriented Programming language with libraries (functions return data)

Part 2: Local Network Information

Let's get information about network adapters, IP addresses, and routes.

Step 1: PowerShell - Network Discovery

# Get all network adapters
Get-NetAdapter

# Get IP addresses
Get-NetIPAddress

# Filter for IPv4 only
Get-NetIPAddress -AddressFamily IPv4

# Get adapters that are UP
Get-NetAdapter | Where-Object Status -eq "Up"

# Get routing table
Get-NetRoute

# Get default gateway
Get-NetRoute -DestinationPrefix "0.0.0.0/0"

# Get ARP cache (IP to MAC address mappings)
arp -a

# Get DNS servers
Get-DnsClientServerAddress

# Combine info - pipeline magic!
Get-NetAdapter | Where-Object Status -eq "Up" | Get-NetIPAddress -AddressFamily IPv4

Understanding the routing and ARP:

  • Get-NetRoute shows the routing table - where different destination networks should go
    • Routes with specific CIDRs (like 192.168.1.0/24) go directly to local network
    • 0.0.0.0/0 (default route) sends everything else to your router/gateway
  • arp -a shows the ARP cache - which MAC addresses correspond to which IP addresses
    • When your computer sends data to an IP on the local network, it uses ARP to find the physical MAC address
    • For destinations outside your network, packets go to the default gateway, which then routes them further

Flow example:

  1. Want to reach 8.8.8.8 (Google DNS)
  2. Routing table says "no specific route, use default gateway 0.0.0.0/0"
  3. ARP cache tells you the MAC address of your router
  4. Packet goes to router, which forwards it to the internet

PowerShell strength: Built-in cmdlets return structured data. No parsing needed!

Step 2: Python - Same Tasks

Create network_info.py:

import socket
import psutil

# Get hostname
hostname = socket.gethostname()
print(f"Hostname: {hostname}")

# Get all network interfaces
print("\n=== Network Interfaces ===")
for interface, addrs in psutil.net_if_addrs().items():
    print(f"\n{interface}:")
    for addr in addrs:
        if addr.family == socket.AF_INET:  # IPv4
            print(f"  IPv4: {addr.address}")
            print(f"  Netmask: {addr.netmask}")

# Get interface statistics
print("\n=== Interface Status ===")
stats = psutil.net_if_stats()
for interface, stat in stats.items():
    status = "UP" if stat.isup else "DOWN"
    print(f"{interface}: {status}, Speed: {stat.speed}Mbps")

# Get routing table (Windows-specific using subprocess)
import subprocess
import re

print("\n=== Default Gateway ===")
result = subprocess.run(["route", "print", "0.0.0.0"], 
                       capture_output=True, text=True)
# Parse output (text processing)
for line in result.stdout.split('\n'):
    if '0.0.0.0' in line and 'On-link' not in line:
        parts = line.split()
        if len(parts) >= 3:
            print(f"Gateway: {parts[2]}")
            break

Run it:

python network_info.py

Python approach: Uses libraries (psutil, socket). More code, but works cross-platform (Linux, Mac, Windows).

Step 3: Comparison

Task PowerShell Python
Get adapters Get-NetAdapter psutil.net_if_addrs()
Get IPs Get-NetIPAddress psutil.net_if_addrs()
Get routes Get-NetRoute subprocess + parsing
Filter Where-Object List comprehension
Format Select-Object Dict manipulation

When to use:

  • PowerShell: Quick Windows network checks, scripting on Windows servers
  • Python: Cross-platform scripts, complex logic, integration with other tools

Part 3: Testing Network Connectivity

Testing if hosts are reachable and ports are open.

⚠️ LEGAL DISCLAIMER: Port scanning can be considered a cyber crime in many jurisdictions when performed without authorization. Only test ports on:

  • Your own systems and servers
  • Internal services you run (localhost, internal networks with permission)
  • Well-known public services on standard ports (80/HTTP, 443/HTTPS) for sites like Google, GitHub, etc.

Never scan random IP addresses or attempt to probe ports on systems you don't own or have explicit permission to test. This lab uses public services (google.com) on standard web ports for educational purposes only.

Step 1: PowerShell - Connectivity Testing

# Ping a host (ICMP)
Test-Connection -ComputerName 8.8.8.8 -Count 4

# Quiet mode (just true/false)
Test-Connection -ComputerName google.com -Count 1 -Quiet

# Test TCP port (this is huge!)
Test-NetConnection -ComputerName google.com -Port 443

# Test multiple ports
$ports = 80, 443
foreach ($port in $ports) {
    $result = Test-NetConnection -ComputerName google.com -Port $port -WarningAction SilentlyContinue
    if ($result.TcpTestSucceeded) {
        Write-Host "Port $port is OPEN" -ForegroundColor Green
    } else {
        Write-Host "Port $port is CLOSED" -ForegroundColor Red
    }
}

# Traceroute
Test-NetConnection -ComputerName google.com -TraceRoute

PowerShell wins here: Test-NetConnection is incredibly powerful and built-in.

Step 2: Python - Same Tasks

Create connectivity_test.py:

import socket
import subprocess
import platform

def ping(host, count=4):
    """Ping a host - works cross-platform"""
    param = '-n' if platform.system().lower() == 'windows' else '-c'
    command = ['ping', param, str(count), host]
    
    result = subprocess.run(command, capture_output=True, text=True)
    return result.returncode == 0

def test_port(host, port, timeout=3):
    """Test if a TCP port is open"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(timeout)
    
    try:
        result = sock.connect_ex((host, port))
        sock.close()
        return result == 0
    except socket.gaierror:
        return False

# Test ping
print("=== Ping Test ===")
hosts = ["8.8.8.8", "google.com", "192.168.1.1"]
for host in hosts:
    status = "✓ UP" if ping(host, 2) else "✗ DOWN"
    print(f"{host}: {status}")

# Test ports
print("\n=== Port Test ===")
test_cases = [
    ("google.com", 443, "HTTPS"),
    ("google.com", 80, "HTTP"),
]

for host, port, service in test_cases:
    status = "✓ OPEN" if test_port(host, port) else "✗ CLOSED"
    print(f"{host}:{port} ({service}): {status}")

Run it:

python connectivity_test.py

Python approach: More code, but you understand exactly what's happening. This uses TCP sockets under the hood.


Part 4: DNS Operations

Looking up hostnames, IP addresses, and DNS records.

Step 1: PowerShell - DNS Queries

# Forward lookup (name to IP)
Resolve-DnsName google.com

# Get specific record type
Resolve-DnsName google.com -Type A

# Reverse lookup (IP to name)
Resolve-DnsName 8.8.8.8

# MX records (mail servers)
Resolve-DnsName google.com -Type MX

# NS records (nameservers)
Resolve-DnsName google.com -Type NS

# TXT records
Resolve-DnsName google.com -Type TXT

# Query specific DNS server
Resolve-DnsName google.com -Server 8.8.8.8

# Get all record types
Resolve-DnsName google.com -Type ALL

Step 2: Python - DNS Operations

Create dns_lookup.py:

import socket

# Basic lookup (name to IP)
def lookup_host(hostname):
    """Get IP address from hostname"""
    try:
        ip = socket.gethostbyname(hostname)
        return ip
    except socket.gaierror:
        return None

# Reverse lookup (IP to name)
def reverse_lookup(ip):
    """Get hostname from IP"""
    try:
        hostname = socket.gethostbyaddr(ip)[0]
        return hostname
    except socket.herror:
        return None

# Test lookups
print("=== DNS Lookups ===")
hosts = ["google.com", "github.com", "cloudflare.com"]

for host in hosts:
    ip = lookup_host(host)
    print(f"{host} -> {ip}")

print("\n=== Reverse Lookups ===")
ips = ["8.8.8.8", "1.1.1.1"]

for ip in ips:
    hostname = reverse_lookup(ip)
    print(f"{ip} -> {hostname}")

# For advanced DNS queries, use dnspython library
print("\n=== Advanced DNS (requires: pip install dnspython) ===")
try:
    import dns.resolver
    
    # Get A records
    answers = dns.resolver.resolve('google.com', 'A')
    print("\nA records for google.com:")
    for rdata in answers:
        print(f"  {rdata}")
    
    # Get MX records
    answers = dns.resolver.resolve('google.com', 'MX')
    print("\nMX records for google.com:")
    for rdata in answers:
        print(f"  {rdata.preference} {rdata.exchange}")
        
except ImportError:
    print("Install dnspython for advanced DNS: pip install dnspython")
except Exception as e:
    print(f"DNS query failed: {e}")

Run it:

python dns_lookup.py

Key difference:

  • PowerShell: Built-in DNS cmdlets (Windows DNS client)
  • Python: Basic via socket, advanced via dnspython library

Part 5: HTTP and REST APIs

Making HTTP requests for API work and web scraping.

Step 1: PowerShell - HTTP Requests

# Simple GET request
Invoke-RestMethod -Uri "https://api.ipify.org?format=json"

# Invoke-WebRequest (more control)
$response = Invoke-WebRequest -Uri "https://api.github.com/users/github"
$response.StatusCode
$response.Content | ConvertFrom-Json

PowerShell strength: Invoke-RestMethod automatically parses JSON. Very clean for REST APIs.

Step 2: Python - HTTP Requests

Create http_client.py:

import requests
import json

# Simple GET request
print("=== Get Public IP ===")
response = requests.get("https://api.ipify.org?format=json")
print(f"Status: {response.status_code}")
print(f"Your IP: {response.json()['ip']}")

# GET with inspection
print("\n=== GitHub API ===")
response = requests.get("https://api.github.com/users/github")
print(f"Status: {response.status_code}")
print(f"Content-Type: {response.headers['Content-Type']}")

data = response.json()
print(f"Name: {data['name']}")
print(f"Public repos: {data['public_repos']}")

Run it:

# Install requests library first
pip install requests

python http_client.py

Part 6: Hands-On Challenge

Scenario: You need to inventory network connectivity for servers in your environment.

Requirements:

  1. PowerShell script that:

    • Gets all network adapters that are UP
    • Tests connectivity to DNS servers (8.8.8.8, 1.1.1.1)
    • Tests if ports 80, 443, are reachable on a target server (ONLY use google.com or your own servers)
    • Exports results to CSV
  2. Python script that:

    • Reads hostnames from a file
    • Performs DNS lookups for each
    • Tests if port 443 is open (ONLY use google.com or your own servers)
    • Gets public IP via API
    • Exports results to JSON
  3. Comparison document: When would you use each tool for this task?

Bonus: Make the Python script work on both Windows and Linux!


Success Criteria

You've completed this lab when you can:

  • Use PowerShell cmdlets: Get-NetAdapter, Test-NetConnection, Resolve-DnsName, Invoke-RestMethod
  • Understand PowerShell pipeline and object filtering
  • Use Python libraries: socket, psutil, subprocess, requests
  • Test network connectivity in both languages
  • Perform DNS lookups in both languages
  • Make HTTP/REST API calls in both languages
  • Explain when to use PowerShell vs Python

Key Takeaways

What you learned:

PowerShell:

  • Object-oriented shell with pipeline
  • Built-in networking cmdlets (no libraries needed)
  • Best for Windows infrastructure and Azure
  • Test-NetConnection is powerful for port testing
  • Invoke-RestMethod auto-parses JSON

Python:

  • Object-oriented Programming language with libraries
  • Cross-platform and flexible
  • Best for network devices and complex automation
  • requests library for HTTP/REST APIs
  • socket module for low-level networking

Key difference:

  • PowerShell: Admin tool for Windows/Azure
  • Python: Automation language for network devices and services

Quick Reference

PowerShell Commands

# Network info
Get-NetAdapter
Get-NetIPAddress
Get-NetRoute
Get-DnsClientServerAddress

# Connectivity
Test-Connection -ComputerName <host> -Count 4
Test-NetConnection -ComputerName <host> -Port <port>

# DNS
Resolve-DnsName <hostname>
Resolve-DnsName <hostname> -Type MX

# HTTP
Invoke-RestMethod -Uri <url>
Invoke-WebRequest -Uri <url>

# Pipeline
Get-NetAdapter | Where-Object Status -eq "Up"
Get-NetIPAddress | Select-Object IPAddress
Get-NetTCPConnection | Sort-Object State

Python Equivalents

# Network info
import psutil
psutil.net_if_addrs()
psutil.net_if_stats()

# Connectivity
import socket
socket.socket().connect_ex((host, port))

# DNS
import socket
socket.gethostbyname(hostname)

# HTTP
import requests
requests.get(url)
requests.post(url, json=data)

# Parsing
import re
re.findall(pattern, text)

Additional Resources

PowerShell:

Python:


Congratulations! You can now work with networking tasks in both PowerShell and Python. You understand when to use each tool for network automation and infrastructure management!