Networking and Shell Scripting
Networking and Shell Scripting
Networking Basics on Linux
Network Configuration
# View network interfaces
ip addr show
ip a # Shortcut
# View the routing table
ip route show
# View active connections
ss -tuln # Listening ports
ss -tupn # With associated processes
# Test connectivity
ping google.com
ping -c 4 192.168.1.1 # 4 pings only
# DNS resolution
nslookup google.com
dig google.com
host google.com
Essential Network Tools
# Download a file
wget https://example.com/fichier.tar.gz
curl -O https://example.com/fichier.tar.gz
# HTTP requests with curl
curl https://api.example.com/users
curl -X POST -H "Content-Type: application/json" \
-d '{"name": "Jean"}' \
https://api.example.com/users
# Transfer files via SSH
scp fichier.txt user@serveur:/home/user/
scp -r dossier/ user@serveur:/tmp/
# Synchronize files
rsync -avz ./projet/ user@serveur:/var/www/projet/
SSH — Secure Connection
# Connect to a remote server
ssh user@serveur.example.com
ssh -p 2222 user@serveur.com # Custom port
# Generate an SSH key pair
ssh-keygen -t ed25519 -C "sacha@example.com"
# Copy the public key to the server
ssh-copy-id user@serveur.com
# SSH configuration (~/.ssh/config)
# ~/.ssh/config
Host prod
HostName 10.0.1.50
User deploy
Port 2222
IdentityFile ~/.ssh/id_prod
Host staging
HostName 10.0.2.50
User deploy
IdentityFile ~/.ssh/id_staging
# Simplified usage
ssh prod # Instead of ssh -p 2222 deploy@10.0.1.50
Firewall with UFW
# Enable the firewall
sudo ufw enable
# Basic rules
sudo ufw allow ssh # Port 22
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
sudo ufw allow from 192.168.1.0/24 # Allow a subnet
# View rules
sudo ufw status verbose
# Delete a rule
sudo ufw delete allow 80/tcp
Bash Scripting
Scripting allows you to automate repetitive tasks. It is an essential skill in system administration.
First Script
#!/bin/bash
# My first script
# Usage: ./hello.sh [name]
nom=${1:-"Monde"} # First argument, "Monde" by default
echo "Bonjour, $nom !"
# Make executable and run
chmod +x hello.sh
./hello.sh
./hello.sh Sacha
Variables and Types
#!/bin/bash
# Simple variables
nom="Sacha"
age=25
repertoire="/var/log"
# Using variables
echo "Je suis $nom, j'ai $age ans"
echo "Les logs sont dans ${repertoire}"
# Result of a command
date_actuelle=$(date +"%Y-%m-%d")
nb_fichiers=$(ls | wc -l)
echo "Aujourd'hui : $date_actuelle, $nb_fichiers fichiers ici"
# Environment variables
echo "Home : $HOME"
echo "Utilisateur : $USER"
echo "Shell : $SHELL"
echo "PATH : $PATH"
# Export a variable
export API_URL="http://localhost:3000"
Conditions
#!/bin/bash
# Test a file
if [ -f "/etc/nginx/nginx.conf" ]; then
echo "Nginx is configured"
elif [ -f "/etc/apache2/apache2.conf" ]; then
echo "Apache is configured"
else
echo "No web server found"
fi
# Numeric comparisons
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print int($2)}')
if [ "$cpu_usage" -gt 80 ]; then
echo "⚠ High CPU usage: ${cpu_usage}%"
fi
# String comparisons
if [ "$USER" = "root" ]; then
echo "You are root!"
fi
# File tests
# -f : file exists -d : directory exists
# -r : readable -w : writable
# -x : executable -s : size > 0
Loops
#!/bin/bash
# For loop
for serveur in web1 web2 web3 db1; do
echo "Pinging $serveur..."
ping -c 1 "$serveur" > /dev/null 2>&1 && echo " ✓ OK" || echo " ✗ Failed"
done
# Loop over files
for fichier in /var/log/*.log; do
taille=$(du -h "$fichier" | cut -f1)
echo "$fichier : $taille"
done
# While loop
compteur=0
while [ $compteur -lt 5 ]; do
echo "Iteration $compteur"
compteur=$((compteur + 1))
done
# Read a file line by line
while IFS= read -r ligne; do
echo "Processing: $ligne"
done < liste-serveurs.txt
Functions
#!/bin/bash
# Define a function
log() {
local niveau=$1
local message=$2
echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$niveau] $message"
}
verifier_service() {
local service=$1
if systemctl is-active --quiet "$service"; then
log "INFO" "$service is active"
return 0
else
log "ERROR" "$service is inactive!"
return 1
fi
}
# Usage
log "INFO" "Starting verification"
verifier_service "nginx"
verifier_service "postgresql"
Practical Script: Automated Backup
#!/bin/bash
# backup.sh — Automated backup of a directory
set -euo pipefail # Stop on error, undefined variable, error in a pipe
# Configuration
SOURCE="/var/www/html"
DESTINATION="/backups"
DATE=$(date +"%Y%m%d_%H%M%S")
ARCHIVE="backup_${DATE}.tar.gz"
RETENTION=7 # Keep backups from the last 7 days
# Checks
if [ ! -d "$SOURCE" ]; then
echo "Error: $SOURCE does not exist" >&2
exit 1
fi
mkdir -p "$DESTINATION"
# Create the backup
echo "Backing up $SOURCE..."
tar -czf "${DESTINATION}/${ARCHIVE}" -C "$(dirname "$SOURCE")" "$(basename "$SOURCE")"
# Check the size
taille=$(du -h "${DESTINATION}/${ARCHIVE}" | cut -f1)
echo "Archive created: ${ARCHIVE} ($taille)"
# Clean up old backups
echo "Deleting backups older than $RETENTION days..."
find "$DESTINATION" -name "backup_*.tar.gz" -mtime +$RETENTION -delete
echo "Backup completed successfully!"
Cron — Scheduling Tasks
# Edit the crontab
crontab -e
# Format: minute hour day month weekday command
# Examples:
# Every day at 2 AM
0 2 * * * /home/sacha/scripts/backup.sh >> /var/log/backup.log 2>&1
# Every 15 minutes
*/15 * * * * /home/sacha/scripts/check-health.sh
# Every Monday at 8 AM
0 8 * * 1 /home/sacha/scripts/rapport-hebdo.sh
# The first of every month
0 0 1 * * /home/sacha/scripts/nettoyage-mensuel.sh
# View scheduled tasks
crontab -l
Scripting Best Practices
- Always start with
#!/bin/bash— the shebang specifies the interpreter - Use
set -euo pipefailto stop at the first error - Quote variables:
"$variable"instead of$variable - Use
localinside functions to avoid side effects - Test with
shellcheck— a linter for Bash scripts - Comment the why, not the what
- Always redirect logs in cron tasks