Day 3: Automation & Network Scripting
📋 Today's Agenda
View Topics
▶
| Topic |
|---|
| Automating System Tasks |
| shutil and pathlib |
| Networking Basics |
| ☕ Break |
| SSH Automation |
| Hands-On Practice |
🤖 System Automation
Simple Backup
import shutil
import os
# Copy file for backup
shutil.copy('config.txt', 'config_backup.txt')
print("Backup created")
# Backup with timestamp
import datetime
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
backup_name = f'config_backup_{timestamp}.txt'
shutil.copy('config.txt', backup_name)
print(f"Backup created: {backup_name}")
# Create backup directory
backup_dir = 'backups'
os.makedirs(backup_dir, exist_ok=True)
shutil.copy('config.txt', f'{backup_dir}/config.txt')
# Backup multiple files
files_to_backup = ['config.txt', 'data.txt', 'log.txt']
for file in files_to_backup:
if os.path.exists(file):
shutil.copy(file, f'backup_{file}')
print(f"Backed up {file}")
Backup with Error Handling
def backup_file(filename):
try:
shutil.copy(filename, f'backup_{filename}')
print(f"Backed up {filename}")
except FileNotFoundError:
print(f"File {filename} not found")
except Exception as e:
print(f"Error backing up {filename}: {e}")
👥 User Management
Note: User management commands require a Linux environment.
These examples show the code structure - practice them on your local machine.
import subprocess
# List users (Linux)
def list_users():
try:
result = subprocess.run(['cat', '/etc/passwd'], capture_output=True, text=True)
return result.stdout
except:
return "Could not list users"
# Check if user exists
def user_exists(username):
try:
result = subprocess.run(['id', username], capture_output=True, text=True)
return result.returncode == 0
except:
return False
# Get user info
def get_user_info(username):
try:
result = subprocess.run(['id', username], capture_output=True, text=True)
if result.returncode == 0:
return result.stdout.strip()
else:
return "User not found"
except:
return "Error getting user info"
📁 File and Folder Management
import shutil
import os
# Copy file
shutil.copy('source.txt', 'destination.txt')
# Copy directory
shutil.copytree('source_folder', 'backup_folder')
# Move/rename file
shutil.move('old_name.txt', 'new_name.txt')
# Remove file
if os.path.exists('temp_file.txt'):
os.remove('temp_file.txt')
# Remove directory and contents
if os.path.exists('temp_folder'):
shutil.rmtree('temp_folder')
🔧 shutil Module
import shutil
# Get disk usage
total, used, free = shutil.disk_usage('/')
print(f"Free space: {free // (1024**3)} GB")
# Copy with metadata
shutil.copy2('source.txt', 'dest.txt')
# Archive files (create zip)
shutil.make_archive('backup', 'zip', 'folder_to_backup')
# Safe copy function
def safe_copy(src, dst):
try:
shutil.copy2(src, dst)
print(f"Copied {src} to {dst}")
except FileNotFoundError:
print(f"Source file {src} not found")
except Exception as e:
print(f"Error copying {src}: {e}")
📂 pathlib Module
from pathlib import Path
# Create path object
path = Path('config.txt')
print(f"Exists: {path.exists()}")
print(f"Name: {path.name}")
print(f"Suffix: {path.suffix}")
# Get file info
file_path = Path('data.txt')
if file_path.exists():
print(f"Size: {file_path.stat().st_size} bytes")
# List files in directory
folder = Path('.')
for file in folder.iterdir():
print(file.name)
# Create directory
new_dir = Path('new_folder')
new_dir.mkdir(exist_ok=True)
# Work with file paths
file_path = Path('folder/subfolder/file.txt')
print(f"Parent: {file_path.parent}")
print(f"Name: {file_path.name}")
print(f"Suffix: {file_path.suffix}")
🌐 Networking Basics
Check Host Reachability
import subprocess
def ping_host(host):
try:
result = subprocess.run(['ping', '-c', '1', host], capture_output=True, text=True)
return result.returncode == 0
except:
return False
# Test
print(f"Google reachable: {ping_host('google.com')}")
print(f"Localhost: {ping_host('localhost')}")
Get Local IP
import socket
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
print(f"Hostname: {hostname}")
print(f"Local IP: {local_ip}")
Check Port
import socket
def check_port(host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except:
return False
# Test common ports
print(f"SSH (22): {check_port('localhost', 22)}")
print(f"HTTP (80): {check_port('localhost', 80)}")
Simple Network Scanner
def scan_ports(host, ports):
open_ports = []
for port in ports:
if check_port(host, port):
open_ports.append(port)
return open_ports
# Scan localhost
common_ports = [22, 80, 443, 8080]
open_ports = scan_ports('localhost', common_ports)
print(f"Open ports: {open_ports}")
🔌 Socket Programming
import socket # Create socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
def connect_to_server(host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
print(f"Connected to {host}:{port}")
sock.close()
return True
except:
print(f"Could not connect to {host}:{port}")
return False
# Simple client
def simple_client(host, port, message):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.send(message.encode())
response = sock.recv(1024)
sock.close()
return response.decode()
except:
return "Connection failed"
🔐 SSH Automation
Note: SSH libraries (paramiko, netmiko) require native Python
and won't work in the browser. Below is the reference code - run these
examples on your local machine with
pip install paramiko netmiko
SSH with Paramiko (Reference)
# Install: pip install paramiko
# Run this locally, not in the browser
import paramiko
def ssh_connect(host, username, password):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=username, password=password)
return ssh
except:
return None
def run_ssh_command(ssh, command):
try:
stdin, stdout, stderr = ssh.exec_command(command)
return stdout.read().decode()
except:
return "Command failed"
# Example usage (run locally):
# ssh = ssh_connect('192.168.1.100', 'admin', 'password')
# output = run_ssh_command(ssh, 'df -h')
# print(output)
SSH with Netmiko (Reference)
# Install: pip install netmiko
# Run this locally, not in the browser
from netmiko import ConnectHandler
def connect_device(host, username, password):
device = {
'device_type': 'linux',
'host': host,
'username': username,
'password': password,
}
try:
connection = ConnectHandler(**device)
return connection
except:
return None
def send_command(connection, command):
try:
output = connection.send_command(command)
return output
except:
return "Command failed"
🛠️ Hands-On: Backup Script
import shutil
import os
import datetime
def backup_file(filename):
if os.path.exists(filename):
shutil.copy(filename, f'backup_{filename}')
print(f"Backed up {filename}")
def backup_with_timestamp(filename):
if os.path.exists(filename):
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
backup_name = f'backup_{timestamp}_{filename}'
shutil.copy(filename, backup_name)
print(f"Backed up {filename} as {backup_name}")
def backup_multiple(files):
for file in files:
if os.path.exists(file):
shutil.copy(file, f'backup_{file}')
print(f"Backed up {file}")
def backup_directory(source_dir, backup_dir):
if os.path.exists(source_dir):
shutil.copytree(source_dir, backup_dir)
print(f"Backed up {source_dir} to {backup_dir}")
🛠️ Hands-On: Network Monitor
import subprocess
def ping_hosts(hosts):
results = {}
for host in hosts:
try:
result = subprocess.run(['ping', '-c', '1', host], capture_output=True, text=True)
results[host] = result.returncode == 0
except:
results[host] = False
return results
def check_common_ports(host):
common_ports = [22, 80, 443, 8080]
open_ports = []
for port in common_ports:
if check_port(host, port):
open_ports.append(port)
return open_ports
def network_status(hosts):
status = {}
for host in hosts:
status[host] = {
'ping': ping_hosts([host])[host],
'ports': check_common_ports(host)
}
return status
# Example usage
hosts = ['localhost', 'google.com']
status = network_status(hosts)
for host, info in status.items():
print(f"{host}: Ping={info['ping']}, Ports={info['ports']}")
✅ What We Did Today
- Automated system tasks (backup, user management)
- Used shutil and pathlib for file operations
- Learned networking basics (ping, ports, sockets)
- Explored SSH automation (reference code)
- Created backup and monitoring scripts
🏠 Homework
- Create a script that backs up important files
- Write a network monitoring script
- Practice SSH connections on your local machine