1. 获取IP地址
#/bin/bash
ipAddr=$(ip addr show | grep inet | grep -v inet6 | grep '/24' | awk '{print $2}' | awk -F '/' '{print $1}')
echo "网卡IP地址:${ipAddr}"
2. 检测某域名、IP地址是否通
#!/bin/bash
targetAddr=$1
if [ $1 ] && ( ping -c 2 ${targetAddr} &>/dev/null ); then
echo "${targetAddr}通"
else
echo '目标地址空或者目标地址访问不通,请检查'
fi
3. 防火墙开闭端口、查看端口开闭状态、所有对外开放的端口
#!/bin/bash
# 开启端口
openPort () {
if [ ! $1 ]; then
echo '请输入需要开启的端口,请检查'
exit 1
fi
portStatus=$(firewall-cmd --query-port="$1"/tcp)
if [ $portStatus = 'no' ]; then
sudo firewall-cmd --add-port=$1/tcp --permanent
firewall-cmd --reload
sleep 1s
echo "端口【$1】已成功开启"
else
echo "端口【$1】已开启,无需重复开启"
fi
}
# 关闭端口
closePort () {
if [ ! $1 ]; then
echo "请输入需要关闭的端口,请检查"
exit 1
fi
portStatus=$(firewall-cmd --query-port="$1"/tcp)
if [ $portStatus = 'yes' ]; then
firewall-cmd --permanent --remove-port=$1/tcp
firewall-cmd --reload
sleep 1s
echo "端口【$1】已成功关闭"
else
echo "端口【$1】已关闭,无需重复关闭"
fi
}
# 查看端口是否开启关闭
checkPort () {
if [ ! $1 ]; then
echo '请输入需要检查的端口,请检查'
exit 1
fi
portStatus=$(firewall-cmd --query-port="$1"/tcp)
echo "端口【$1】状态:$portStatus"
}
# 查看系统中开放的端口
listPort () {
openPortInfo=$( firewall-cmd --list-all | grep ports | awk 'NR==1{for(i=2;i<=NF;i++) print $i}' | sort -nk 1 -t '/')
echo "系统中对外开启的端口"
echo "$openPortInfo"
}
case $1 in
open)
openPort $2
;;
close)
closePort $2
;;
check|status)
checkPort $2
;;
list)
listPort
;;
*)
echo '参数错误:请输入第一个参数open|close|check|status|list 中的任何一个、第二个参数【可选】端口号'
esac
sh firewallUtil.sh open 端口号
sh firewallUtil.sh close 端口号
sh firewallUtil.sh check 端口号
sh firewallUtil.sh list
4. Nginx安装脚本
#!/bin/bash
# 检查是否是root用户,不是则退出程序;检查是否有wget应用,没有则帮其装上
# 如果已经安装且启动的,想重新安装,自行手动杀死后台的Nginx进程
check () {
test $USER == 'root' || (echo '必须是root用户,请检查' ; exit 1)
[ -e /usr/bin/wget ] || yum -y install wget &>/dev/null
}
# 依赖安装
install_dependencies () {
if ! ( yum -y install elinks gcc-* pcre-devel zlib-devel 1>/dev/null ); then
echo "nginx相关的依赖安装失败,请检查"
exit 1
fi
}
# 变量分别是
# nginx_home:下载目录[别将其设为根目录,会导致删掉整个Linux,后果自负]
# nginx_install_home:安装目录[别将其设为根目录,会导致删掉整个Linux,后果自负]
# nginx_version:Nginx版本号
nginx_home=/usr/nginx
nginx_install_home=/usr/nginx/nginx
nginx_version=nginx-1.20.0.tar.gz
# 下载、解压nginx
download_nginx () {
if [ ! -d ${nginx_home} ]; then
mkdir -p ${nginx_home}
fi
cd $nginx_home
rm -rf *
# if ! $(find / -name $nginx_version | grep ${nginx_home}'/'$nginx_version); then
rm -rf ${nginx_version}
wget "http://nginx.org/download/${nginx_version}" || (echo "nginx安装包下载失败, 请检查" ; exit 1)
# fi
tar -xvf ${nginx_version} 1>/dev/null || echo " ${nginx_version}解压失败"
}
# 安装nginx
install_nginx () {
cd $(echo $nginx_version | cut -d '.' -f1-3)
rm -rf ${nginx_install_home}
if ./configure --prefix=${nginx_install_home} 1>/dev/null; then
echo "Nginx: 配置成功"
if make 1>/dev/null; then
echo "Nginx: 编译成功"
if make install 1>/dev/null; then
echo "Nginx: 编译后安装成功"
else
echo "Nginx: 编译后安装失败"
make clean
exit 1
fi
else
echo "Nginx: 编译失败"
make clean
exit 1
fi
else
echo "Nginx: 配置失败"
exit 1
fi
}
# 启动nginx
test_nginx () {
if $nginx_install_home/sbin/nginx ; then
# 将nginx设为全局命令
ln -s $nginx_install_home/sbin/nginx /usr/bin/nginx
echo "Nginx: 启动成功"
# 访问80端口,查看是否是nginx页面
elinks http://localhost -dump
nginx -v
else
echo "Nginx: 启动失败"
fi
}
# 开放服务器防火墙80端口给外界
open_firewalld_80 () {
# 查看Linux防火墙是否开启,开启则开放80端口,否则不做处理
if firewall-cmd --state | grep 'running' ; then
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --reload
echo '80端口已经开启,可通过浏览器进行访问服务器80端口'
fi
}
# 调用上述函数, 开始执行Nginx安装流程
check
install_dependencies
download_nginx
install_nginx
test_nginx
open_firewalld_80
5. 监控磁盘IO
"
运行前安装iostat:yum -y install sysstat
"
#!/bin/bash
startIoStat () {
echo "IO设备名 平均每秒写的数据量【KB】 平均每次IO请求等待的时间【毫秒】"
# 每秒打印5次 iostat -x报告
# 抓取vdx设备的数据
iostat -x 1 5 | egrep '^vd[a-z]' | awk '{io_writeDataInfo[$1]+=$7;io_waitDataInfo[$1]+=$10;print $1,$7,$10}END{print "平均结果";for (elem in io_writeDataInfo ) print elem, io_writeDataInfo[elem]/5, io_waitDataInfo[elem]/5; print "=================" }'
}
case $1 in
one)
startIoStat
;;
iterator)
while [ true ]; do
startIoStat
sleep 5
done
;;
*)
startIoStat
;;
esac
6. 监控本机内存使用率
#!/bin/bash
totalMemory=$( head -9 /proc/meminfo | awk 'NR==1{print $2}')
usedMemory=$( head -9 /proc/meminfo | awk 'NR==9{print $2}')
freeMemory=$( head -9 /proc/meminfo | awk 'NR==2{print $2}')
cachedMemory=$( head -9 /proc/meminfo | awk 'NR==4{buffers=$2}NR==5{print buffers+$2}')
echo -e "usedMemoryRate: $(($usedMemory * 100 / $totalMemory)) %"
echo -e "cachedMemoryRate: $(($cachedMemory * 100 / $totalMemory)) %"
echo -e "freeMemoryRate: $(($freeMemory * 100 / $totalMemory)) %"
7. Dos攻击防范 ,收藏起来(自动屏蔽攻击 IP)
#!/bin/bash
DATE=$(date +%d/%b/%Y:%H:%M)
LOG_FILE=/usr/local/nginx/logs/demo2.access.log
ABNORMAL_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; do
if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
iptables -I INPUT -s $IP -j DROP
echo "$(date +'%F_%T') $IP" >> /tmp/drop_ip.log
fi
done
8. 系统发送告警脚本
# yum install mailx
# vi /etc/mail.rc
set from=baojingtongzhi@163.com smtp=smtp.163.com
set smtp-auth-user=baojingtongzhi@163.com smtp-auth-password=123456
set smtp-auth=login
9. MySQL 数据库备份单循环
#!/bin/bash
DATE=$(date +%F_%H-%M-%S)
HOST=localhost
USER=backup
PASS=123.com
BACKUP_DIR=/data/db_backup
DB_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}.sql
if ! mysqldump -h$HOST -u$USER -p$PASS -B $DB > $BACKUP_NAME 2>/dev/null; then
echo "$BACKUP_NAME 备份失败!"
fi
done
10. MySQL 数据库备份多循环
#!/bin/bash
DATE=$(date +%F_%H-%M-%S)
HOST=localhost
USER=backup
PASS=123.com
BACKUP_DIR=/data/db_backup
DB_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}.sql
if ! mysqldump -h$HOST -u$USER -p$PASS $DB $TABLE > $BACKUP_NAME 2>/dev/null; then
echo "$BACKUP_NAME 备份失败!"
fi
done
done
11. Nginx 访问访问日志按天切割
#!/bin/bash
LOG_DIR=/usr/local/nginx/logs
YESTERDAY_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}
done
kill -USR1 $(cat /var/run/nginx.pid)
12. 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=$1
echo "统计访问最多的10个IP"
awk '{a[$1]++}END{print "UV:",length(a);for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr |head -10
echo "----------------------"
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 -10
echo "----------------------"
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 -nr
echo "----------------------"
echo "统计访问页面状态码数量"
awk '{a[$7" "$9]++}END{for(v in a){if(a[v]>5)print v,a[v]}}'
13. 查看网卡实时流量脚本
#!/bin/bash
NIC=$1
echo -e " In ------ Out"
while true; do
OLD_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
OLD_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
sleep 1
NEW_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
NEW_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
IN=$(printf "%.1f%s" "$((($NEW_IN-$OLD_IN)/1024))" "KB/s")
OUT=$(printf "%.1f%s" "$((($NEW_OUT-$OLD_OUT)/1024))" "KB/s")
echo "$IN $OUT"
sleep 1
done
14. 服务器系统配置初始化脚本
#/bin/bash
# 设置时区并同步时间
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
if ! crontab -l |grep ntpdate &>/dev/null ; then
(echo "* 1 * * * ntpdate time.windows.com >/dev/null 2>&1";crontab -l) |crontab
fi
# 禁用selinux
sed -i '/SELINUX/{s/permissive/disabled/}' /etc/selinux/config
# 关闭防火墙
if egrep "7.[0-9]" /etc/redhat-release &>/dev/null; then
systemctl stop firewalld
systemctl disable firewalld
elif egrep "6.[0-9]" /etc/redhat-release &>/dev/null; then
service iptables stop
chkconfig iptables off
fi
# 历史命令显示操作时间
if ! grep HISTTIMEFORMAT /etc/bashrc; then
echo 'export HISTTIMEFORMAT="%F %T `whoami` "' >> /etc/bashrc
fi
# SSH超时时间
if ! grep "TMOUT=600" /etc/profile &>/dev/null; then
echo "export TMOUT=600" >> /etc/profile
fi
# 禁止root远程登录
sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
# 禁止定时任务向发送邮件
sed -i 's/^MAILTO=root/MAILTO=""/' /etc/crontab
# 设置最大打开文件数
if ! grep "* soft nofile 65535" /etc/security/limits.conf &>/dev/null; then
cat >> /etc/security/limits.conf << EOF
* soft nofile 65535
* hard nofile 65535
EOF
fi
# 系统内核优化
cat >> /etc/sysctl.conf << EOF
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_tw_buckets = 20480
net.ipv4.tcp_max_syn_backlog = 20480
net.core.netdev_max_backlog = 262144
net.ipv4.tcp_fin_timeout = 20
EOF
# 减少SWAP使用
echo "0" > /proc/sys/vm/swappiness
# 安装系统性能分析工具及其他
yum install gcc make autoconf vim sysstat net-tools iostat if
15. 监控 100 台服务器磁盘利用率脚本
#!/bin/bash
HOST_INFO=host.info
for IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); do
USER=$(awk -v ip=$IP 'ip==$1{print $2}' $HOST_INFO)
PORT=$(awk -v ip=$IP 'ip==$1{print $3}' $HOST_INFO)
TMP_FILE=/tmp/disk.tmp
ssh -p $PORT $USER@$IP 'df -h' > $TMP_FILE
USE_RATE_LIST=$(awk 'BEGIN{OFS="="}/^\/dev/{print $NF,int($5)}' $TMP_FILE)
for USE_RATE in $USE_RATE_LIST; do
PART_NAME=${USE_RATE%=*}
USE_RATE=${USE_RATE#*=}
if [ $USE_RATE -ge 80 ]; then
echo "Warning: $PART_NAME Partition usage $USE_RATE%!"
fi
done
done
标签:shell,dev,echo,学习,nginx,awk,print,fi
From: https://www.cnblogs.com/hm201402/p/17057631.html