Linux Production Shell Scripts by sickn33/antigravity-awesome-skills
npx skills add https://github.com/sickn33/antigravity-awesome-skills --skill 'Linux Production Shell Scripts'提供适用于生产环境的 Shell 脚本模板,用于常见的 Linux 系统管理任务,包括备份、监控、用户管理、日志分析和自动化。这些脚本可作为安全运维和渗透测试环境的构建模块。
基本目录备份
#!/bin/bash
backup_dir="/path/to/backup"
source_dir="/path/to/source"
# 创建带时间戳的源目录备份
tar -czf "$backup_dir/backup_$(date +%Y%m%d_%H%M%S).tar.gz" "$source_dir"
echo "Backup completed: backup_$(date +%Y%m%d_%H%M%S).tar.gz"
远程服务器备份
#!/bin/bash
source_dir="/path/to/source"
remote_server="user@remoteserver:/path/to/backup"
# 使用 rsync 将文件/目录备份到远程服务器
rsync -avz --progress "$source_dir" "$remote_server"
echo "Files backed up to remote server."
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
备份轮换脚本
#!/bin/bash
backup_dir="/path/to/backups"
max_backups=5
# 如果备份数量超过 max_backups,则删除最旧的备份进行轮换
while [ $(ls -1 "$backup_dir" | wc -l) -gt "$max_backups" ]; do
oldest_backup=$(ls -1t "$backup_dir" | tail -n 1)
rm -r "$backup_dir/$oldest_backup"
echo "Removed old backup: $oldest_backup"
done
echo "Backup rotation completed."
数据库备份脚本
#!/bin/bash
database_name="your_database"
db_user="username"
db_pass="password"
output_file="database_backup_$(date +%Y%m%d).sql"
# 使用 mysqldump 执行数据库备份
mysqldump -u "$db_user" -p"$db_pass" "$database_name" > "$output_file"
gzip "$output_file"
echo "Database backup created: $output_file.gz"
CPU 使用率监控器
#!/bin/bash
threshold=90
# 监控 CPU 使用率,如果超过阈值则触发警报
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d. -f1)
if [ "$cpu_usage" -gt "$threshold" ]; then
echo "ALERT: High CPU usage detected: $cpu_usage%"
# 在此处添加通知逻辑(邮件、slack 等)
# mail -s "CPU Alert" admin@example.com <<< "CPU usage: $cpu_usage%"
fi
磁盘空间监控器
#!/bin/bash
threshold=90
partition="/dev/sda1"
# 监控磁盘使用率,如果超过阈值则触发警报
disk_usage=$(df -h | grep "$partition" | awk '{print $5}' | cut -d% -f1)
if [ "$disk_usage" -gt "$threshold" ]; then
echo "ALERT: High disk usage detected: $disk_usage%"
# 在此处添加警报/通知逻辑
fi
CPU 使用率记录器
#!/bin/bash
output_file="cpu_usage_log.txt"
# 将带时间戳的当前 CPU 使用率记录到文件
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
cpu_usage=$(top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d. -f1)
echo "$timestamp - CPU Usage: $cpu_usage%" >> "$output_file"
echo "CPU usage logged."
系统健康检查
#!/bin/bash
output_file="system_health_check.txt"
# 执行系统健康检查并将结果保存到文件
{
echo "System Health Check - $(date)"
echo "================================"
echo ""
echo "Uptime:"
uptime
echo ""
echo "Load Average:"
cat /proc/loadavg
echo ""
echo "Memory Usage:"
free -h
echo ""
echo "Disk Usage:"
df -h
echo ""
echo "Top Processes:"
ps aux --sort=-%cpu | head -10
} > "$output_file"
echo "System health check saved to $output_file"
用户账户创建
#!/bin/bash
username="newuser"
# 检查用户是否存在;如果不存在,则创建新用户
if id "$username" &>/dev/null; then
echo "User $username already exists."
else
useradd -m -s /bin/bash "$username"
echo "User $username created."
# 交互式设置密码
passwd "$username"
fi
密码过期检查器
#!/bin/bash
output_file="password_expiry_report.txt"
# 检查使用 bash shell 的用户的密码过期情况
echo "Password Expiry Report - $(date)" > "$output_file"
echo "=================================" >> "$output_file"
IFS=$'\n'
for user in $(grep "/bin/bash" /etc/passwd | cut -d: -f1); do
password_expires=$(chage -l "$user" 2>/dev/null | grep "Password expires" | awk -F: '{print $2}')
echo "User: $user - Password Expires: $password_expires" >> "$output_file"
done
unset IFS
echo "Password expiry report saved to $output_file"
密码生成器
#!/bin/bash
length=${1:-16}
# 生成随机密码
password=$(openssl rand -base64 48 | tr -dc 'a-zA-Z0-9!@#$%^&*' | head -c"$length")
echo "Generated password: $password"
文件加密脚本
#!/bin/bash
file="$1"
action="${2:-encrypt}"
if [ -z "$file" ]; then
echo "Usage: $0 <file> [encrypt|decrypt]"
exit 1
fi
if [ "$action" == "encrypt" ]; then
# 使用 AES-256-CBC 加密文件
openssl enc -aes-256-cbc -salt -pbkdf2 -in "$file" -out "$file.enc"
echo "File encrypted: $file.enc"
elif [ "$action" == "decrypt" ]; then
# 解密文件
output_file="${file%.enc}"
openssl enc -aes-256-cbc -d -pbkdf2 -in "$file" -out "$output_file"
echo "File decrypted: $output_file"
fi
错误日志提取器
#!/bin/bash
logfile="${1:-/var/log/syslog}"
output_file="error_log_$(date +%Y%m%d).txt"
# 从日志文件中提取包含 "ERROR" 的行
grep -i "error\|fail\|critical" "$logfile" > "$output_file"
echo "Error log created: $output_file"
echo "Total errors found: $(wc -l < "$output_file")"
Web 服务器日志分析器
#!/bin/bash
log_file="${1:-/var/log/apache2/access.log}"
echo "Web Server Log Analysis"
echo "========================"
echo ""
echo "Top 10 IP Addresses:"
awk '{print $1}' "$log_file" | sort | uniq -c | sort -rn | head -10
echo ""
echo "Top 10 Requested URLs:"
awk '{print $7}' "$log_file" | sort | uniq -c | sort -rn | head -10
echo ""
echo "HTTP Status Code Distribution:"
awk '{print $9}' "$log_file" | sort | uniq -c | sort -rn
网络连通性检查器
#!/bin/bash
hosts=("8.8.8.8" "1.1.1.1" "google.com")
echo "Network Connectivity Check"
echo "=========================="
for host in "${hosts[@]}"; do
if ping -c 1 -W 2 "$host" &>/dev/null; then
echo "[UP] $host is reachable"
else
echo "[DOWN] $host is unreachable"
fi
done
网站正常运行时间检查器
#!/bin/bash
websites=("https://google.com" "https://github.com")
log_file="uptime_log.txt"
echo "Website Uptime Check - $(date)" >> "$log_file"
for website in "${websites[@]}"; do
if curl --output /dev/null --silent --head --fail --max-time 10 "$website"; then
echo "[UP] $website is accessible" | tee -a "$log_file"
else
echo "[DOWN] $website is inaccessible" | tee -a "$log_file"
fi
done
网络接口信息
#!/bin/bash
interface="${1:-eth0}"
echo "Network Interface Information: $interface"
echo "========================================="
ip addr show "$interface" 2>/dev/null || ifconfig "$interface" 2>/dev/null
echo ""
echo "Routing Table:"
ip route | grep "$interface"
自动化软件包安装
#!/bin/bash
packages=("vim" "htop" "curl" "wget" "git")
echo "Installing packages..."
for package in "${packages[@]}"; do
if dpkg -l | grep -q "^ii $package"; then
echo "[SKIP] $package is already installed"
else
sudo apt-get install -y "$package"
echo "[INSTALLED] $package"
fi
done
echo "Package installation completed."
任务调度器(Cron 设置)
#!/bin/bash
scheduled_task="/path/to/your_script.sh"
schedule_time="0 2 * * *" # 每天凌晨 2 点运行
# 将任务添加到 crontab
(crontab -l 2>/dev/null; echo "$schedule_time $scheduled_task") | crontab -
echo "Task scheduled: $schedule_time $scheduled_task"
服务重启脚本
#!/bin/bash
service_name="${1:-apache2}"
# 重启指定的服务
if systemctl is-active --quiet "$service_name"; then
echo "Restarting $service_name..."
sudo systemctl restart "$service_name"
echo "Service $service_name restarted."
else
echo "Service $service_name is not running. Starting..."
sudo systemctl start "$service_name"
echo "Service $service_name started."
fi
目录同步
#!/bin/bash
source_dir="/path/to/source"
destination_dir="/path/to/destination"
# 使用 rsync 同步目录
rsync -avz --delete "$source_dir/" "$destination_dir/"
echo "Directories synchronized successfully."
数据清理脚本
#!/bin/bash
directory="${1:-/tmp}"
days="${2:-7}"
echo "Cleaning files older than $days days in $directory"
# 删除早于指定天数的文件
find "$directory" -type f -mtime +"$days" -exec rm -v {} \;
echo "Cleanup completed."
文件夹大小检查器
#!/bin/bash
folder_path="${1:-.}"
echo "Folder Size Analysis: $folder_path"
echo "===================================="
# 按大小排序显示子目录的大小
du -sh "$folder_path"/* 2>/dev/null | sort -rh | head -20
echo ""
echo "Total size:"
du -sh "$folder_path"
系统信息收集器
#!/bin/bash
output_file="system_info_$(hostname)_$(date +%Y%m%d).txt"
{
echo "System Information Report"
echo "Generated: $(date)"
echo "========================="
echo ""
echo "Hostname: $(hostname)"
echo "OS: $(uname -a)"
echo ""
echo "CPU Info:"
lscpu | grep -E "Model name|CPU\(s\)|Thread"
echo ""
echo "Memory:"
free -h
echo ""
echo "Disk Space:"
df -h
echo ""
echo "Network Interfaces:"
ip -br addr
echo ""
echo "Logged In Users:"
who
} > "$output_file"
echo "System info saved to $output_file"
Git 仓库更新器
#!/bin/bash
git_repos=("/path/to/repo1" "/path/to/repo2")
for repo in "${git_repos[@]}"; do
if [ -d "$repo/.git" ]; then
echo "Updating repository: $repo"
cd "$repo"
git fetch --all
git pull origin "$(git branch --show-current)"
echo "Updated: $repo"
else
echo "Not a git repository: $repo"
fi
done
echo "All repositories updated."
远程脚本执行
#!/bin/bash
remote_server="${1:-user@remote-server}"
remote_script="${2:-/path/to/remote/script.sh}"
# 通过 SSH 在远程服务器上执行脚本
ssh "$remote_server" "bash -s" < "$remote_script"
echo "Remote script executed on $remote_server"
| 模式 | 用途 |
|---|---|
#!/bin/bash | bash 的 Shebang |
$(date +%Y%m%d) | 日期格式化 |
$((expression)) | 算术运算 |
${var:-default} | 默认值 |
"$@" | 所有参数 |
| 命令 | 用途 |
|---|---|
chmod +x script.sh | 使可执行 |
./script.sh | 运行脚本 |
nohup ./script.sh & | 在后台运行 |
crontab -e | 编辑 cron 作业 |
source script.sh | 在当前 shell 中运行 |
分钟(0-59) 小时(0-23) 日(1-31) 月(1-12) 星期几(0-7, 0/7=周日)
bash -x script.sh 进行调试每周安装次数
–
仓库
GitHub 星标数
27.4K
首次出现时间
–
安全审计
Provide production-ready shell script templates for common Linux system administration tasks including backups, monitoring, user management, log analysis, and automation. These scripts serve as building blocks for security operations and penetration testing environments.
Basic Directory Backup
#!/bin/bash
backup_dir="/path/to/backup"
source_dir="/path/to/source"
# Create a timestamped backup of the source directory
tar -czf "$backup_dir/backup_$(date +%Y%m%d_%H%M%S).tar.gz" "$source_dir"
echo "Backup completed: backup_$(date +%Y%m%d_%H%M%S).tar.gz"
Remote Server Backup
#!/bin/bash
source_dir="/path/to/source"
remote_server="user@remoteserver:/path/to/backup"
# Backup files/directories to a remote server using rsync
rsync -avz --progress "$source_dir" "$remote_server"
echo "Files backed up to remote server."
Backup Rotation Script
#!/bin/bash
backup_dir="/path/to/backups"
max_backups=5
# Rotate backups by deleting the oldest if more than max_backups
while [ $(ls -1 "$backup_dir" | wc -l) -gt "$max_backups" ]; do
oldest_backup=$(ls -1t "$backup_dir" | tail -n 1)
rm -r "$backup_dir/$oldest_backup"
echo "Removed old backup: $oldest_backup"
done
echo "Backup rotation completed."
Database Backup Script
#!/bin/bash
database_name="your_database"
db_user="username"
db_pass="password"
output_file="database_backup_$(date +%Y%m%d).sql"
# Perform database backup using mysqldump
mysqldump -u "$db_user" -p"$db_pass" "$database_name" > "$output_file"
gzip "$output_file"
echo "Database backup created: $output_file.gz"
CPU Usage Monitor
#!/bin/bash
threshold=90
# Monitor CPU usage and trigger alert if threshold exceeded
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d. -f1)
if [ "$cpu_usage" -gt "$threshold" ]; then
echo "ALERT: High CPU usage detected: $cpu_usage%"
# Add notification logic (email, slack, etc.)
# mail -s "CPU Alert" admin@example.com <<< "CPU usage: $cpu_usage%"
fi
Disk Space Monitor
#!/bin/bash
threshold=90
partition="/dev/sda1"
# Monitor disk usage and trigger alert if threshold exceeded
disk_usage=$(df -h | grep "$partition" | awk '{print $5}' | cut -d% -f1)
if [ "$disk_usage" -gt "$threshold" ]; then
echo "ALERT: High disk usage detected: $disk_usage%"
# Add alert/notification logic here
fi
CPU Usage Logger
#!/bin/bash
output_file="cpu_usage_log.txt"
# Log current CPU usage to a file with timestamp
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
cpu_usage=$(top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d. -f1)
echo "$timestamp - CPU Usage: $cpu_usage%" >> "$output_file"
echo "CPU usage logged."
System Health Check
#!/bin/bash
output_file="system_health_check.txt"
# Perform system health check and save results to a file
{
echo "System Health Check - $(date)"
echo "================================"
echo ""
echo "Uptime:"
uptime
echo ""
echo "Load Average:"
cat /proc/loadavg
echo ""
echo "Memory Usage:"
free -h
echo ""
echo "Disk Usage:"
df -h
echo ""
echo "Top Processes:"
ps aux --sort=-%cpu | head -10
} > "$output_file"
echo "System health check saved to $output_file"
User Account Creation
#!/bin/bash
username="newuser"
# Check if user exists; if not, create new user
if id "$username" &>/dev/null; then
echo "User $username already exists."
else
useradd -m -s /bin/bash "$username"
echo "User $username created."
# Set password interactively
passwd "$username"
fi
Password Expiry Checker
#!/bin/bash
output_file="password_expiry_report.txt"
# Check password expiry for users with bash shell
echo "Password Expiry Report - $(date)" > "$output_file"
echo "=================================" >> "$output_file"
IFS=$'\n'
for user in $(grep "/bin/bash" /etc/passwd | cut -d: -f1); do
password_expires=$(chage -l "$user" 2>/dev/null | grep "Password expires" | awk -F: '{print $2}')
echo "User: $user - Password Expires: $password_expires" >> "$output_file"
done
unset IFS
echo "Password expiry report saved to $output_file"
Password Generator
#!/bin/bash
length=${1:-16}
# Generate a random password
password=$(openssl rand -base64 48 | tr -dc 'a-zA-Z0-9!@#$%^&*' | head -c"$length")
echo "Generated password: $password"
File Encryption Script
#!/bin/bash
file="$1"
action="${2:-encrypt}"
if [ -z "$file" ]; then
echo "Usage: $0 <file> [encrypt|decrypt]"
exit 1
fi
if [ "$action" == "encrypt" ]; then
# Encrypt file using AES-256-CBC
openssl enc -aes-256-cbc -salt -pbkdf2 -in "$file" -out "$file.enc"
echo "File encrypted: $file.enc"
elif [ "$action" == "decrypt" ]; then
# Decrypt file
output_file="${file%.enc}"
openssl enc -aes-256-cbc -d -pbkdf2 -in "$file" -out "$output_file"
echo "File decrypted: $output_file"
fi
Error Log Extractor
#!/bin/bash
logfile="${1:-/var/log/syslog}"
output_file="error_log_$(date +%Y%m%d).txt"
# Extract lines with "ERROR" from the log file
grep -i "error\|fail\|critical" "$logfile" > "$output_file"
echo "Error log created: $output_file"
echo "Total errors found: $(wc -l < "$output_file")"
Web Server Log Analyzer
#!/bin/bash
log_file="${1:-/var/log/apache2/access.log}"
echo "Web Server Log Analysis"
echo "========================"
echo ""
echo "Top 10 IP Addresses:"
awk '{print $1}' "$log_file" | sort | uniq -c | sort -rn | head -10
echo ""
echo "Top 10 Requested URLs:"
awk '{print $7}' "$log_file" | sort | uniq -c | sort -rn | head -10
echo ""
echo "HTTP Status Code Distribution:"
awk '{print $9}' "$log_file" | sort | uniq -c | sort -rn
Network Connectivity Checker
#!/bin/bash
hosts=("8.8.8.8" "1.1.1.1" "google.com")
echo "Network Connectivity Check"
echo "=========================="
for host in "${hosts[@]}"; do
if ping -c 1 -W 2 "$host" &>/dev/null; then
echo "[UP] $host is reachable"
else
echo "[DOWN] $host is unreachable"
fi
done
Website Uptime Checker
#!/bin/bash
websites=("https://google.com" "https://github.com")
log_file="uptime_log.txt"
echo "Website Uptime Check - $(date)" >> "$log_file"
for website in "${websites[@]}"; do
if curl --output /dev/null --silent --head --fail --max-time 10 "$website"; then
echo "[UP] $website is accessible" | tee -a "$log_file"
else
echo "[DOWN] $website is inaccessible" | tee -a "$log_file"
fi
done
Network Interface Info
#!/bin/bash
interface="${1:-eth0}"
echo "Network Interface Information: $interface"
echo "========================================="
ip addr show "$interface" 2>/dev/null || ifconfig "$interface" 2>/dev/null
echo ""
echo "Routing Table:"
ip route | grep "$interface"
Automated Package Installation
#!/bin/bash
packages=("vim" "htop" "curl" "wget" "git")
echo "Installing packages..."
for package in "${packages[@]}"; do
if dpkg -l | grep -q "^ii $package"; then
echo "[SKIP] $package is already installed"
else
sudo apt-get install -y "$package"
echo "[INSTALLED] $package"
fi
done
echo "Package installation completed."
Task Scheduler (Cron Setup)
#!/bin/bash
scheduled_task="/path/to/your_script.sh"
schedule_time="0 2 * * *" # Run at 2 AM daily
# Add task to crontab
(crontab -l 2>/dev/null; echo "$schedule_time $scheduled_task") | crontab -
echo "Task scheduled: $schedule_time $scheduled_task"
Service Restart Script
#!/bin/bash
service_name="${1:-apache2}"
# Restart a specified service
if systemctl is-active --quiet "$service_name"; then
echo "Restarting $service_name..."
sudo systemctl restart "$service_name"
echo "Service $service_name restarted."
else
echo "Service $service_name is not running. Starting..."
sudo systemctl start "$service_name"
echo "Service $service_name started."
fi
Directory Synchronization
#!/bin/bash
source_dir="/path/to/source"
destination_dir="/path/to/destination"
# Synchronize directories using rsync
rsync -avz --delete "$source_dir/" "$destination_dir/"
echo "Directories synchronized successfully."
Data Cleanup Script
#!/bin/bash
directory="${1:-/tmp}"
days="${2:-7}"
echo "Cleaning files older than $days days in $directory"
# Remove files older than specified days
find "$directory" -type f -mtime +"$days" -exec rm -v {} \;
echo "Cleanup completed."
Folder Size Checker
#!/bin/bash
folder_path="${1:-.}"
echo "Folder Size Analysis: $folder_path"
echo "===================================="
# Display sizes of subdirectories sorted by size
du -sh "$folder_path"/* 2>/dev/null | sort -rh | head -20
echo ""
echo "Total size:"
du -sh "$folder_path"
System Info Collector
#!/bin/bash
output_file="system_info_$(hostname)_$(date +%Y%m%d).txt"
{
echo "System Information Report"
echo "Generated: $(date)"
echo "========================="
echo ""
echo "Hostname: $(hostname)"
echo "OS: $(uname -a)"
echo ""
echo "CPU Info:"
lscpu | grep -E "Model name|CPU\(s\)|Thread"
echo ""
echo "Memory:"
free -h
echo ""
echo "Disk Space:"
df -h
echo ""
echo "Network Interfaces:"
ip -br addr
echo ""
echo "Logged In Users:"
who
} > "$output_file"
echo "System info saved to $output_file"
Git Repository Updater
#!/bin/bash
git_repos=("/path/to/repo1" "/path/to/repo2")
for repo in "${git_repos[@]}"; do
if [ -d "$repo/.git" ]; then
echo "Updating repository: $repo"
cd "$repo"
git fetch --all
git pull origin "$(git branch --show-current)"
echo "Updated: $repo"
else
echo "Not a git repository: $repo"
fi
done
echo "All repositories updated."
Remote Script Execution
#!/bin/bash
remote_server="${1:-user@remote-server}"
remote_script="${2:-/path/to/remote/script.sh}"
# Execute a script on a remote server via SSH
ssh "$remote_server" "bash -s" < "$remote_script"
echo "Remote script executed on $remote_server"
| Pattern | Purpose |
|---|---|
#!/bin/bash | Shebang for bash |
$(date +%Y%m%d) | Date formatting |
$((expression)) | Arithmetic |
${var:-default} | Default value |
"$@" | All arguments |
| Command | Purpose |
|---|---|
chmod +x script.sh | Make executable |
./script.sh | Run script |
nohup ./script.sh & | Run in background |
crontab -e | Edit cron jobs |
source script.sh | Run in current shell |
Minute(0-59) Hour(0-23) Day(1-31) Month(1-12) Weekday(0-7, 0/7=Sun)
bash -x script.sh for debuggingWeekly Installs
–
Repository
GitHub Stars
27.4K
First Seen
–
Security Audits
Azure Data Explorer (Kusto) 查询技能:KQL数据分析、日志遥测与时间序列处理
107,900 周安装
LangChain4j AI 服务模式指南:Java声明式AI接口构建与内存管理
374 周安装
Coinw合约API技能:市场数据、交易下单、止盈止损、仓位查询、账户资产
AI提示词库大全:专家级ChatGPT提示词模板与角色扮演技巧
373 周安装
Slack Bot Builder 教程:使用 Bolt 框架和 Block Kit 构建 Slack 机器人
371 周安装
代码简化工具 - 自动优化代码可读性,保持行为不变 | AI辅助开发
370 周安装
AWS SDK Java 2.x S3 开发指南:存储桶操作、文件上传下载与Spring Boot集成
375 周安装