shell常用脚本经典案例-2
1 批量解压 使用for循环实现
模板一
for tar_file in *.tar; do
if [ -f "$tar_file " ] ; then
tar -xvf "$tar_file " && echo "解压 $tar_file 成功."
fi
done
for zip_file in *.zip; do
if [ -f "$zip_file " ] ; then
unzip "$zip_file " && echo "解压 $zip_file 成功."
fi
done
for tar_gz_file in *.tar.gz; do
if [ -f "$tar_gz_file " ] ; then
tar -xzvf "$tar_gz_file " && echo "解压 $tar_gz_file 成功."
fi
done
echo "批量解压完成."
模板二
select ACTION in \
"1. 批量解压tar.gz文件" \
"2. 批量解压.zip和war文件" \
"3. 批量删除压缩文件" \
"4. 批量打包(未实现)" \
"5. 退出脚本" ; do
case $ACTION in
"1. 批量解压tar.gz文件" )
echo "批量解压tar.gz文件..."
find . -type f -name "*.tar.gz" -exec tar -xzvf { } \ ;
break
; ;
"2. 批量解压.zip和war文件" )
echo "批量解压.zip和war文件..."
find . -type f \ ( -name "*.zip" -o -name "*.war" \ ) -exec unzip { } \ ;
break
; ;
"3. 批量删除压缩文件" )
echo "批量删除压缩文件..."
read -p "警告:您将删除当前目录下的所有.tar.gz, .zip和.war文件,是否继续? (yes/no): " confirm
if [ [ "$confirm " == "yes" ] ] ; then
find . -type f \ ( -name "*.tar.gz" -o -name "*.zip" -o -name "*.war" \ ) -delete
fi
break
; ;
"4. 批量打包(未实现)" )
echo "抱歉,批量打包功能尚未实现。"
break
; ;
"5. 退出脚本" )
echo "退出脚本..."
exit 0
; ;
*) echo "无效的选择,请重新选择。" ; ;
esac
done
2 公司的nginx日志太大 做一个日志切割,每天生成一个日志
模板1
LOG_DIR = /usr/local/nginx/logs/
YESTERDAY_TIME = $( date -d "yesterday" +%F)
LOG_MONTH_DIR = $LOG_DIR /$( date +"%Y-%m" )
LOG_FILE_LIST = "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 /usr/local/nginx/logs/nginx.pid)
此脚本每天将nginx昨日的access.log移到按年月分的目录,并重命名,然后让nginx重新打开日志文件。流程如下:
1 . 设置日志路径变量,昨日前缀名。
2 . 循环处理access.log,创建昨月目录(如无)。
3 . 移动access.log到昨月目录,并添加日期后缀。
4 . 向nginx主进程发USR1信号,令其刷新日志文件。
模板2
nmkdir -p /usr/local/nginx/logs/date( 为了存放切分日志文件的)
LOGS_PATH = /usr/local/nginx/logs/
YESTERDAY = $( date -d "yesterday" +%Y-%m-%d)
KEEPTIME = $( date -d "-30 days" +%Y-%m-%d)
mv ${LOGS_PATH} /access.log ${LOGS_PATH} /date/access_${YESTERDAY} .log
mv ${LOGS_PATH} /error.log ${LOGS_PATH} /date/error_${YESTERDAY} .log
kill -USR1 $( cat /usr/local/nginx/logs/nginx.pid)
rm -f ${LOGS_PATH} /date/access_{ KEEPTIME} .log
rm -f ${LOGS_PATH} /date/error_{ KEEPTIME} .log
此脚本每日自动整理nginx日志:
1 . 获取昨天和30天前日期。
2 . 将昨日access和error日志移动到/logs/date目录并重命名(加日期)。
3 . 发送信号给nginx,使其重新打开日志文件。
4 . 删除30天前的日志文件。
crontab -e
1 0 0 * * * sh /usr/local/nginx/logs/cut_nginx_log.sh
( 使定时任务每天0点执行,将前一天的access.log和error.log文件改为带昨日日期时间戳的log文件,然后重载配置文件,生成新的access.log,error.log存储新一天的记录)
crontab -l
3 写一个脚本 实现判断 192.168.10.0/24 网络里 当前在线ip,能ping通 就是在线 ping不通 则打印 报警
#!/bin/bash
for ip in $( seq 1 254 ) ; do
address = "192.168.10.$ip "
ping -c 1 -W 1 $address > /dev/null 2 >&1
if [ $? -eq 0 ] ; then
echo "$address 在线"
else
echo "$address 不在线 (报警)"
fi
done
效果
[ root@centos7mage logs]
10.0 .1.1 在线
10.0 .1.2 在线
10.0 .1.3 不在线 ( 报警)
10.0 .1.4 不在线 ( 报警)
10.0 .1.5 不在线 ( 报警)
10.0 .1.6 不在线 ( 报警)
10.0 .1.7 不在线 ( 报警)
10.0 .1.8 不在线 ( 报警)
10.0 .1.9 不在线 ( 报警)
10.0 .1.10 不在线 ( 报警)
10.0 .1.11 不在线 ( 报警)
10.0 .1.12 不在线 ( 报警)
10.0 .1.13 不在线 ( 报警)
4 写一个脚本完成 输入编号 输出需要查看内容:
1 .help帮助
2 .显示内存使用
3 .显示磁盘使用
4 .登录用户
5 .查看ip
function help_message {
echo "1. 显示帮助信息"
echo "2. 显示内存使用情况"
echo "3. 显示磁盘使用情况"
echo "4. 显示登录用户列表"
echo "5. 显示本机IP地址"
}
function display_memory_usage {
free -h
}
function display_disk_usage {
df -h
}
function show_logged_in_users {
who
}
function show_ip_address {
hostname -I
}
while true ; do
echo "请选择操作:"
help_message
read -p "请输入编号: " choice
case $choice in
1 ) help_message ; ;
2 ) display_memory_usage ; ;
3 ) display_disk_usage ; ;
4 ) show_logged_in_users ; ;
5 ) show_ip_address ; ;
*) echo "无效的选择,请重新输入!" ; ;
esac
echo
done
效果
[ root@centos7mage logs]
请选择操作:
1 . 显示帮助信息
2 . 显示内存使用情况
3 . 显示磁盘使用情况
4 . 显示登录用户列表
5 . 显示本机IP地址
请输入编号: 1
1 . 显示帮助信息
2 . 显示内存使用情况
3 . 显示磁盘使用情况
4 . 显示登录用户列表
5 . 显示本机IP地址
请选择操作:
1 . 显示帮助信息
2 . 显示内存使用情况
3 . 显示磁盘使用情况
4 . 显示登录用户列表
5 . 显示本机IP地址
请输入编号: 2
total used free shared buff/cache available
Mem: 972M 156M 310M 7 .5M 505M 654M
Swap: 4 .0G 264K 4 .0G
请选择操作:
1 . 显示帮助信息
2 . 显示内存使用情况
3 . 显示磁盘使用情况
4 . 显示登录用户列表
5 . 显示本机IP地址
请输入编号: 3
Filesystem Size Used Avail Use% Mounted on
devtmpfs 475M 0 475M 0 % /dev
tmpfs 487M 0 487M 0 % /dev/shm
tmpfs 487M 7 .6M 479M 2 % /run
tmpfs 487M 0 487M 0 % /sys/fs/cgroup
/dev/sda2 94G 7 .8G 86G 9 % /
/dev/sda3 47G 33M 47G 1 % /data
/dev/sda1 1014M 153M 862M 16 % /boot
请选择操作:
1 . 显示帮助信息
2 . 显示内存使用情况
3 . 显示磁盘使用情况
4 . 显示登录用户列表
5 . 显示本机IP地址
请输入编号: 4
root pts/0 2024 -04-07 16 :29 ( 10.0 .1.1)
root pts/1 2024 -04-07 12 :57 ( 10.0 .1.1)
请选择操作:
1 . 显示帮助信息
2 . 显示内存使用情况
3 . 显示磁盘使用情况
4 . 显示登录用户列表
5 . 显示本机IP地址
请输入编号: 5
10.0 .1.145
5 使用shell 完成 将当前目录下大于10K的文件批量转移到/tmp目录下
find . -type f -size +10k -exec mv { } /tmp \ ;
echo "已完成转移大于10K的文件至/tmp目录。"
效果(部分展示)
[ root@centos7mage tmp]
0 /tmp/
[ root@centos7mage ~]
已完成转移大于10K的文件至/tmp目录。
[ root@centos7mage ~]
594M /tmp/
HashTreeTraverser.html
HC4CookieHandler.html
HeaderAsPropertyRenderer.html
HeaderAsPropertyRendererWrapper.html
Header.html
HeaderManager.html
HeaderPanel.html
HeapDumper.html
Help.html
hints_and_tips.html
HitsPerSecondGraphConsumer.html
Hoic-高轨道离子炮-压力测试工具.rar
HoldSampleSender.html
HorizontalPanel.html
HTMLAssertionGui.html
HTMLAssertion.html
HtmlExtractorGui.html
HtmlExtractor.html
HtmlPane.html
HTMLParseException.html
HTMLParser.html
HtmlParsingUtils.html
HtmlReportAction.html
HtmlReportGenerator.html
html_report_menu.png
HtmlReportUI.html
HtmlTemplateExporter.html
HTTPAbstractImpl.html
HTTPArgument.html
HTTPArgumentsPanel.html
httpasyncclient-4.1.5.jar
httpclient-4.5.13.jar
HttpClientDefaultParameters.html
HTTPConstants.html
HTTPConstantsInterface.html
http-cookie-manager.png
httpcore-4.4.15.jar
httpcore-nio-4.4.15.jar
http-defaults1.png
http-defaults2.png
HttpDefaultsGui.html
HTTPFileArg.html
HTTPFileArgs.html
HTTPFileArgsPanel.html
HTTPFileImpl.html
HTTPHC4Impl.html
6.一键部署LNMP
#!/bin/bash
NGINX_V = 1.15 .6
PHP_V = 5.6 .36
TMP_DIR = /tmp
INSTALL_DIR = /usr/local
PWD_C = $PWD
echo
echo -e "\t Menu\n "
echo -e "1. Install Nginx"
echo -e "2. Install PHP"
echo -e "3. Install MySQL"
echo -e "4. Deploy LNMP"
echo -e "9. Quit"
function command_status_check ( ) {
if [ $? -ne 0 ] ; then
echo $1
exit
fi
}
function install_nginx ( ) {
cd $TMP_DIR
yum install -y gcc gcc-c++ make openssl-devel pcre-devel wget
wget http://nginx.org/download/nginx-${NGINX_V} .tar.gz
tar zxf nginx-${NGINX_V} .tar.gz
cd nginx-${NGINX_V}
./configure --prefix = $INSTALL_DIR /nginx \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-stream
command_status_check "Nginx - 平台环境检查失败!"
make -j 4
command_status_check "Nginx - 编译失败!"
make install
command_status_check "Nginx - 安装失败!"
mkdir -p $INSTALL_DIR /nginx/conf/vhost
alias cp = cp ; cp -rf $PWD_C /nginx.conf $INSTALL_DIR /nginx/conf
rm -rf $INSTALL_DIR /nginx/html/*
echo "ok" > $INSTALL_DIR /nginx/html/status.html
echo '<?php echo "ok"?>' > $INSTALL_DIR /nginx/html/status.php
$INSTALL_DIR /nginx/sbin/nginx
command_status_check "Nginx - 启动失败!"
}
function install_php ( ) {
cd $TMP_DIR
yum install -y gcc gcc-c++ make gd-devel libxml2-devel \
libcurl-devel libjpeg-devel libpng-devel openssl-devel \
libmcrypt-devel libxslt-devel libtidy-devel
wget http://docs.php.net/distributions/php-${PHP_V} .tar.gz
tar zxf php-${PHP_V} .tar.gz
cd php-${PHP_V}
./configure --prefix = $INSTALL_DIR /php \
--with-config-file-path= $INSTALL_DIR /php/etc \
--enable-fpm --enable-opcache \
--with-mysql --with-mysqli --with-pdo-mysql \
--with-openssl --with-zlib --with-curl --with-gd \
--with-jpeg-dir --with-png-dir --with-freetype-dir \
--enable-mbstring --enable-hash
command_status_check "PHP - 平台环境检查失败!"
make -j 4
command_status_check "PHP - 编译失败!"
make install
command_status_check "PHP - 安装失败!"
cp php.ini-production $INSTALL_DIR /php/etc/php.ini
cp sapi/fpm/php-fpm.conf $INSTALL_DIR /php/etc/php-fpm.conf
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod +x /etc/init.d/php-fpm
/etc/init.d/php-fpm start
command_status_check "PHP - 启动失败!"
}
read -p "请输入编号:" number
case $number in
1 )
install_nginx; ;
2 )
install_php; ;
3 )
install_mysql; ;
4 )
install_nginx
install_php
; ;
9 )
exit ; ;
esac
7.监控2台服务器硬盘利用率 使用率
输出内容如下
ip:xxxx
磁盘总容量: 40GB
使用磁盘容量:17GB
ssh-keygen
ls .ssh/
ssh-copy-id root@10.0.0.1
ssh root@10.0.1.142 df -h
SERVERS = ( "10.0.1.142" "10.0.1.143" )
for SERVER_IP in "${SERVERS[ @] } " ; do
DISK_USAGE = $( ssh root@$SERVER_IP 'df -h / | awk ' \ ''NR==2{print $5}' \ ''' )
TOTAL_DISK = $( ssh root@$SERVER_IP 'df -hT / | awk ' \ ''NR==2{print $2}' \ ''' )
USED_DISK = $( ssh root@$SERVER_IP 'df -hT / | awk ' \ ''NR==2{print $3}' \ ''' )
echo "IP: $SERVER_IP "
echo "磁盘总容量: $TOTAL_DISK "
echo "使用磁盘容量: $USED_DISK "
done
测试效果
[ root@centos7mage ~]
IP: 10.0 .1.142
磁盘总容量: xfs
使用磁盘容量: 94G
IP: 10.0 .1.143
磁盘总容量: xfs
使用磁盘容量: 94G
8.批量检查 5个网站域名是否正常
#!/bin/bash
domains = ( "www.baidu.com" "www.sansi.com" "www.abc.com" "www.jkkcss.cn" "bbs.sansi.fun" )
for domain in "${domains[ @] } " ; do
response_code = $( curl -s -o /dev/null -w "%{http_code}" "$domain " )
case $response_code in
200 )
echo "$domain is up with status code $response_code (OK)"
; ;
301 | 302 )
echo "$domain is redirected with status code $response_code "
; ;
403 )
echo "$domain is up but returning a 403 Forbidden status code"
; ;
404 )
echo "$domain is up but returning a 404 Not Found status code"
; ;
500 | 501 | 502 )
echo "$domain is up but returning an error status code $response_code "
; ;
*)
echo "$domain is down or returned unknown status code $response_code "
; ;
esac
done
效果测试
[ root@centos7mage ~]
www.baidu.com is up with status code 200 ( OK)
www.sansi.com is redirected with status code 301
www.abc.com is redirected with status code 301
www.jkkcss.cn is redirected with status code 301
bbs.sansi.fun is redirected with status code 301
9.统计磁盘使用率
磁盘大于%5 就打印mail 小于 硬盘正常
内存使用使用率 内存使用率大于%5就打印mail 小于 就 内存正常
function send_email ( ) {
local SUBJECT = $1
local MESSAGE = $2
echo "$MESSAGE " | mail -s "$SUBJECT " "15178374440@163.com"
}
function check_and_send_alert ( ) {
local USAGE = $1
local RESOURCE = $2
local THRESHOLD = 5
if (( $( echo "$USAGE >= $THRESHOLD" | bc - l) )) ; then
ALERT_BODY = "系统${RESOURCE} 资源可能过大,请及时解决。当前使用率为${USAGE} %"
send_email "[$RESOURCE ]资源警告" "$ALERT_BODY "
fi
}
function cpu ( ) {
util = $( vmstat | awk 'NR==3{print $13+$14}' )
iowait = $( vmstat | awk 'NR==3{print $16}' )
echo "CPU - 使用率: ${util} %, 等待磁盘IO响应使用率: ${iowait} %"
check_and_send_alert "$util " "CPU"
}
function memory ( ) {
total = $( free -m | awk 'NR==2{print $2}' )
used = $( free -m | awk 'NR==2{print $3}' )
usage = $(( 100 * used / total))
echo "内存 - 总大小: ${total} MB, 已使用:${used} MB, 使用率:${usage} %"
check_and_send_alert "$usage " "内存"
}
function disk ( ) {
fs = $( df -h | awk '/^\/dev/{print $1}' )
for p in $fs ; do
mounted = $( df -h | awk -v p = "$p " '$1==p{print $NF}' )
size = $( df -h | awk -v p = "$p " '$1==p{print $2}' )
used = $( df -h | awk -v p = "$p " '$1==p{print $3}' )
user_percent = $( df -h | awk -v p = "$p " '$1==p{print $5}' | tr -d '%' )
echo "硬盘 - 挂载点: $mounted , 总大小: $size , 已使用: $used , 使用率:${user_percent} %"
check_and_send_alert "$user_percent " "硬盘(挂载点:$mounted )"
done
}
function tcp_status ( ) {
if ! command -v netstat &> /dev/null; then
echo "检测到netstat未安装,正在尝试安装..."
yum -y install net-tools > &2
fi
if command -v netstat &> /dev/null; then
summary = $( netstat -antp | awk '{a[$6]++} END{for(i in a) print i ": " a[i] " "}' )
echo "TCP连接状态 - $summary "
else
echo "安装netstat失败,请手动安装并重试。"
fi
}
if ! command -v mailx &> /dev/null; then
echo "邮件发送工具mailx未安装,正在尝试安装..."
yum -y install mailx > &2
fi
cpu
memory
disk
tcp_status
测试
dd if = /dev/zero of = /bigfile bs = 1G count = 10
10. 使用for循环安装 批量安装3台服务器 php环境 使用(LAMP)脚本实现 环境yum 安装都可以 主要测试语法
工作结果就是 每台服务器 都可以打开php 测试页面
模板一(yum安装)
SERVERS = ( "10.0.1.142" "10.0.1.143" "10.0.1.145" )
function install_lamp ( ) {
server_ip = $1
ssh root@$server_ip << EOF
set -e
yum update -y
yum install epel-release -y
yum install httpd mariadb-server php php-mysqlnd -y
systemctl enable httpd
systemctl start httpd
systemctl enable mariadb
systemctl start mariadb
firewall-cmd --permanent --add-service=http
firewall-cmd --reload
EOF
}
for server in "${SERVERS[ @] } " ; do
echo "开始在服务器 $server 上安装 LAMP 环境..."
install_lamp "$server "
echo "完成在服务器 $server 上安装 LAMP 环境。"
done
模板一(2)
NETWORK = "10.0.1."
START = 1
END = 254
ONLINE_SERVERS = ( )
MENU_OPTIONS = ( )
for i in $( seq $START $END) ; do
IP = "$NETWORK $i "
if nmap -q -Pn -p22 $IP | grep -q 'open' ; then
ONLINE_SERVERS += ( "$IP " )
MENU_OPTIONS += ( "$(( i- START+ 1 )) $IP " )
echo "在线: $IP "
else
echo "离线: $IP "
fi
done
install_lamp ( ) {
server_ip = $1
ssh root@$server_ip << EOF
set -e
yum update -y
yum install epel-release -y
yum install httpd mariadb-server php php-mysqlnd -y
systemctl enable httpd
systemctl start httpd
systemctl enable mariadb
systemctl start mariadb
firewall-cmd --permanent --add-service=http
firewall-cmd --reload
EOF
}
echo "请选择要安装LAMP环境的服务器:"
COUNTER = 1
for option in "${MENU_OPTIONS[ @] } " ; do
echo "$option "
done
echo "$(( COUNTER+ 1 )) 全部安装"
echo "$(( COUNTER+ 2 )) 退出"
read -p "请选择: " CHOICE
if [ [ $CHOICE -eq $(( COUNTER+ 1 )) ] ] ; then
for ip in "${ONLINE_SERVERS[ @] } " ; do
install_lamp "$ip "
done
elif [ [ $CHOICE -gt 0 && $CHOICE -le $COUNTER ] ] ; then
install_lamp "${ONLINE_SERVERS[ $(($CHOICE-1))] } "
else
echo "无效的选择,请重新运行脚本。"
fi
模板二(编译安装)
NGINX_V = 1.15 .6
PHP_V = 5.6 .36
TMP_DIR = /tmp
INSTALL_DIR = /usr/local
PWD_C = $PWD
echo
echo -e "\t Menu\n "
echo -e "1. Install Nginx"
echo -e "2. Install PHP"
echo -e "3. Install MySQL"
echo -e "4. Deploy LNMP"
echo -e "9. Quit"
function command_status_check ( ) {
if [ $? -ne 0 ] ; then
echo $1
exit
fi
}
function install_nginx ( ) {
cd $TMP_DIR
yum install -y gcc gcc-c++ make openssl-devel pcre-devel wget
wget http://nginx.org/download/nginx-${NGINX_V} .tar.gz
tar zxf nginx-${NGINX_V} .tar.gz
cd nginx-${NGINX_V}
./configure --prefix = $INSTALL_DIR /nginx \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-stream
command_status_check "Nginx - 平台环境检查失败!"
make -j 4
command_status_check "Nginx - 编译失败!"
make install
command_status_check "Nginx - 安装失败!"
mkdir -p $INSTALL_DIR /nginx/conf/vhost
alias cp = cp ; cp -rf $PWD_C /nginx.conf $INSTALL_DIR /nginx/conf
rm -rf $INSTALL_DIR /nginx/html/*
echo "ok" > $INSTALL_DIR /nginx/html/status.html
echo '<?php echo "ok"?>' > $INSTALL_DIR /nginx/html/status.php
$INSTALL_DIR /nginx/sbin/nginx
command_status_check "Nginx - 启动失败!"
}
function install_php ( ) {
cd $TMP_DIR
yum install -y gcc gcc-c++ make gd-devel libxml2-devel \
libcurl-devel libjpeg-devel libpng-devel openssl-devel \
libmcrypt-devel libxslt-devel libtidy-devel
wget http://docs.php.net/distributions/php-${PHP_V} .tar.gz
tar zxf php-${PHP_V} .tar.gz
cd php-${PHP_V}
./configure --prefix = $INSTALL_DIR /php \
--with-config-file-path= $INSTALL_DIR /php/etc \
--enable-fpm --enable-opcache \
--with-mysql --with-mysqli --with-pdo-mysql \
--with-openssl --with-zlib --with-curl --with-gd \
--with-jpeg-dir --with-png-dir --with-freetype-dir \
--enable-mbstring --enable-hash
command_status_check "PHP - 平台环境检查失败!"
make -j 4
command_status_check "PHP - 编译失败!"
make install
command_status_check "PHP - 安装失败!"
cp php.ini-production $INSTALL_DIR /php/etc/php.ini
cp sapi/fpm/php-fpm.conf $INSTALL_DIR /php/etc/php-fpm.conf
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod +x /etc/init.d/php-fpm
/etc/init.d/php-fpm start
command_status_check "PHP - 启动失败!"
}
read -p "请输入编号:" number
case $number in
1 )
install_nginx; ;
2 )
install_php; ;
3 )
install_mysql; ;
4 )
install_nginx
install_php
; ;
9 )
exit ; ;
esac
11.有人攻击我服务器 就拉黑异常ip
模板一
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
模板二
LOGFILE = /usr/local/nginx/logs/access.log
THRESHOLD = 100
PORT = 80
BLOCK_TIME = 1800
BADIPS_LOG = /tmp/badip.log
IPS_FILE = /tmp/ips.txt
NOW = $( date +%s)
MINUTE_AGO = $(( NOW - 60 ))
HOUR_MINUTE = $( date -d "@$MINUTE_AGO " "+%d/%b/%Y:%H:%M" )
grep "$HOUR_MINUTE :" $LOGFILE | awk '{print $1}' | sort | uniq -c | awk -v th = "$THRESHOLD " '$1 > th {print $2}' > $IPS_FILE
block ( ) {
while IFS = read -r IP; do
if ! iptables -L INPUT -n --line-numbers -v | grep -q "^ *[[:digit:]]*:.* -s $IP -p tcp --dport $PORT .*REJECT" ; then
iptables -I INPUT -p tcp --dport $PORT -s $IP -j REJECT
echo "` date +%F-%T` $IP " >> $BADIPS_LOG
( sleep $BLOCK_TIME && unblock_ip "$IP " ) &
fi
done < "$IPS_FILE "
}
unblock_ip ( ) {
IP = $1
iptables -D INPUT -p tcp --dport $PORT -s $IP -j REJECT
echo "` date +%F-%T` $IP - Unblocked" >> $BADIPS_LOG
}
if [ $( date +%M) -eq 00 ] || [ $( date +%M) -eq 30 ] ; then
unblock_all
block
else
block
fi
unblock_all ( ) {
iptables -L INPUT -n --line-numbers -v | grep '^ *[[:digit:]]*:.* -s .* -p tcp --dport $PORT .*REJECT' | awk '{print $1}' | xargs -n1 iptables -D INPUT
iptables -Z
}
block
cat ips.txt
cat badip.log
模拟压测(脚本)
while true ; do
ab -n 9000 -c 1000 http://10.0.1.145/
sleep 3
done
[ root@centos7mage tmp]
10.0 .1.135
[ root@centos7mage tmp]
2024 -04-07-22:45:49 10.0 .1.139
2024 -04-07-22:45:50 10.0 .1.139
2024 -04-07-22:49:02 10.0 .1.135
2024 -04-07-22:49:02 10.0 .1.135
2024 -04-07-22:49:03 10.0 .1.135
2024 -04-07-22:49:03 10.0 .1.135
2024 -04-07-22:49:04 10.0 .1.135
2024 -04-07-22:49:04 10.0 .1.135
2024 -04-07-22:49:05 10.0 .1.135
Benchmarking 10.0 .1.145 ( be patient)
apr_socket_recv: Connection refused ( 111 )
This is ApacheBench, Version 2.3 < $Revision : 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南