Operating Systems Guide

Complete guide for operating system administration, security hardening, performance optimization, and advanced system management techniques.

Linux Distributions

Important: Choose your distribution based on your specific use case, hardware requirements, and expertise level.

Popular Server Distributions

Ubuntu Server

Best for: Beginners, cloud deployments, extensive community support

bash
# Install Ubuntu Server 22.04 LTS
wget http://releases.ubuntu.com/22.04/ubuntu-22.04.3-live-server-amd64.iso

# Update system after installation
sudo apt update && sudo apt upgrade -y

# Install essential packages
sudo apt install curl wget git vim htop net-tools -y

CentOS/AlmaLinux

Best for: Enterprise environments, stability, RHEL compatibility

bash
# Download AlmaLinux 9
wget https://repo.almalinux.org/almalinux/9/isos/x86_64/AlmaLinux-9.3-x86_64-dvd.iso

# Update system
sudo dnf update -y

# Install EPEL repository
sudo dnf install epel-release -y

# Install essential tools
sudo dnf install curl wget git vim htop -y

Debian

Best for: Stability, minimal resource usage, advanced users

bash
# Download Debian 12 "Bookworm"
wget https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-12.2.0-amd64-netinst.iso

# Update package list and upgrade
sudo apt update && sudo apt upgrade -y

# Install basic utilities
sudo apt install curl wget git vim htop net-tools sudo -y

Initial System Setup

bash
# Create a new user with sudo privileges
sudo adduser newuser
sudo usermod -aG sudo newuser

# Configure hostname
sudo hostnamectl set-hostname your-server-name

# Set timezone
sudo timedatectl set-timezone Europe/Copenhagen

# Configure static IP (Ubuntu/Debian)
sudo nano /etc/netplan/00-installer-config.yaml

Network Configuration Example

yaml
# /etc/netplan/00-installer-config.yaml
network:
  version: 2
  ethernets:
    enp0s3:
      dhcp4: false
      addresses:
        - 192.168.1.100/24
      gateway4: 192.168.1.1
      nameservers:
        addresses:
          - 8.8.8.8
          - 8.8.4.4

Windows Server

Windows Server 2022 Setup

System Requirements

  • Processor: 1.4 GHz 64-bit
  • RAM: 2GB (Desktop Experience: 4GB)
  • Storage: 32GB minimum
  • Network: Gigabit Ethernet

Installation Types

  • Server Core (recommended for servers)
  • Desktop Experience (GUI)
  • Nano Server (containers)
  • Server Core App Compatibility FOD

PowerShell Administration

powershell
# Configure Server Name and Domain
Rename-Computer -NewName "SERVER01" -Restart

# Install Windows Features
Install-WindowsFeature -Name Web-Server -IncludeManagementTools
Install-WindowsFeature -Name DHCP -IncludeManagementTools
Install-WindowsFeature -Name DNS -IncludeManagementTools

# Configure Firewall
New-NetFirewallRule -DisplayName "HTTP" -Direction Inbound -Protocol TCP -LocalPort 80
New-NetFirewallRule -DisplayName "HTTPS" -Direction Inbound -Protocol TCP -LocalPort 443

# Check Windows Updates
Get-WUList
Install-WUUpdates -AcceptAll -AutoReboot

Active Directory Setup

powershell
# Install AD Domain Services
Install-WindowsFeature AD-Domain-Services -IncludeManagementTools

# Promote server to Domain Controller
Install-ADDSForest -DomainName "company.local" -SafeModeAdministratorPassword (ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force)

# Create Organizational Units
New-ADOrganizationalUnit -Name "Users" -Path "DC=company,DC=local"
New-ADOrganizationalUnit -Name "Computers" -Path "DC=company,DC=local"
New-ADOrganizationalUnit -Name "Servers" -Path "DC=company,DC=local"

# Create user account
New-ADUser -Name "John Doe" -GivenName "John" -Surname "Doe" -SamAccountName "jdoe" -UserPrincipalName "jdoe@company.local" -Path "OU=Users,DC=company,DC=local"

System Administration

User Management

Linux User Management

# Create user with home directory
sudo useradd -m -s /bin/bash username

# Set password
sudo passwd username

# Add to sudoers
sudo usermod -aG sudo username

# Lock/unlock account
sudo usermod -L username  # Lock
sudo usermod -U username  # Unlock

# Delete user and home directory
sudo userdel -r username

Windows User Management

# Create local user
New-LocalUser -Name "username" -Password (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force)

# Add to administrators group
Add-LocalGroupMember -Group "Administrators" -Member "username"

# Disable/Enable account
Disable-LocalUser -Name "username"
Enable-LocalUser -Name "username"

# Remove user
Remove-LocalUser -Name "username"

Service Management

Systemd (Linux)

# Service operations
sudo systemctl start service-name
sudo systemctl stop service-name
sudo systemctl restart service-name
sudo systemctl reload service-name

# Enable/disable at boot
sudo systemctl enable service-name
sudo systemctl disable service-name

# Check status
sudo systemctl status service-name
sudo systemctl is-active service-name

# View logs
sudo journalctl -u service-name -f

Windows Services

# Service operations
Start-Service -Name "ServiceName"
Stop-Service -Name "ServiceName"
Restart-Service -Name "ServiceName"

# Set startup type
Set-Service -Name "ServiceName" -StartupType Automatic

# Get service status
Get-Service -Name "ServiceName"

# View event logs
Get-EventLog -LogName System -Source "Service Control Manager"

Process Management

bash
# View running processes
ps aux
htop
top

# Kill process by PID
kill PID
kill -9 PID  # Force kill

# Kill process by name
pkill process-name
killall process-name

# View process tree
pstree

# Monitor process activity
pidstat 1
iostat 1

Security Hardening

SSH Security Configuration

config
# /etc/ssh/sshd_config - Secure SSH configuration
Port 2222                          # Change default port
Protocol 2
PermitRootLogin no                 # Disable root login
PasswordAuthentication no          # Use key-based auth only
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding no
PrintMotd no
ClientAliveInterval 300
ClientAliveCountMax 2
MaxAuthTries 3
MaxSessions 2
AllowUsers username                # Restrict users

Firewall Configuration

UFW (Ubuntu)

# Enable UFW
sudo ufw enable

# Default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow specific services
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Allow from specific IP
sudo ufw allow from 192.168.1.100

# Delete rule
sudo ufw delete allow 80/tcp

# View status
sudo ufw status verbose

firewalld (CentOS/RHEL)

# Enable firewalld
sudo systemctl enable --now firewalld

# Add services
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https

# Add ports
sudo firewall-cmd --permanent --add-port=8080/tcp

# Reload configuration
sudo firewall-cmd --reload

# List active rules
sudo firewall-cmd --list-all

Fail2Ban Configuration

ini
# /etc/fail2ban/jail.local
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
backend = systemd

[sshd]
enabled = true
port = ssh,2222
logpath = /var/log/auth.log
maxretry = 3

[nginx-http-auth]
enabled = true
filter = nginx-http-auth
logpath = /var/log/nginx/error.log

[nginx-limit-req]
enabled = true
filter = nginx-limit-req
logpath = /var/log/nginx/error.log

System Auditing

bash
# Install and configure auditd
sudo apt install auditd audispd-plugins -y

# Basic audit rules
echo "-w /etc/passwd -p wa -k passwd_changes" >> /etc/audit/rules.d/audit.rules
echo "-w /etc/shadow -p wa -k shadow_changes" >> /etc/audit/rules.d/audit.rules
echo "-w /etc/sudoers -p wa -k sudo_changes" >> /etc/audit/rules.d/audit.rules
echo "-w /var/log/auth.log -p wa -k auth_log" >> /etc/audit/rules.d/audit.rules

# Restart auditd
sudo systemctl restart auditd

# Search audit logs
sudo ausearch -k passwd_changes
sudo aureport --summary

Performance Tuning

Kernel Parameters Optimization

config
# /etc/sysctl.conf - Performance optimizations
# Network optimizations
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_congestion_control = bbr
net.core.netdev_max_backlog = 5000

# File system optimizations
fs.file-max = 2097152
vm.swappiness = 10
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5

# Security optimizations
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Apply changes
sudo sysctl -p

I/O Scheduler Optimization

bash
# Check current I/O scheduler
cat /sys/block/sda/queue/scheduler

# Set I/O scheduler for SSD (temporary)
echo mq-deadline > /sys/block/sda/queue/scheduler

# Set I/O scheduler permanently
echo 'GRUB_CMDLINE_LINUX="elevator=mq-deadline"' >> /etc/default/grub
sudo update-grub

# For NVMe drives
echo none > /sys/block/nvme0n1/queue/scheduler

# Monitor I/O performance
iotop -a
iostat -x 1

CPU Performance Tuning

bash
# Install CPU frequency tools
sudo apt install cpufrequtils -y

# Set CPU governor to performance
sudo cpufreq-set -g performance

# View CPU information
lscpu
cat /proc/cpuinfo

# Monitor CPU usage
htop
mpstat 1
sar -u 1

# Set CPU affinity for process
taskset -c 0,1 process_command

# View CPU topology
lstopo

Memory Optimization

bash
# View memory usage
free -h
cat /proc/meminfo

# Clear cache (if needed)
sync && echo 3 > /proc/sys/vm/drop_caches

# Configure swap
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# Add to fstab for persistence
echo '/swapfile none swap sw 0 0' >> /etc/fstab

# Monitor memory usage
vmstat 1
sar -r 1

System Monitoring

Essential Monitoring Tools

Htop - Interactive Process Viewer

# Install htop
sudo apt install htop -y

# Run htop
htop

# Useful htop shortcuts:
# F2 - Setup/Configuration
# F3 - Search
# F4 - Filter
# F5 - Tree view
# F6 - Sort by column
# F9 - Kill process
# F10 - Quit

Netdata - Real-time Performance

# Install Netdata
bash <(curl -Ss https://my-netdata.io/kickstart.sh)

# Configure Netdata
sudo nano /etc/netdata/netdata.conf

# Access web interface
# http://server-ip:19999

# Secure Netdata with nginx reverse proxy
sudo nano /etc/nginx/sites-available/netdata

Prometheus + Grafana

# Install Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.40.0/prometheus-2.40.0.linux-amd64.tar.gz
tar xzf prometheus-2.40.0.linux-amd64.tar.gz
sudo mv prometheus-2.40.0.linux-amd64 /opt/prometheus

# Install Node Exporter
wget https://github.com/prometheus/node_exporter/releases/download/v1.5.0/node_exporter-1.5.0.linux-amd64.tar.gz
tar xzf node_exporter-1.5.0.linux-amd64.tar.gz
sudo mv node_exporter-1.5.0.linux-amd64 /opt/node_exporter

Log Management

bash
# Important log files to monitor
tail -f /var/log/syslog          # System messages
tail -f /var/log/auth.log        # Authentication logs
tail -f /var/log/kern.log        # Kernel messages
tail -f /var/log/nginx/access.log # Nginx access logs
tail -f /var/log/nginx/error.log  # Nginx error logs

# Use journalctl for systemd logs
journalctl -f                     # Follow all logs
journalctl -u service-name -f     # Follow specific service
journalctl --since "1 hour ago"   # Recent logs
journalctl -p err                 # Only error messages

# Log rotation configuration
sudo nano /etc/logrotate.conf
sudo logrotate -d /etc/logrotate.conf  # Test configuration

Alert Configuration

bash
# Install and configure Monit
sudo apt install monit -y

# Basic monit configuration
sudo nano /etc/monit/monitrc

# Example monit checks
check system localhost
    if loadavg (1min) > 4 then alert
    if loadavg (5min) > 2 then alert
    if memory usage > 75% then alert
    if cpu usage (user) > 70% then alert

check process nginx with pidfile /var/run/nginx.pid
    start program = "/bin/systemctl start nginx"
    stop program  = "/bin/systemctl stop nginx"
    if failed host localhost port 80 protocol http then restart

# Enable and start monit
sudo systemctl enable --now monit

Backup & Recovery

Backup Strategies

Rsync Backups

# Basic rsync backup
rsync -av --delete /source/ /backup/

# Remote backup over SSH
rsync -avz --delete -e ssh /source/ user@backup-server:/backup/

# Incremental backup script
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
SOURCE="/home"
BACKUP_DIR="/backup"
LINK_DEST="$BACKUP_DIR/latest"

rsync -av --delete --link-dest="$LINK_DEST" "$SOURCE/" "$BACKUP_DIR/$DATE/"
ln -sfn "$BACKUP_DIR/$DATE" "$LINK_DEST"

Tar Archives

# Create compressed archive
tar -czf backup_$(date +%Y%m%d).tar.gz /path/to/backup

# Create archive with exclusions
tar --exclude='/proc' --exclude='/sys' --exclude='/dev' \
    -czf system_backup.tar.gz /

# Extract archive
tar -xzf backup.tar.gz

# List archive contents
tar -tzf backup.tar.gz

# Automated backup script with rotation
#!/bin/bash
tar -czf /backup/daily_$(date +%Y%m%d).tar.gz /home
find /backup -name "daily_*.tar.gz" -mtime +7 -delete

Database Backups

bash
# MySQL/MariaDB backup
mysqldump -u root -p --all-databases > all_databases_$(date +%Y%m%d).sql
mysqldump -u root -p database_name > database_$(date +%Y%m%d).sql

# PostgreSQL backup
pg_dumpall -U postgres > all_databases_$(date +%Y%m%d).sql
pg_dump -U postgres database_name > database_$(date +%Y%m%d).sql

# Automated MySQL backup script
#!/bin/bash
DB_USER="backup_user"
DB_PASS="backup_password"
BACKUP_DIR="/backup/mysql"
DATE=$(date +%Y%m%d)

mkdir -p "$BACKUP_DIR"
mysqldump -u "$DB_USER" -p"$DB_PASS" --all-databases | gzip > "$BACKUP_DIR/all_db_$DATE.sql.gz"
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +30 -delete

System Recovery

bash
# Create bootable rescue USB
dd if=ubuntu-22.04-live-server-amd64.iso of=/dev/sdX bs=4M status=progress

# Boot into recovery mode (GRUB)
# Select "Advanced options" -> "recovery mode"

# Mount filesystem in recovery
mount -o remount,rw /
mount --all

# Restore from backup
tar -xzf /backup/system_backup.tar.gz -C /

# Fix boot issues
grub-install /dev/sda
update-grub

# Check filesystem
fsck /dev/sda1
e2fsck -f /dev/sda1

Virtualization

KVM/QEMU Setup

bash
# Check virtualization support
egrep -c '(vmx|svm)' /proc/cpuinfo
ls /dev/kvm

# Install KVM and related packages
sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virt-manager -y

# Add user to libvirt group
sudo usermod -aG libvirt $USER

# Start and enable libvirtd
sudo systemctl enable --now libvirtd

# Create VM storage pool
virsh pool-define-as default dir - - - - "/var/lib/libvirt/images"
virsh pool-build default
virsh pool-start default
virsh pool-autostart default

# Create virtual machine
virt-install \
  --name ubuntu-vm \
  --ram 2048 \
  --disk path=/var/lib/libvirt/images/ubuntu-vm.qcow2,size=20 \
  --vcpus 2 \
  --os-type linux \
  --os-variant ubuntu20.04 \
  --network bridge=virbr0 \
  --graphics none \
  --console pty,target_type=serial \
  --location 'http://archive.ubuntu.com/ubuntu/dists/focal/main/installer-amd64/' \
  --extra-args 'console=ttyS0,115200n8 serial'

Docker Containerization

bash
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

# Add user to docker group
sudo usermod -aG docker $USER

# Install Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose

# Basic Docker commands
docker run hello-world
docker ps
docker images
docker stop container_id
docker rm container_id
docker rmi image_id

# Create Dockerfile example
cat > Dockerfile << EOF
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y nginx
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
EOF

# Build and run container
docker build -t my-nginx .
docker run -d -p 80:80 my-nginx

Hyper-V (Windows)

powershell
# Enable Hyper-V feature
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

# Create virtual switch
New-VMSwitch -Name "External Switch" -NetAdapterName "Ethernet" -AllowManagementOS $true

# Create virtual machine
New-VM -Name "TestVM" -MemoryStartupBytes 2GB -Generation 2 -NewVHDPath "C:\VMs\TestVM.vhdx" -NewVHDSizeBytes 40GB -SwitchName "External Switch"

# Configure VM settings
Set-VM -Name "TestVM" -ProcessorCount 2
Set-VM -Name "TestVM" -DynamicMemory -MemoryMinimumBytes 1GB -MemoryMaximumBytes 4GB

# Start VM
Start-VM -Name "TestVM"

# Connect to VM
vmconnect localhost "TestVM"

Troubleshooting

Common System Issues

System Won't Boot

Diagnosis Steps:
  • Check GRUB configuration
  • Verify filesystem integrity
  • Check hardware connections
  • Review boot logs
# Boot from rescue media and check
mount /dev/sda1 /mnt
chroot /mnt
grub-install /dev/sda
update-grub
exit
reboot

Network Issues

Troubleshoot Network:
  • Check physical connections
  • Verify IP configuration
  • Test DNS resolution
  • Check routing table
# Network diagnostics
ip addr show
ip route show
ping 8.8.8.8
nslookup google.com
netstat -tuln

Disk Space Issues

Free Up Space:
  • Find large files and directories
  • Clean package cache
  • Remove old logs
  • Clean temporary files
# Disk space analysis
df -h
du -sh /* | sort -rh
find / -type f -size +100M
apt clean
journalctl --vacuum-time=7d

High Memory Usage

Memory Analysis:
  • Identify memory-hungry processes
  • Check for memory leaks
  • Configure swap
  • Optimize applications
# Memory troubleshooting
free -h
ps aux --sort=-%mem | head
cat /proc/meminfo
sar -r 1 10
echo 3 > /proc/sys/vm/drop_caches

Diagnostic Commands

System Information

# Hardware information
lshw -short
lscpu
lsmem
lsblk
lspci
lsusb

# System information
uname -a
hostnamectl
timedatectl
systemctl --failed

Performance Analysis

# CPU analysis
top
htop
vmstat 1 10
sar -u 1 10

# I/O analysis
iotop
iostat -x 1 10
lsof +D /path/to/directory

# Network analysis
ss -tuln
netstat -i
iftop
tcpdump -i eth0

Emergency Recovery

bash
# Boot into single user mode
# Add "single" or "1" to kernel parameters in GRUB

# Reset root password
mount -o remount,rw /
passwd root
sync
reboot

# Recover deleted files (if filesystem supports)
testdisk /dev/sda
photorec /dev/sda

# System file integrity check
rpm -Va  # CentOS/RHEL
debsums -c  # Debian/Ubuntu

# Kernel module troubleshooting
lsmod
modprobe module_name
rmmod module_name
dmesg | tail