Introduction to CentOS
CentOS (Community Enterprise Operating System) is a free, enterprise-class Linux distribution derived from Red Hat Enterprise Linux (RHEL). Known for its stability, security, and long-term support, CentOS is widely used for servers, data centers, and enterprise applications. Understanding CentOS administration is essential for maintaining reliable, secure, and efficient Linux-based infrastructure.
System Information and Basic Commands
System Information
# System version and information
cat /etc/centos-release # Show CentOS version
uname -a # Kernel information
hostnamectl # System hostname information
lscpu # CPU information
free -h # Memory usage (human-readable)
df -h # Disk usage (human-readable)
uptime # System uptime and load average
User Management
# User administration
useradd username # Create new user
usermod -aG wheel username # Add user to wheel group (sudo access)
passwd username # Set/change user password
userdel -r username # Delete user and home directory
# User information
id username # Display user ID and groups
who # Show who is logged in
w # Show who is logged in and what they're doing
last # Show last logins
File and Directory Operations
# Basic file operations
ls -la # List all files with details
cp -rp source destination # Copy files/directories recursively preserving attributes
mv source destination # Move/rename files or directories
rm -rf directory # Remove directory recursively (use with caution!)
mkdir -p dir1/dir2/dir3 # Create directory structure
touch filename # Create empty file or update timestamp
# File permissions
chmod 755 file # Change file permissions (rwxr-xr-x)
chown user:group file # Change file ownership
chcon -t httpd_sys_content_t file # Change SELinux context
Process Management
# View processes
ps aux # List all running processes
top # Interactive process viewer
htop # Enhanced interactive process viewer (may need installation)
# Process control
kill PID # Terminate process by PID
kill -9 PID # Force terminate process
killall process_name # Kill all processes by name
nice -n 19 command # Run command with lower priority
renice +10 -p PID # Change priority of running process
Package Management
YUM (CentOS 7) / DNF (CentOS 8+)
# Package installation
yum install package # Install package (CentOS 7)
dnf install package # Install package (CentOS 8+)
yum groupinstall "group" # Install package group
# Package updates
yum update # Update all packages
yum update package # Update specific package
dnf upgrade # Upgrade packages (CentOS 8+)
# Package removal
yum remove package # Remove package
yum autoremove # Remove unneeded dependencies
# Package search and info
yum search keyword # Search packages by keyword
yum info package # Display package information
yum provides /path/to/file # Find which package provides a file
rpm -qa # List all installed packages
rpm -ql package # List files installed by package
Repository Management
# Repository configuration
yum repolist # List enabled repositories
yum-config-manager --enable repo # Enable repository
yum-config-manager --disable repo # Disable repository
# Add a new repository
yum-config-manager --add-repo URL
# EPEL repository installation
yum install epel-release # Install EPEL repository
Service Management
Systemd (CentOS 7 and 8+)
# Service control
systemctl start service # Start a service
systemctl stop service # Stop a service
systemctl restart service # Restart a service
systemctl reload service # Reload configuration without restart
systemctl status service # Check service status
systemctl enable service # Enable service at boot
systemctl disable service # Disable service at boot
# System control
systemctl poweroff # Shut down the system
systemctl reboot # Reboot the system
systemctl suspend # Suspend the system
systemctl hibernate # Hibernate the system
Important System Services
Service | Description | Default Configuration |
---|
sshd | SSH server | /etc/ssh/sshd_config |
httpd | Apache web server | /etc/httpd/conf/httpd.conf |
firewalld | Dynamic firewall manager | /etc/firewalld/ |
named | DNS server (BIND) | /etc/named.conf |
postfix | Mail transfer agent | /etc/postfix/main.cf |
mariadb | MariaDB database server | /etc/my.cnf |
nginx | NGINX web server | /etc/nginx/nginx.conf |
chronyd | Time synchronization | /etc/chrony.conf |
Network Administration
Network Configuration
# Interface information
ip addr show # Show IP addresses
ip link show # Show network interfaces
nmcli device show # NetworkManager device details
nmcli connection show # Show network connections
# Configure network with NetworkManager
nmcli con add type ethernet con-name "My Connection" ifname eth0
nmcli con mod "My Connection" ipv4.addresses 192.168.1.100/24
nmcli con mod "My Connection" ipv4.gateway 192.168.1.1
nmcli con mod "My Connection" ipv4.dns "8.8.8.8 8.8.4.4"
nmcli con mod "My Connection" ipv4.method manual
nmcli con up "My Connection"
# Network testing
ping host # Test connectivity to host
traceroute host # Trace route to host
mtr host # Combination of ping and traceroute
dig domain # DNS lookup
nslookup domain # DNS lookup (alternative)
whois domain # Get WHOIS information
netstat -tulpn # Show listening ports and associated processes
ss -tulpn # Modern alternative to netstat
Firewall Management
# firewalld management
firewall-cmd --state # Check firewall state
firewall-cmd --get-default-zone # Get default zone
firewall-cmd --get-active-zones # Get active zones
firewall-cmd --list-all # List all firewall rules
firewall-cmd --permanent --add-service=http # Add HTTP service
firewall-cmd --permanent --add-port=8080/tcp # Add specific port
firewall-cmd --reload # Reload firewall configuration
Storage Management
Disk and Filesystem Operations
# Partition management
fdisk -l # List disk partitions
fdisk /dev/sda # Partition a disk
gdisk /dev/sda # GPT partition tool
parted -l # List partitions (alternative)
# Filesystem operations
mkfs.ext4 /dev/sda1 # Create ext4 filesystem
mkfs.xfs /dev/sda1 # Create XFS filesystem
mount /dev/sda1 /mnt # Mount filesystem
umount /mnt # Unmount filesystem
# Persistent mounts
blkid # Show block device attributes
# Add to /etc/fstab:
# UUID=xxxx-xxxx /mount_point filesystem defaults 0 0
Logical Volume Management (LVM)
# Physical volumes
pvcreate /dev/sdb # Create physical volume
pvs # List physical volumes
pvdisplay # Display physical volume details
# Volume groups
vgcreate vg_name /dev/sdb # Create volume group
vgs # List volume groups
vgextend vg_name /dev/sdc # Extend volume group
# Logical volumes
lvcreate -L 10G -n lv_name vg_name # Create logical volume
lvs # List logical volumes
lvextend -L +5G /dev/vg_name/lv_name # Extend logical volume
lvreduce -L -5G /dev/vg_name/lv_name # Reduce logical volume
xfs_growfs /mount_point # Resize XFS filesystem after extending
resize2fs /dev/vg_name/lv_name # Resize ext4 after extending/reducing
System Monitoring and Logs
System Monitoring
# Resource monitoring
top # Process activity, CPU usage
htop # Enhanced interactive process viewer
glances # Advanced system monitoring tool
vmstat 1 # Virtual memory statistics
iostat -x 1 # IO statistics
mpstat -P ALL 1 # CPU statistics
sar -u 1 10 # CPU utilization (1 second intervals, 10 times)
# Service and login monitoring
systemctl list-units --state=running # List running services
journalctl -f # Follow system logs
journalctl -u service # View logs for specific service
who # Show logged-in users
w # Show logged-in users and activity
last # Show last logged-in users
Log Management
# Important log files
/var/log/messages # General system logs
/var/log/secure # Authentication logs
/var/log/audit/audit.log # Audit logs
/var/log/httpd/ # Apache logs
/var/log/boot.log # Boot logs
# Log tools
tail -f /var/log/messages # Follow log file in real-time
grep "error" /var/log/messages # Search for errors in log
journalctl --since "1 hour ago" # View logs from last hour
journalctl -p err # View error-level logs
Security and Hardening
SELinux Management
# SELinux status
getenforce # Get current SELinux mode
sestatus # Detailed SELinux status
# SELinux configuration
setenforce 1 # Set Enforcing mode
setenforce 0 # Set Permissive mode (not recommended for production)
# Edit /etc/selinux/config for permanent change
# SELinux troubleshooting
ausearch -m avc -ts recent # Search for recent AVC denials
sealert -a /var/log/audit/audit.log # Analyze SELinux issues
getsebool -a # List all SELinux booleans
setsebool -P http_can_network_connect on # Set boolean permanently
SSH Hardening
# Important settings in /etc/ssh/sshd_config
PermitRootLogin no # Disable root login
PasswordAuthentication no # Disable password authentication
PubkeyAuthentication yes # Enable key-based authentication
AllowUsers user1 user2 # Allow only specific users
Port 2222 # Change SSH port (not 22)
# After changing config:
systemctl restart sshd # Restart SSH server
Password Policies
# Configuration in /etc/login.defs
# For existing users:
chage -M 90 username # Set maximum password age
chage -m 7 username # Set minimum password age
chage -W 14 username # Set password expiration warning
chage -l username # List password aging information
Backup and Recovery
Backup Commands
# File backup tools
tar -czvf backup.tar.gz /path/to/backup # Create compressed archive
tar -xzvf backup.tar.gz # Extract archive
rsync -avz --progress source/ destination/ # Sync directories
# System backup
dd if=/dev/sda of=/path/to/disk.img # Disk image backup
System Snapshots
# LVM snapshots
lvcreate -L 1G -s -n snap_name /dev/vg_name/lv_name # Create snapshot
lvconvert --merge /dev/vg_name/snap_name # Restore from snapshot
Automation and Scripting
Cron Jobs
# Cron configuration
crontab -e # Edit user's crontab
crontab -l # List user's crontab jobs
# Crontab format
# minute hour day month day-of-week command
# Examples:
# 0 5 * * * /path/to/script.sh # Run at 5:00 AM daily
# */10 * * * * command # Run every 10 minutes
Basic Bash Scripting
#!/bin/bash
# Variables
NAME="CentOS"
echo "Hello, $NAME!"
# Conditionals
if [ -f /etc/centos-release ]; then
echo "This is CentOS"
else
echo "This is not CentOS"
fi
# Loops
for i in {1..5}; do
echo "Number: $i"
done
# Functions
function check_service() {
systemctl is-active $1 >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "$1 is running"
else
echo "$1 is not running"
fi
}
check_service httpd
Comparison: CentOS 7 vs. CentOS 8+ vs. CentOS Stream
Feature | CentOS 7 | CentOS 8 | CentOS Stream |
---|
Based on | RHEL 7 | RHEL 8 | Development branch between Fedora and RHEL |
Release Model | Point release | Point release | Rolling release |
Support Until | June 30, 2024 | December 31, 2021 (EOL) | Varies by version |
Package Manager | YUM | DNF | DNF |
Default Filesystem | XFS | XFS | XFS |
Firewall | firewalld | firewalld | firewalld |
Init System | systemd | systemd | systemd |
Python Version | 2.7 | 3.6 | 3.6+ |
Default SELinux | Enforcing | Enforcing | Enforcing |
Common Administration Challenges and Solutions
Challenge | Explanation | Solution |
---|
SELinux denials | Services blocked by SELinux | Check audit.log; use ausearch and sealert; adjust SELinux contexts or booleans |
Disk space issues | Low disk space impacting system | Use df -h and du -sh /*; clear /tmp, /var/log; resize LVM volumes |
Service won’t start | Configuration or dependency issues | Check systemctl status; examine service logs; verify configurations |
Network connectivity | Server unreachable | Check firewall with firewall-cmd –list-all; verify network settings; ping gateway |
Package conflicts | Dependency problems during updates | Use yum/dnf history to rollback; carefully review dependencies; test on non-production first |
Boot failures | System unable to boot properly | Use rescue mode; check /var/log/boot.log; repair GRUB if needed |
Performance issues | Slow system response | Use top, iostat, and vmstat to identify bottlenecks; optimize based on findings |
Best Practices for CentOS Administration
- Regular Updates: Maintain system security by regularly applying security updates
- Configuration Management: Use tools like Ansible, Puppet, or Chef for consistent configurations
- Documentation: Maintain detailed documentation of system configurations and changes
- Monitoring: Implement system monitoring and alerting with tools like Nagios, Zabbix, or Prometheus
- Backup Strategy: Implement regular automated backups with testing of restore procedures
- Security Hardening: Follow CIS benchmarks for CentOS security hardening
- Change Control: Implement change management procedures for production systems
- Performance Tuning: Optimize system performance based on workload requirements
- Log Management: Centralize and monitor logs with tools like ELK stack or Graylog
Resources for Further Learning
Official Documentation
Books
- “RHEL/CentOS 7 Certified System Administrator Study Guide” by Asghar Ghori
- “Mastering CentOS 7 Linux Server” by Mohamed Alibi
- “Pro Linux System Administration” by James Turnbull, et al.
Online Resources
Training and Certification
- Red Hat Certified System Administrator (RHCSA)
- Red Hat Certified Engineer (RHCE)
- Linux Professional Institute Certification (LPIC)