Essential Linux Command Scripts for Backup, Monitoring, and System Administration
This article compiles a comprehensive set of Linux command‑line tricks and ready‑to‑run Bash scripts covering zombie‑process detection, email and URL extraction, web page download, HTTP header checks, POST requests, traceroute, socket communication, directory and MySQL backups, ping sweeps, disk I/O diagnostics, performance monitoring, process management, Java heap dumps, bulk tool installation, common library setup, system health checks, and advanced sed usage, providing sysadmins with practical, copy‑and‑paste solutions for everyday tasks.
This guide gathers a large collection of useful Linux command‑line one‑liners and full Bash scripts that address common system‑administration needs such as monitoring, backup, performance analysis, and tool installation.
Useful one‑liners
# 查看僵尸进程
ps -al | gawk '{print $2,$4}' | grep Z # 匹配电子邮件地址
cat index.html | egrep -o "[A-Za-z0-9._]+@[A-Za-z0-9.]+\.[a-zA-Z]{2,4}" > ans.txt # 匹配 http URL
cat index.html | egrep -o "http://[A-Za-z0-9.]+\.[a-zA-Z]{2,3}" > ans.txt # 纯文本形式下载网页
lynx -dump www.baidu.com > plain.txt # 只打印 HTTP 头部信息
curl --head www.baidu.com # 使用 POST 提交数据
curl -d "param2=nickwolfe¶m2=12345" http://www.linuxidc.com/login.cgi # 显示分组途经的网关
traceroute www.baidu.com # 列出系统中的开放端口以及运行在端口上的服务
lsof -i # nc 命令建立 socket 连接
# 设置监听
nc -l 5555
# 连接到套接字
nc 192.0.0.1 5555 # 快速文件传输(发送/接收)
# 接收端
nc -l 5555 > destination_filename
# 发送端
nc 192.0.0.1 5555 < source_filename # 找出指定目录最大的 n 个文件
du -ak target_dir | sort -nrk 1 | head -n 4 # 向所有登录用户广播信息
cat message.txt | wall # 创建新的 screen 窗口
screen # 打印所有的 .txt 和 .pdf 文件
find . \( -name "*.txt" -o -name "*.pdf" \) -print # 将文件分割成多个 10KB 的块
split -b 10k data.file # 打印两个文件的交集
comm A.txt B.txt -3 | sed 's/^\t//' # sed 移除空白行
sed '/^$/d' fileMySQL Backup Script (mysql备份)
#!/bin/bash
set -e
USER="backup"
PASSWORD="backup"
DATA_DIR="/data/mysql"
BIN_INDEX=$DATA_DIR"/mysql-bin.index"
BACKUP_DIR="/data/backup/mysql"
BACKUP_LOG="/var/log/mysql/backup.log"
DATE=`date +"%Y%m%d"`
TIME=`date +"%Y%m%d%H"`
LOG_TIME=`date +"%Y-%m-%d %H:%M:%S"`
DELETE_BINLOG_TIME="7 day"
INCREMENT_INTERVAL="3 hour"
note() { printf "[${LOG_TIME}] note: $*
" >> $BACKUP_LOG; }
warning() { printf "[${LOG_TIME}] warning: $*
" >> $BACKUP_LOG; }
error() { printf "[${LOG_TIME}] error: $*
" >> $BACKUP_LOG; exit 1; }
full_backup() {
dbs=`ls -l $DATA_DIR | grep "^d" | awk -F " " '{print $9}'`
for db in $dbs; do
backup_dir=$BACKUP_DIR"/full/"$db
filename=$db"."$DATE
backup_file=$backup_dir"/"$filename".sql"
if [ ! -d $backup_dir ]; then
mkdir -p $backup_dir || { error "创建数据库 $db 全量备份目录 $backup_dir 失败"; continue; }
note "数据库 $db 全量备份目录 $backup_dir 不存在,创建完成";
fi
note "full backup $db start ..."
mysqldump --user=${USER} --password=${PASSWORD} --flush-logs --skip-lock-tables --quick $db > $backup_file || { warning "数据库 $db 备份失败"; continue; }
cd $backup_dir
tar -cPzf $filename".tar.gz" $filename".sql"
rm -f $backup_file
chown -fR mysql:mysql $backup_dir
note "数据库 $db 备份成功"
note "full backup $db end."
done
}
increment_backup() {
StartTime=`date "-d $INCREMENT_INTERVAL ago" +"%Y-%m-%d %H:%M:%S"`
DELETE_BINLOG_END_TIME=`date "-d $DELETE_BINLOG_TIME ago" +"%Y-%m-%d %H:%M:%S"`
dbs=`ls -l $DATA_DIR | grep "^d" | awk -F " " '{print $9}'`
mysql -u${USER} -p${PASSWORD} -e "purge master logs before '${DELETE_BINLOG_END_TIME}'" && note "delete $DELETE_BINLOG_TIME days before log"
filename=`cat $BIN_INDEX | awk -F "/" '{print $2}'`
for i in $filename; do
for db in $dbs; do
backup_dir=$BACKUP_DIR"/increment/"$db
filename=$db"."$TIME
backup_file=$backup_dir"/"$filename".sql"
if [ ! -d $backup_dir ]; then
mkdir -p $backup_dir || { error "创建数据库 $db 增量备份目录 $backup_dir 失败"; continue; }
note "数据库 $db 增量备份目录 $backup_dir 不存在,创建完成";
fi
note "increment backup $db from $StartTime start ..."
mysqlbinlog -d $db --start-datetime="${StartTime}" $DATA_DIR/$i >> $backup_file || { warning "数据库 $db 备份失败"; continue; }
note "increment backup $db end."
done
done
for db in $dbs; do
backup_dir=$BACKUP_DIR"/increment/"$db
filename=$db"."$TIME
backup_file=$backup_dir"/"$filename".sql"
cd $backup_dir
tar -cPzf $filename".tar.gz" $filename".sql"
rm -f $backup_file
note "数据库 $db 备份成功"
done
}
case "$1" in
full) full_backup ;;
increment) increment_backup ;;
*) exit 2 ;;
esac
exit 1Directory Backup Script (目录备份)
#!/bin/bash
DATE=$(date '+%Y-%m-%d_%H_%M_%S')
BACKUPDIR="/home/backups"
SORFILE=/opt
DESFILE=/home/backups/${SORFILE}.$(date '+%Y-%m-%d_%H_%M_%S').zip
[ ! -d $BACKUPDIR ] && mkdir -p $BACKUPDIR
cd $BACKUPDIR
echo "start backup $SORFILE ..."
sleep 3
zip -r $DESFILE $SORFILE &>/dev/null
if [ "$?" == "0" ]; then
echo "$(date +%Y-%m-%d) zip success" >>backup.log
else
echo "$(date +%Y-%m-%d) zip failed" >>backup.log
exit 0
fi
# 删除 3 天前的备份
find $BACKUPDIR -type f -ctime +3 | xargs rm -rfPing Sweep Script (PING查询)
#!/bin/bash
# 用于并行 ping 192.168.0.1‑255,检测活动主机
for ip in 192.168.0.{1..255}; do
(
ping $ip -c 2 &>/dev/null
if [ $? -eq 0 ]; then
echo "$ip is alive"
fi
) &
done
waitDisk I/O Check Commands (磁盘IO检查)
# iostat 查看磁盘活动统计
iostat
# 每 2 秒刷新 3 次
iostat 2 3
# 查看特定磁盘的 I/O 信息
iostat -d sda1
# 显示 CPU 信息
iostat -t
# 以 MB 为单位显示
iostat -m
# 查看 TPS、吞吐量等详细信息
iostat -d -k 1 1
# 查看设备使用率、响应时间
iostat -d -x -k 1 1
# 查看 CPU 状态
iostat -c 1 3
# 进程 I/O 信息
lsof
ls /proc/pid/fd
# 使用 sar 查看磁盘 I/O
sar -pd 10 3
# iotop 实时 I/O 监控
iotop
# slabtop 查看内核 slab 分配
slabtop -sc
# sysctl 查看系统参数
sysctl -aPerformance‑Related Commands (性能相关)
# 查看系统 load
uptime
# 查看系统状态和每个进程的资源使用
top
# 可视化 CPU 使用情况
htop
# 每 CPU 的负载信息
mpstat -P ALL 1
# 每秒刷新磁盘 I/O 统计
iostat -xkdz 1
# 每秒查看虚拟内存使用
vmstat 1
# 查看内存使用统计
free
# 查看网络使用信息
nicstat -z 1
# dstat 综合显示系统活动
dstat 1
# netstat 查看网络连接状态
netstat -s
# pidstat 查看进程资源使用
pidstat 1
pidstat -d 1
# strace 查看系统调用
strace -tttT -p 12670
# tcpdump 捕获网络数据包
tcpdump -nr /tmp/out.tcpdump
# btrace 查看块设备读写事件
btrace /dev/sdb
# iotop 查看进程 I/O
iotop -bod5
# slabtop 查看内核 slab
slabtop -sc
# sysctl 查看系统参数
sysctl -a
# perf 统计 CPU 活动
perf stat gzip file1
perf record -a -g -F 997 sleep 10Process‑Related Commands (进程相关)
# 查看当前线程列表
ps
ps aux
ps -f -u www-data
ps -C apache2
ps aux --sort=-pcpu | head -5
ps -f --forest -C apache2
ps -o pid,uname,comm -C apache2
ps --ppid 2359
ps -p 3150 -L
ps -e -o pid,comm,etime
watch -n 1 'ps -e -o pid,uname,cmd,pmem,pcpu --sort=-pmem,-pcpu | head -15'
# 杀死进程
kill 12
kill -2 123 # 相当于 Ctrl+C
kill -9 123 # 强制终止
kill -l # 列出所有信号
kill -l KILL # 查看 KILL 的数值
# 前台/后台切换
fg 123
bg 123
# nohup 让进程在退出终端后继续运行
nohup command > myout.file 2>&1 &
# at 计划一次性任务
at 12:00
# 查看计划任务列表
atq
# 删除计划任务
atrm 1
# pstree 查看进程树
pstree
# nice 改变进程优先级
nice -n 5 ls
# renice 动态修改优先级
renice -5 -p 5200
# pmap 查看进程内存映射
pmap 20367Java Dump Script (javadump.sh)
#!/bin/sh
DUMP_PIDS=`ps --no-heading -C java -f --width 1000 | awk '{print $2}'`
if [ -z "$DUMP_PIDS" ]; then
echo "The server $HOST_NAME is not started!"
exit 1;
fi
DUMP_ROOT=~/dump
[ ! -d $DUMP_ROOT ] && mkdir -p $DUMP_ROOT
DUMP_DATE=`date +%Y%m%d%H%M%S`
DUMP_DIR=$DUMP_ROOT/dump-$DUMP_DATE
[ ! -d $DUMP_DIR ] && mkdir $DUMP_DIR
for PID in $DUMP_PIDS ; do
$JAVA_HOME/bin/jstack $PID > $DUMP_DIR/jstack-$PID.dump 2>&1
echo -e ".\c"
$JAVA_HOME/bin/jinfo $PID > $DUMP_DIR/jinfo-$PID.dump 2>&1
echo -e ".\c"
$JAVA_HOME/bin/jstat -gcutil $PID > $DUMP_DIR/jstat-gcutil-$PID.dump 2>&1
echo -e ".\c"
$JAVA_HOME/bin/jstat -gccapacity $PID > $DUMP_DIR/jstat-gccapacity-$PID.dump 2>&1
echo -e ".\c"
$JAVA_HOME/bin/jmap $PID > $DUMP_DIR/jmap-$PID.dump 2>&1
echo -e ".\c"
$JAVA_HOME/bin/jmap -heap $PID > $DUMP_DIR/jmap-heap-$PID.dump 2>&1
echo -e ".\c"
$JAVA_HOME/bin/jmap -dump:format=b,file=$DUMP_DIR/jmap-dump-$PID.dump $PID 2>&1
echo -e ".\c"
if [ -r /usr/sbin/lsof ]; then
/usr/sbin/lsof -p $PID > $DUMP_DIR/lsof-$PID.dump
echo -e ".\c"
fi
done
if [ -r /usr/bin/sar ]; then
/usr/bin/sar > $DUMP_DIR/sar.dump
echo -e ".\c"
fi
if [ -r /usr/bin/uptime ]; then
/usr/bin/uptime > $DUMP_DIR/uptime.dump
echo -e ".\c"
fi
if [ -r /usr/bin/free ]; then
/usr/bin/free -t > $DUMP_DIR/free.dump
echo -e ".\c"
fi
if [ -r /usr/bin/vmstat ]; then
/usr/bin/vmstat > $DUMP_DIR/vmstat.dump
echo -e ".\c"
fi
if [ -r /usr/bin/mpstat ]; then
/usr/bin/mpstat > $DUMP_DIR/mpstat.dump
echo -e ".\c"
fi
if [ -r /usr/bin/iostat ]; then
/usr/bin/iostat > $DUMP_DIR/iostat.dump
echo -e ".\c"
fi
if [ -r /bin/netstat ]; then
/bin/netstat > $DUMP_DIR/netstat.dump
echo -e ".\c"
fi
echo "OK!"Common Tools Installation Script (常用工具安装)
#!/usr/bin/env bash
# 安装常用命令工具
printf "
\033[1;34m>>> 安装常用命令工具开始\033[0m
"
# 核心工具
printf "
\033[1;36m>>> install coreutils(df、du)\033[0m
"
yum install -y coreutils
printf "
\033[1;36m>>> install chkconfig\033[0m
"
yum install -y chkconfig
# 网络工具
printf "
\033[1;36m>>> install net-tools(ifconfig、netstat、route)\033[0m
"
yum install -y net-tools
printf "
\033[1;36m>>> install iptables\033[0m
"
yum install -y iptables
# IP 工具
printf "
\033[1;36m>>> install iputils(ping、tracepath)\033[0m
"
yum install -y iputils
printf "
\033[1;36m>>> install traceroute\033[0m
"
yum install -y traceroute
printf "
\033[1;36m>>> install iproute(ip、ss)\033[0m
"
yum install -y iproute
# 端口工具
printf "
\033[1;36m>>> install lsof\033[0m
"
yum install -y lsof
printf "
\033[1;36m>>> install nc\033[0m
"
yum install -y nc
printf "
\033[1;36m>>> install netstat\033[0m
"
yum install -y netstat
# DNS 工具
printf "
\033[1;36m>>> install bind-utils(dig、host、nslookup)\033[0m
"
yum install -y bind-utils
printf "
\033[1;36m>>> install whois\033[0m
"
yum install -y whois
# 下载工具
printf "
\033[1;36m>>> install curl\033[0m
"
yum install -y curl
printf "
\033[1;36m>>> install wget\033[0m
"
yum install -y wget
# 编辑工具
printf "
\033[1;36m>>> install emacs\033[0m
"
yum install -y emacs
printf "
\033[1;36m>>> install vim\033[0m
"
yum install -y vim
# 流量工具
printf "
\033[1;36m>>> install iftop\033[0m
"
yum install -y iftop
printf "
\033[1;36m>>> install nethogs\033[0m
"
yum install -y nethogs
# 抓包工具
printf "
\033[1;36m>>> install tcpdump\033[0m
"
yum install -y tcpdump
# 压缩工具
printf "
\033[1;36m>>> install unzip\033[0m
"
yum install -y unzip
# 版本控制工具
printf "
\033[1;36m>>> install git\033[0m
"
yum install -y git
printf "
\033[1;36m>>> install subversion\033[0m
"
yum install -y subversion
printf "
\033[1;32m<<< 安装常用命令工具结束\033[0m
"Common Libraries Installation Script (常用lib库安装)
#!/usr/bin/env bash
printf "
\033[1;34m>>> 安装常见 lib 开始\033[0m
"
# gcc、kernel-devel、libtool
yum -y install make gcc gcc-c++ kernel-devel libtool
printf "
\033[1;36m>>> install openssl openssl-devel\033[0m
"
yum -y install make openssl openssl-devel
printf "
\033[1;36m>>> install zlib zlib-devel\033[0m
"
yum -y install make zlib zlib-devel
printf "
\033[1;36m>>> install pcre\033[0m
"
yum -y install pcre
printf "
\033[1;32m<<< 安装常见 lib 结束\033[0m
"System Information Check Script (系统检查脚本)
#!/usr/bin/env bash
C_RESET="$(tput sgr0)"
C_BLACK="\033[1;30m"
C_RED="\033[1;31m"
C_GREEN="\033[1;32m"
C_YELLOW="\033[1;33m"
C_BLUE="\033[1;34m"
C_PURPLE="\033[1;35m"
C_CYAN="\033[1;36m"
C_WHITE="\033[1;37m"
printf "${C_PURPLE}"
cat << EOF
###################################################################################
# 系统信息检查脚本
###################################################################################
EOF
printf "${C_RESET}"
[[ $(id -u) -gt 0 ]] && echo "请用root用户执行此脚本!" && exit 1
sysversion=$(rpm -q centos-release | cut -d- -f3)
double_line="==============================================================="
line="----------------------------------------------"
printHeadInfo() {
cat << EOF
+---------------------------------------------------------------------------------+
| 欢迎使用 【系统信息检查脚本】 |
+---------------------------------------------------------------------------------+
EOF
}
printFootInfo() {
cat << EOF
+---------------------------------------------------------------------------------+
| 脚本执行结束,感谢使用!|
+---------------------------------------------------------------------------------+
EOF
}
options=("获取系统信息" "获取服务信息" "获取CPU信息" "获取系统网络信息" "获取系统内存信息" "获取系统磁盘信息" "获取CPU/内存占用TOP10" "获取系统用户信息" "输出所有信息" "退出")
printMenu() {
printf "${C_BLUE}"
printf "主菜单:
"
for i in "${!options[@]}"; do
index=$((i+1))
printf "\t(%02d) %-30s" $index "${options[$i]}"
(( index % 2 == 0 )) && printf "
"
done
printf "
${C_BLUE}请输入需要执行的指令:
"
printf "${C_RESET}"
}
get_systatus_info() {
sys_os=$(uname -o)
sys_release=$(cat /etc/redhat-release)
sys_kernel=$(uname -r)
sys_hostname=$(hostname)
sys_selinux=$(getenforce)
sys_lang=$LANG
sys_lastreboot=$(who -b | awk '{print $3,$4}')
sys_runtime=$(uptime | awk '{print $3,$4}' | cut -d, -f1)
sys_time=$(date)
sys_load=$(uptime | cut -d: -f5)
cat << EOF
【系统信息】
系统: $sys_os
发行版本: $sys_release
系统内核: $sys_kernel
主机名: $sys_hostname
selinux状态: $sys_selinux
系统语言: $sys_lang
系统当前时间: $sys_time
系统最后重启时间: $sys_lastreboot
系统运行时间: $sys_runtime
系统负载: $sys_load
EOF
}
# (Other functions omitted for brevity – they follow the same pattern as in the source)
printHeadInfo
main
printFootInfo
printf "${C_RESET}"Advanced sed Examples (sed进阶)
#!/bin/bash
# 多个空格只保留一个
# sed '/./,/^$/!d' test
# 删除开头的空白行
# sed '/./,$!d' test
# 删除结尾的空白行
sed '{
:start
/^
*$/{$d; N; b start}
}' test
# 删除 html 标签(示例)
# sed 's/<[^>]*>//g' test1
# 替换并保留匹配内容
echo "The cat sleeps in his hat" | sed 's/.at/"&"/g'
# 替换单独的单词
echo "The System Administrator manual" | sed 's/\(System\) Administrator/\1 user/'
# 在长数字中插入逗号
echo "1234567" | sed '{:start; s/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/; t start}'
# 给文件中的行编号
sed '=' test | sed 'N; s/
/ /'All the snippets above can be copied directly into a terminal or saved as .sh files to provide quick, reusable solutions for routine Linux system administration tasks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
