1. 监控服务器内存使用情况
#!/bin/bashMEM_TOTAL=$(free -m | awk '/Mem:/ {print $2}')MEM_USED=$(free -m | awk '/Mem:/ {print $3}')MEM_PERCENT=$(echo"scale=2; ($MEM_USED / $MEM_TOTAL) * 100" | bc)echo"内存总容量: $MEM_TOTAL MB"echo"已使用内存: $MEM_USED MB"echo"内存使用率: $MEM_PERCENT%"
2. 检查指定服务是否正在运行
#!/bin/bashSERVICE_NAME="httpd"if systemctl is-active --quiet $SERVICE_NAME; thenecho"$SERVICE_NAME 服务正在运行"elseecho"$SERVICE_NAME 服务未运行"fi
3. 批量创建用户
#!/bin/bashUSERS=("user1""user2""user3")for USER in"${USERS[@]}"do useradd $USERecho"密码: 123456" | passwd $USER --stdindone
4. 清理过期的日志文件
#!/bin/bashLOG_DIR="/var/log"DAYS_TO_KEEP=7find $LOG_DIR -type f -mtime +$DAYS_TO_KEEP -delete
5. 监控磁盘空间使用情况
#!/bin/bashdf -h
6. 自动备份数据库
#!/bin/bashDB_NAME="mydatabase"USER="username"PASSWORD="password"mysqldump -u $USER -p$PASSWORD$DB_NAME > /backup/$DB_NAME-$(date +%Y%m%d).sql
7. 检测网络连接是否正常
#!/bin/bashURL="www.example.com"curl -I $URL > /dev/null 2>&1if [ $? -eq 0 ]; thenecho"网络连接正常"elseecho"网络连接异常"fi
8. 重启特定服务
#!/bin/bashSERVICE="nginx"systemctl restart $SERVICE
9. 监控进程是否存在
#!/bin/bashPROCESS="myprocess"if pgrep -f $PROCESS > /dev/null; thenecho"$PROCESS 进程正在运行"elseecho"$PROCESS 进程未运行"fi
10. 统计文件行数
#!/bin/bashFILE="myfile.txt"LINE_COUNT=$(wc -l < $FILE)echo"文件 $FILE 行数: $LINE_COUNT"
以下是一些 Linux 运维中可能会用到的 shell 脚本示例:
#!/bin/bashdate=$(date +%d/%b/%y:%h:%m)log_file=/usr/local/nginx/logs/demo2.access.logabnormal_ip=$(tail -n5000 $log_file | grep $date | awk '{a[$1]++} END {for (i in a) if (a[i] > 10) print i}')for ip in$abnormal_ip; doif ($(iptables -vnL | grep -c "$ip") -eq 0); then iptables -I INPUT -s $ip -j DROPecho"$(date +'%f_%t')$ip" >> /tmp/drop_ip.logfidone
该脚本会分析 Nginx 访问日志,找出在一段时间内请求过于频繁的 IP 地址,并使用 IPTables 自动屏蔽这些 IP。
首先需要安装 mailx,并配置 /etc/mail.rc 文件,设置发件人信息,例如:
set from=baojingtongzhi@163.com smtp=smtp.163.comset smtp-auth-user=baojingtongzhi@163.com smtp-auth-password=123456set smtp-auth=login
然后可以使用以下脚本来发送告警邮件:
#!/bin/bashsubject="告警信息"message="这是一封测试告警邮件"recipient="接收告警的邮箱地址"echo"$message" | mail -s "$subject""$recipient"
#!/bin/bashdate=$(date +%f_%h-%m-%s)host=localhostuser=backuppass=123.combackup_dir=/data/db_backupdb_list=$(mysql -h $host -u $user -p$pass -s -e "show databases;" 2>/dev/null | egrep -v "database|information_schema|mysql|performance_schema|sys")for db in$db_list; do backup_name=$backup_dir/${db}_${date}.sqlif [! -f $backup_name ]; then mysqldump -h $host -u $user -p$pass -b $db > $backup_name 2>/dev/nullif [ $? -ne 0 ]; thenecho"$backup_name 备份失败!"fifidone
此脚本会对指定的 MySQL 数据库进行备份,每个数据库备份为一个单独的 SQL 文件。
#!/bin/bashdate=$(date +%f_%h-%m-%s)host=localhostuser=backuppass=123.combackup_dir=/data/db_backupdb_list=$(mysql -h $host -u $user -p$pass -s -e "show databases;" 2>/dev/null | egrep -v "database|information_schema|mysql|performance_schema|sys")for db in$db_list; do backup_db_dir=$backup_dir/${db}_${date} (! -d $backup_db_dir) && mkdir -p $backup_db_dir &>/dev/null table_list=$(mysql -h $host -u $user -p$pass -s -e "use $db; show tables;" 2>/dev/null)for table in$table_list; do backup_name=$backup_db_dir/${table}.sqlif [! -f $backup_name ]; then mysqldump -h $host -u $user -p$pass$db$table > $backup_name 2>/dev/nullif [ $? -ne 0 ]; thenecho"$backup_name 备份失败!"fifidonedone
这个脚本会为每个数据库创建一个对应的目录,然后将数据库中的每个表分别备份为一个 SQL 文件。
#!/bin/bashlog_dir=/usr/local/nginx/logsyesterday_time=$(date -d "yesterday" +%f)log_month_dir=$log_dir/$(date +"%y-%m")log_file_list="default.access.log"for log_file in$log_file_list; do (! -d $log_month_dir) && mkdir -p $log_month_dir mv $log_dir/$log_file$log_month_dir/${log_file}_${yesterday_time}donekill -USR1 $(cat /var/run/nginx.pid)
该脚本用于将 Nginx 访问日志按天进行切割,方便后续的分析和管理。
#!/bin/bash# 日志格式:$remote_addr - $remote_user ($time_local) "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"log_file=$1echo"统计访问最多的 10 个 IP"awk '{a[$1]++} END {print "uv:", length(a); for (v in a) print v, a(v)}'$log_file | sort -k2 -nr | head -10echo"----------------------"echo"统计时间段访问最多的 IP"awk '$4>="(01/dec/2018:13:20:25" && $4<="(27/nov/2018:16:20:49" {a[$1]++} END {for (v in a) print v, a(v)}'$log_file | sort -k2 -nr | head -10echo"----------------------"echo"统计访问最多的 10 个页面"awk '{a[$7]++} END {print "pv:", length(a); for (v in a) {if (a[v] > 10) print v, a(v)}}'$log_file | sort -k2 -nrecho"----------------------"echo"统计访问页面状态码数量"awk '{a[$7""$9]++} END {for (v in a) {if (a[v] > 5) print v, a(v)}}'
此脚本可以对 Nginx 访问日志进行各种分析,例如统计访问最多的 IP、页面以及页面状态码数量等。
eth0=$1echo -e "流量进入 -- 流量传出"whiletrue; do old_in=$(cat /proc/net/dev | grep $eth0 | awk '{print $2}') old_out=$(cat /proc/net/dev | grep $eth0 | awk '{print $10}') sleep 1 new_in=$(cat /proc/net/dev | grep $eth0 | awk '{print $2}') new_out=$(cat /proc/net/dev | grep $eth0 | awk '{print $10}') in_speed=$((new_in - old_in)) out_speed=$((new_out - old_out))echo"$in_speed -- $out_speed"done
运行该脚本时需指定网卡名称(如 eth0),它会实时显示该网卡的流入和流出流量。
#!/bin/bash# 安装系统性能分析工具及其他yum install gcc make autoconf vim sysstat net-tools iostat iftop iotop wget lrzsz lsof unzip openssh-clients net-tool vim ntpdate -y# 设置时区并同步时间ln -s /usr/share/zoneinfo/asia/shanghai /etc/localtimeif [! crontab -l | grep ntpdate &> /dev/null ]; then (echo"* 1 * * * ntpdate time.windows.com > /dev/null 2>&1"; crontab -l) | crontabfi# 禁用 SELinuxsed -i '/selinux/{s/permissive/disabled/}' /etc/selinux/config# 关闭防火墙if egrep "7.(0-9)" /etc/redhat-release &> /dev/null; then systemctl stop firewalld systemctl disable firewalldelif egrep "6.(0-9)" /etc/redhat-release &> /dev/null; then service iptables stop chkconfig iptables offfi# 历史命令显示操作时间if [! grep histtimeformat /etc/bashrc ]; thenecho'export HISTTIMEFORMAT="%y-%m-%d %h:%m:%s `whoami` "' >> /etc/bashrcfi# SSH 超时时间if [! grep "tmout=600" /etc/profile &> /dev/null ]; thenecho"export TMOUT=600" >>