User Account Management
Creating New Users
CentOS/RHEL Systems:
USERNAME=admin
adduser ${USERNAME}
echo securePass123 | sudo passwd ${USERNAME} --stdin &>/dev/null
usermod -aG wheel ${USERNAME} && usermod -aG docker ${USERNAME}
Debian/Ubuntu Systems:
USERNAME=admin
useradd -d /home/${USERNAME} -s /bin/bash -m ${USERNAME}
echo "${USERNAME}:securePass123" | chpasswd
usermod -aG sudo ${USERNAME} && usermod -aG docker ${USERNAME}
Managing Group Membership:
# Remove user from wheel group
gpasswd -d admin wheel
# Delete user along with home directory
sudo userdel -r admin
Passwordless Sudo Configuration
sudo visudo /etc/sudoers
admin ALL=(ALL:ALL) NOPASSWD: ALL
Forcing User Logout
w
pkill -kill -t pts/1
Background Processes and Logging
nohup long_running_task &
tail -f nohup.out
Memory Buffer Cache Management
echo 1 > /proc/sys/vm/drop_caches # Clear pagecache
echo 2 > /proc/sys/vm/drop_caches # Clear slab allocator objects
echo 3 > /proc/sys/vm/drop_caches # Clear both pagecache and slab objects
Shell Shortcuts
| Shortcut | Function |
|---|---|
Ctrl+A |
Jump to line start |
Ctrl+E |
Jump to line end |
Ctrl+Left/Right Arrow |
Move by word |
Ctrl+W |
Cut word before cursor |
Ctrl+U |
Cut from cursor to line start |
Ctrl+K |
Cut from cursor to line end |
Ctrl+Y |
Paste cut content |
Ctrl+R |
Search command history |
Directory and File Navigation
nmtui # NetworkManager TUI for network config
pwd # Show current directory
df -h # Disk space usage
free -lh # Memory utilization
ll -tr /etc # List by modification time (oldest first)
lsof -i:22 # Process listening on port 22
# Reading files with less
less -N /etc/services # -N shows line numbers
# Navigation: Arrow keys, Space (forward), B (backward)
# Search: /pattern, N (next), SHIFT+N (previous), Q (quit)
# Command location lookup
whereis nginx # Binary, source, and manual pages
which mv # Only binary location
Disk Usage Aanlysis
# Sort directories by size
du -sh /* | sort -h
# Find largest items in /var
du -sh /var/* | sort -h
# Hidden files only
du -sh .[!.]* | sort -hr
File Search with find
# Basic find operations
find /etc -type f -name 'config.txt'
find /etc -type f -iname 'config.txt' # Case-insensitive
# Size-based searches
find /tmp -type f -size +100 # Files larger than 100K
find /tmp -type f -size -80 # Files smaller than 80K
find /tmp -type f -size +1M # Files larger than 1MB
# Depth-limited search
find /mnt -maxdepth 2 -type f -size +10
# Permission-based search
find /opt/ -maxdepth 1 -type f -perm 644
# Inode-based lookup
find / -type f -inum 2110038
# Wildcard pattern matching
find / -name '*.txt' # Fuzzy search
# Combining with xargs
find /data -type f -name '*.log' | xargs # Output as single line
cat input.txt | xargs -n2 # Display 2 items per line
# Copy matching files
find /data -type f -name '*.txt' | xargs cp -t /backup/
# Delete operations
find /data -type f -name '1*' | xargs rm
find /data -type f -mtime +10 -delete
# Time-based filters
find /data -type f -mtime +10 # Modified 10+ days ago
find /data -type f -mtime -10 # Modified within 10 days
find /data -type f -mtime 10 # Modified exactly 7 days ago
Directory Tree Visualization
tree /opt # Full tree structure
tree -L 2 /opt # Two levels deep
tree -d /opt # Directories only
Network and System Information
# IP configuration
ifconfig
ip addr
ip a
# Public IP lookup
curl cip.cc
# OS version
cat /etc/redhat-release
uname -a
# Network interface config
vim /etc/sysconfig/network-scripts/ifcfg-ens33
# Hostname configuration
cat /etc/hostname # Config file path
hostnamectl set-hostname newhostname # Apply change
Locale and Encoding
echo $LANG # Check current locale
# Modify encoding
vim /etc/locale.conf
LANG=en_US.UTF-8
source /etc/locale.conf
# Alternative method
localectl set-locale LANG=en_US.UTF-8
Customizing the Prompt (PS1)
echo $PS1 # Current: [\u@\h \W]\$
# Edit /etc/profile to add:
# Show full path
export PS1='[\u@\h \w]\$ '
# Colored prompt
export PS1='\[\e[32;1m\][\u@\h \w]\$ \[\e[0m\]] '
source /etc/profile
System Configuration Files
vim /etc/issue # Pre-login banner
vim /etc/motd # Post-login banner
vim /etc/hosts # Hostname-to-IP mapping
vim /etc/fstab # Auto-mount entries
vim /etc/rc.local # Startup commands
Environment Variables
echo $PATH # Current PATH value
# Add to /etc/profile
PATH=$PATH:/opt/kubernetes/bin
# Verify changes
echo $PATH
Command Aliases
# Scope differences
# /etc/profile or /etc/bashrc → All users
# ~/.bashrc or ~/.bash_profile → Specific user
# View all aliases
alias
# Temporary alias
alias ll='ls -la'
# Remove alias
unalias ll
# Persistent alias - add to ~/.bashrc
alias catnet='cat /etc/sysconfig/network-scripts/ifcfg-eth0'
source ~/.bashrc
Package Management
Yum Repositoreis
ls /etc/yum.repos.d/
# Alibaba Cloud mirror setup
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum repolist
yum clean all && yum makecache
# Tab completion support
yum install bash-completion
RPM Package Operations
rpm -qa | grep package_name # Query installed packages
rpm -ql package_name # List package files
rpm -ivh package.rpm # Install with progress
rpm -Uvh package.rpm # Upgrade
rpm -e package_name --nodeps # Force uninstall
# Query which package provides a command
which ssh
rpm -qf /usr/bin/ssh
rpm -qf `which ssh` # Backticks execute inner command first
Log File Examination
ll -h /var/log/
head -5 /var/log/messages # First 5 lines
tail -6 /var/log/messages # Last 6 lines
# Real-time monitoring
tail -f /var/log/messages # Stop tracking if file rotates
tail -F /var/log/messages # Keep tracking after rotation
tail -f /var/log/secure # Authentication logs
Process Managemant
top # Real-time process viewer
ps # Snapshot of processes
ps -aux # All processes with details
ps -l # Current user's processes
ps -ef # Full format listing
# Filter and terminate
ps -ef | grep nginx
killall -9 nginx
Hardware Information
# CPU
cat /proc/cpuinfo
lscpu
# Load averages
cat /proc/loadavg
w
# Memory
cat /proc/meminfo
free -h
# Storage
cat /proc/mounts
df -h
Network Port Inspection
yum install -y net-tools # Install netstat
ss -lntup # All listening ports
ss -lntup | grep 22 # Filter by port
# Flags: -l list, -n numeric, -u udp, -t tcp, -p process
File Permissions
# Change ownership
chown user.group /path # Owner
chown -R user.group /path # Recursive
# Change group
chgrp group_name file
# Modify permissions
chmod +x script.sh # Add execute
chmod 755 /path # rwxr-xr-x
chmod a+rwx /path # Full access
# View groups
groups
# Add user to group
gpasswd -a username groupname
# Immutable files (even root cannot modify)
chattr +i sensitive_file
lsattr sensitive_file
chattr -i sensitive_file # Remove immutable flag
# Remove user completely
userdel -r username
Symbolic and Hard Links
# Soft link (shortcut)
ln -s /path/to/original link_name
# Hard link (shares inode)
ln /path/to/original link_name
ls -i file # View inode number
# Locate file by inode
find / -type f -inum 2110038
# Count directories
ll /etc/ | grep -c "^d"
Job Control
command & # Run in background
jobs -l # List jobs with PIDs
Ctrl+Z # Suspend job
Ctrl+C # Interrupt job
fg # Bring to foreground
bg # Resume in background
kill -9 PID # Force terminate
kill -15 PID # Graceful terminate
Archive Operations
# Compress
tar zcvf archive.tar.gz source/
# Extract to current directory
tar xvf archive.tar.gz
# Extract to specific directory
tar xvf archive.tar.gz -C /destination/
# List contents
tar tf archive.tar.gz
# Compare files
diff file1 file2
vimdiff file1 file2
Parallel Compression
# Install pigz (parallel gzip)
sudo apt install pigz
# Multi-core compression
sudo tar --use-compress-program=pigz -cvpf data.tar.gz ./data
# Multi-core extraction
sudo tar --use-compress-program=pigz -xvpf data.tar.gz
sudo tar --use-compress-program=pigz -xvpf data.tar.gz -C /target/path
# Split large archive into chunks
split -b 100M data.tar.gz -d backup --additional-suffix=.tar.gz
# Reassemble and extract
cat backup*.tar.gz > data.tar.gz
sudo tar --use-compress-program=pigz -xvpf data.tar.gz
Date and Time
date
date '+%Y-%m-%d %H:%M:%S'
# Copy with timestamp suffix
cp app.log app.log-$(date "+%F_%T")
# Calculate dates
date '+%F' -d '-2day' # 2 days ago
date '+%F' -d '3day' # 3 days ahead
# NTP synchronization
yum install ntpdate
ntpdate ntp1.aliyun.com
Runlevels and Targets
CentOS 6 (SysVinit):
| Level | Purpose |
|---|---|
| 0 | Halt |
| 1 | Single user (password reset) |
| 2 | Multi-user, no network |
| 3 | Multi-user, with network |
| 4 | Reserved |
| 5 | Graphical |
| 6 | Reboot |
runlevel
init 3 # Temporary change
vim /etc/inittab # Permanent change
CentOS 7 (systemd):
# View runlevel mappings
ls -la /usr/lib/systemd/system/runlevel*.target
# Check and set default target
systemctl get-default
systemctl set-default graphical.target
Service Boot Sequence
CentOS 6:
- POST (hardware check)
- MBR read
- GRUB menu
- Kernel loading
- init process (sequential)
- /etc/inittab
- Init scripts
- Service scripts
- mingetty (login prompt)
CentOS 7:
- POST (hardware check)
- MBR read
- GRUB menu
- Kernel loading
- systemd (parallel startup)
- default.target
- sysinit.target
- Services enablement
- mingetty (login prompt)
File Transfer
yum install -y lrzsz
rz -y # Windows → Linux
sz -y filename # Linux → Windows
Scheduled Tasks
yum install cronie
systemctl status crond
# Configuration locations
tail /var/spool/cron/root
tail -f /var/log/cron
tail -f /var/spool/mail/root # Error notifications
# Stop mail notifications
systemctl stop postfix
Cron Syntax
* * * * * command
┬ ┬ ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ └─── Day of week (0-7)
│ │ │ └────── Month (1-12)
│ │ └────────── Day (1-31)
│ └───────────── Hour (0-23)
└─────────────── Minute (0-59)
Scheduling Examples
# Daily at 2:00 AM
00 02 * * * /backup/script.sh
# Every 5 minutes
*/5 * * * * /usr/sbin/ntpdate cn.pool.ntp.org >/dev/null 2>&1
# Every 8 hours
0 */8 * * * sync_data.sh
# Multiple times
00 14,20 * * * /scripts/daily_report.sh
# Date range
01-05 03 * * * incremental_backup.sh
# Redirect all output
58 14 * * * cp /data/file.txt /backup/file.bak >/dev/null 2>&1
# Log output
00 17 * * * /scripts/analyze.sh >/tmp/output.log 2>&1
Timezone Configuration
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime