shell应用

1、查询帖子的点赞数量

代码示例:

a=`curl -s https://testerhome.com/topics | grep -o 'href="/topics/[0-9]*"'|awk -F '/|"' '{print $4}'`;for id in $a;do url='https://testerhome.com/topics/'$id;zan=`curl -s $url | grep -o -m1 '<span>[0-9]*' | awk -F '>' '{print $2}' `;if [ -n "$zan" ];then echo $url '点赞数为' $zan;fi;done;

首先,获取社区下帖子的链接ID

a=`curl -s https://testerhome.com/topics | grep -o 'href="/topics/[0-9]*"'|awk -F '/|"' '{print $4}'`;echo $a

结果:

21495 21377 21201 21497 21462 21378 20733 21487 20960 21238 21496 20632 21465 21483 21492 21485 21426 21445 21429 21490 21397 21489 21237 21475 20574 21490 21471 21470 21452 21444

然后,并且将帖子ID并且为完成URL链接

a=`curl -s https://testerhome.com/topics | grep -o 'href="/topics/[0-9]*"'|awk -F '/|"' '{print $4}'`;for id in $a;do url='https://testerhome.com/topics/'$id;echo $url;done;

结果:

https://testerhome.com/topics/21495
https://testerhome.com/topics/21377
https://testerhome.com/topics/21201
https://testerhome.com/topics/21497
https://testerhome.com/topics/21462
https://testerhome.com/topics/21378
https://testerhome.com/topics/20733
https://testerhome.com/topics/21487
https://testerhome.com/topics/20960
https://testerhome.com/topics/21238
https://testerhome.com/topics/21496
https://testerhome.com/topics/20632
https://testerhome.com/topics/21465
https://testerhome.com/topics/21483
https://testerhome.com/topics/21492

接着,访问每一个链接,获取其中的点赞数量

a=`curl -s https://testerhome.com/topics | grep -o 'href="/topics/[0-9]*"'|awk -F '/|"' '{print $4}'`;for id in $a;do url='https://testerhome.com/topics/'$id;zan=`curl -s $url | grep -o -m1 '<span>[0-9]*' | awk -F '>' '{print $2}' `;echo $zan;done

结果:

2
1
3

最后,让输出信息更符合人类阅读习惯

a=`curl -s https://testerhome.com/topics | grep -o 'href="/topics/[0-9]*"'|awk -F '/|"' '{print $4}'`;for id in $a;do url='https://testerhome.com/topics/'$id;zan=`curl -s $url | grep -o -m1 '<span>[0-9]*' | awk -F '>' '{print $2}' `;if [ -n "$zan" ];then echo $url '点赞数为:' $zan;else echo $url '点赞数为:'0;fi;done;

结果:

https://testerhome.com/topics/21495 点赞数为: 2
https://testerhome.com/topics/21377 点赞数为: 1
https://testerhome.com/topics/21201 点赞数为: 3
https://testerhome.com/topics/21323 点赞数为: 1
https://testerhome.com/topics/21497 点赞数为:0
https://testerhome.com/topics/21462 点赞数为: 1
https://testerhome.com/topics/21378 点赞数为: 7
https://testerhome.com/topics/20733 点赞数为:0

最后再简化信息,获取链接ID和点赞数

a=`curl -s https://testerhome.com/topics | grep -o 'href="/topics/[0-9]*"'|awk -F '/|"' '{print $4}'`;for id in $a;do url='https://testerhome.com/topics/'$id;zan=`curl -s $url | grep -o -m1 '<span>[0-9]*' | awk -F '>' '{print $2}' `;if [ -n "$zan" ];then echo $url '点赞数为:' $zan;else echo $url '点赞数为:'0;fi;done | awk -F '/' '{print $NF}'

结果:

21495 点赞数为: 2
21377 点赞数为: 1
21201 点赞数为: 3
21323 点赞数为: 1
21497 点赞数为:0
21462 点赞数为: 1
21378 点赞数为: 7
20733 点赞数为:0
2、shell编程
while true
do
  read -p "please input:" var_q
  if [ $var_q == "quit"	]
     then 
	break
  else
     echo $var_q
  fi
done

3、修改环境变量path
[root@localhost ~]# vi .bash_profile

添加要修改的path变量,注意添加时新增一行,填入新的path变量

export PATH

#以下为新增的path变量
export PATH=$PATH:/root/xyz

编辑好后,重新生效

[root@localhost ~]# vi .bash_profile
[root@localhost ~]# source ~/.bash_profile 
4、判断网页中是否有死链

代码示例:

curl -s http://www.gdsc.com.cn/sc/index.jsp | grep href | grep -o "http[^\"']*" | while read line;do curl -s -I $line | grep 200 && echo $line 200 || echo $line error;done

结果:

http://www.cgdc.com.cn/gzgqggfz/index.jhtml error
HTTP/1.1 200 OK
http://www.12371.cn/ 200
HTTP/1.1 200 OK
X-Powered-By: Servlet 2.4; Tomcat-5.0.28/JBoss-4.0.1RC2 (build: CVSTag=JBoss_4_0_1_RC2 date=200411302349)
http://www.gdsc.com.cn/sc/lxyz/index.jsp 200
HTTP/1.1 200 OK
5、查找出log中的404 500的报错

在400和500的前后添加空格,可以过滤一部分内容

grep -E ' 400 | 500 ' test.log

另外一种方法:

awk '$9=="400"' test.log

另外一种方法:

 grep -E ' 400 | 500 ' test.log | sort |uniq -c | less

注意less可以加载少部分内容,不会因为访问的文件过大导致系统奔溃。

6、找出500错误数据行的前10条非500的数据
grep -B 10 "500" test.log
7、找出访问量最高的ip
awk '{print $1}' test.log | sort | uniq -c | sort -nr | head -5

结果:

[root@localhost ~]# awk '{print $1}' test.log | sort | uniq -c | sort -nr | head -5
      2 10.1.1.112
      2 
      1 119.139.196.241
      1 10.1.1.77
      1 10.1.1.7

命令解释:

 uniq 命令删除文件中的重复行  -c 在输出行前面加上每行在输入文件中出现的次数
 sort 将文本文件内容加以排序,sort可针对文本文件的内容,以行为单位来排序
 -n  依照数值的大小排序
 -r  以相反的顺序来排序
8、找出访问量最高的页面地址

复杂版本:

awk '{print $7}' test.log |sed -e "s#[0-9]\{1,\}#*#g" -e 's#?.*##' -e 's#/[^/]*\.png.*##'|  sort | uniq -c | sort -nr |head -10
sed -e:表示可以匹配多个表达式
sed -e "s#[0-9]\{1,\}#*#g" :表示将多个数字替换为一个*
sed -e 's#?.*##' :表示将?后面的内容都替换为空
sed -e 's#/[^/]*\.png.*##':表示将非/至.png的内容替换为空

精简版本:

 awk '{print $7}' test.log | sed 's#[0-9]#_#g' | sort |uniq -c|sort -nr|head -10
9、排序

表示对data文件中的内容进行排序。sort命令是对于每一行的内容根据字典序(ASCII码)进行排序,这样可以保证重复的记录时相邻的。

cat  t1.log | sort

输入图片说明

10、合并相邻重复记录,统计重复数
cat  t1.log | sort | uniq -c

这里,通过管道(|)将左边部分的命令的输出作为右边部分的输入。uniq -c 表示合并相邻的重复记录,并统计重复数。因为uniq -c 只会合并相邻的记录,所以在使用该命令之前需要先排序。

11、对记录重新排序

需要用到sort命令的 -k 1 、-n、-r 三个命令参数

cat  t1.log | sort | uniq -c | sort -k 1 -n -r

经过uniq -c 处理之后的数据格式形如"2 data",第一个字段是数字,表示重复的记录数;第二个字段为记录的内容。我们将对此内容进行排序。sort -k 1表示对于每行的第一个字段进行排序,这里即指代表重复记录数的那个字段。因为sort命令的默认排序是按照ASCII,这就会导致按从大到小进行排序时,数值2会排在数值11的前面,所以需要使用-n 参数指定sort命令按照数值大小进行排序。-r 表示逆序,即按照从大到小的顺序进行排序。

12、使用awk -F命令分隔IP地址,并取数组的第二部分
cat  t1.log | sort  | uniq -c | sort -k 1 -n -r | awk -F '//'  '{print  $2}'

经过sort data | uniq -c | sort -k 1 -n -r 处理后的文本是 http://192.168.1.100 这样的格式,我们需要的结果是192.168.1.100这样的格式,需要去掉http://这些字段,采用awk才处理,awk -F '//' 是将http://192.168.1.100分组成2部分 http://192.168.1.100{print $2}的作用是取数组的第二部分,即192.168.1.100

13、使用head -n命令选取前n行
cat  t1.log | sort | uniq -c | sort -k 1 -n -r | awk -F '//'  '{print  $2}'| head -10

head 命令表示选取文本的前x行。通过head -10 就可以得到排序结果中前十行的内容。

14、分析日志文件下 2012-05-04 访问页面最高 的前20个 URL 并排序
cat access.log |grep '04/May/2012'| awk '{print $11}'|sort|uniq -c|sort -nr|head -20
15、查询受访问页面的URL地址中 含有 www.abc.com 网址的 IP 地址
cat access_log | awk '($11~/\www.abc.com/){print $1}'|sort|uniq -c|sort -nr
16、获取访问最高的10个IP地址 同时也可以按时间来查询
cat linewow-access.log|awk '{print $1}'|sort|uniq -c|sort -nr|head -10
17、获得访问前10位的ip地址
cat access.log|awk '{print $1}'|sort|uniq -c|sort -nr|head -10
cat access.log|awk '{counts[$(11)]+=1}; END {for(url in counts) print counts[url], url}'
18、访问次数最多的文件或页面,取前20及统计所有访问IP
cat access.log|awk '{print $11}'|sort|uniq -c|sort -nr|head -20
awk '{ print $1}' access.log |sort -n -r |uniq -c|wc -l
cat wangsu.log | egrep '06/Sep/2012:14:35|06/Sep/2012:15:05' |awk '{print $1}'|sort|uniq -c|sort -nr|head -10  
查询日志中 时间段内的情况
19、列出传输最大的几个exe文件(分析下载站的时候常用)
cat access.log |awk '($7~/\.exe/){print $10 " " $1 " " $4 " " $7}'|sort -nr|head -20
20、列出输出大于200000byte(约200kb)的exe文件以及对应文件发生次数
cat access.log |awk '($10 > 200000 && $7~/\.exe/){print $7}'|sort -n|uniq -c|sort -nr|head -100
20、如果日志最后一列记录的是页面文件传输时间,则有列出到客户端最耗时的页面
cat access.log |awk '($7~/\.php/){print $NF " " $1 " " $4 " " $7}'|sort -nr|head -100
21、列出最最耗时的页面(超过60秒的)的以及对应页面发生次数
cat access.log |awk '($NF > 60 && $7~/\.php/){print $7}'|sort -n|uniq -c|sort -nr|head -100
22、列出传输时间超过 30 秒的文件
cat access.log |awk '($NF > 30){print $7}'|sort -n|uniq -c|sort -nr|head -20
23、统计网站流量(G)
cat access.log |awk '{sum+=$10} END {print sum/1024/1024/1024}'
24、统计404的连接
awk '($9 ~/404/)' access.log | awk '{print $9,$7}' | sort
25、统计http status
cat access.log |awk '{counts[$(9)]+=1}; END {for(code in counts) print code, counts[code]}'

cat access.log |awk '{print $9}'|sort|uniq -c|sort -rn
26、每秒并发
awk '{if($9~/200|30|404/)COUNT[$4]++}END{for( a in COUNT) print a,COUNT[a]}'|sort -k 2 -nr|head -n10
27、带宽统计
cat apache.log |awk '{if($7~/GET/) count++}END{print "client_request="count}'

cat apache.log |awk '{BYTE+=$11}END{print "client_kbyte_out="BYTE/1024"KB"}'
28、找出某天访问次数最多的10个IP
cat /tmp/access.log | grep "20/Mar/2011" |awk '{print $3}'|sort |uniq -c|sort -nr|head
29、当天ip连接数最高的ip都在干些什么:
cat access.log | grep "10.0.21.17" | awk '{print $8}' | sort | uniq -c | sort -nr | head -n 10
30、找出访问次数最多的几个分钟
awk '{print $1}' access.log | grep "20/Mar/2011" |cut -c 14-18|sort|uniq -c|sort -nr|head
31、求100以内的质数
#!/bin/bash                      
#******************************************
#Author:          xyz      
#Create_Time:     2020-02-14
#Version:         v1.0                 
#Mail:            471604754@qq.com    
#Description:     let it go         
#******************************************


for i in {1..100}
do
        for ((x=2;x<=i-1;x++))
        do
                d=$[$i%$x]
                if [ $d -eq 0 ];then
                        break
                fi
        done
        if [ $x -eq $i ];then
                echo $i 
        fi

done
32、假设有一个脚本scan.sh,里面有1000行代码,并在vim模式下面,请按照如下要求写入对应的指令

1) 将shutdown字符串全部替换成reboot

:%s/shutdown/reboot/g

2) 清空所有字符

:%d

3) 不保存退出

q!
33、使用for循环在/oldboy目录下通过随机小写10个字母加固定字符串oldboy批量创建10个html文件
#!/usr/bin/env bash

# target directory
dir=$HOME/wwl

if [ ! -d $dir ];then
    mkdir -p $dir
fi

for i in `seq 10`
do
	#$RANDOM随机生成5位数字,md5sum进行加密,cut 截取10位数
    str=`echo $RANDOM | md5sum | cut -c 1-10`
    touch $dir/${str}_oldboy.html
done
#!/usr/bin/env bash

# target directory
dir=$HOME/wwl

if [ ! -d $dir ];then
    mkdir -p $dir
fi

letter=(`echo {a..z}`) #包含26个字母的数组
tmp="" #保存10个字母

for i in `seq 10`
do
    for i in `seq 10`
    do
        str=${letter[$(($(($RANDOM%26))+1))]}
        tmp=$tmp$str
    done
    touch $dir/${tmp}_oldboy.html
    tmp=""
done
34、将以上文件名中的oldboy全部改成oldgirl(用for循环实现),并且html改成大写。
#!/usr/bin/env bash

dir=$HOME/wwl
str=(`ls $dir`)
for i in `seq 10`
do  
    tmp1=${str[((i-1))]} #原始名
    tmp2=`echo $tmp1 | sed "s/oldboy/oldgirl/g" |  sed "s/html/HTML/g"`
    mv $dir/$tmp1 $dir/$tmp2
done
#!/usr/bin/env bash

find $HOME/wwl -name "*.*" | sed "s/\.html$//" | xargs -i echo mv {}.html {}.HTML | sed "s/oldboy/oldgirl/2" | sh
35、写一个脚本,实现判断10.0.0.0/24网络里,当前在线用户的IP有哪些
#!/usr/bin/env bash

for i in `seq 255`
do
    ping -c 2 -w 2 10.190.23.$i > /dev/null
    if (($? == 0 ));then
        echo -e "\033[32;40m 10.190.23.$i is UP.\033[0m"
    else
        echo -e "\033[31;40m 10.190.23.$i is Down.\033[0m"
    fi
done
36、批量创建10个系统帐号oldboy01-oldboy10并设置密码(密码为随机8位字符串)
#!/usr/bin/env bash

for i in `seq -w 10`
do
    useradd oldboy$i
    pass=`echo $RANDOM | md5sum | cut -c 1-8`
    echo $pass | passwd --stdin oldboy-$i
    echo oldboy$i:$pass >> psswd.txt
done 
37、写一个脚本解决DOS攻击生产案例

提示:根据web日志或者或者网络连接数,监控当某个IP并发连接数或者短时内PV达到100,即调用防火墙命令封掉对应的IP,监控频率每隔3分钟。防火墙命令为:iptables -A INPUT -s 10.0.1.10 -j DROP。

#!/usr/bin/env bash
log=/tmp/tmp.log
[ -f $log ] || touch $log
function add_iptables(){
    while read line
        do
          ip=`echo $line|awk '{print $2}'`
          count=`echo $line|wc -l`
            if [ $count -gt 100 ] && [`iptables -L -n|grep "$ip"|wc -l` -lt 1 ]
             then
                iptables -I INPUT -s $ip -jDROP
                echo "$line isdropped" >>/tmp/droplist.log
            fi
        done<$log
}
function main(){
    while true
           do
             netstat -an|grep EST|awk '{print $(NF-1)}'|awk -F '[:]' '{print $1}'|sort|uniq -c >$log
             add_iptables
             sleep 180
    done
}
 
main
38、开发mysql多实例启动脚本:

已知mysql多实例启动命令为:mysqld_safe –defaults-file=/data/3306/my.cnf & 停止命令为:mysqladmin -u root -poldboy123 -S /data/3306/mysql.sock shutdown 请完成mysql多实例启动启动脚本的编写 要求:用函数,case语句、if语句等实现。

#!/bin/sh

[ -f /etc/init.d/functions ]&&. /etc/init.d/functions||exit
#Define Variables
Port=$1
Mysql_user=root
Mysql_sock=/data/${Port}/mysql.sock
Path=/application/mysql/bin
RETVAL=0
#Define Start Function
start() {
  if [ ! -e "$Mysql_sock" ];then
    /bin/sh $Path/mysqld_safe --defaults-file=/data/${Port}/my.cnf 2>&1 >/dev/null &
    RETVAL=$?
    if [ $RETVAL -eq 0 ];then
        action "Starting $Port MySQL..." /bin/true
      else
        action "Starting $Port MySQL..." /bin/false
    fi
    else
      echo "$Port MySQL is Running..."
  fi
  return $RETVAL
}

#Define Stop Function
stop() {
  if [ ! -e "$Mysql_sock" ];then
      echo "$Port MySQL is Stopped..."
    else
      read -p "Please Input $Port MySQL Password:" PWD
      Mysql_pwd=$PWD
      $Path/mysqladmin -u ${Mysql_user} -p${Mysql_pwd} -S /data/${Port}/mysql.sock shutdown
      RETVAL=$?
      if [ $RETVAL -eq 0 ];then
        action "Stopping $Port MySQL..." /bin/true
      else
        action "Stopping $Port MySQL..." /bin/false
      fi
  fi
  return $RETVAL
}

case "$2" in
  start)
        start
        RETVAL=$?
        ;;
  stop)
        stop
        RETVAL=$?
        ;;
  restart)
        stop
        sleep 3
        start
        RETVAL=$?
        ;;
  *)
        echo -e "USAGE:$0 {3306|3307|3308} {start|stop|restart}"
        RETVAL=2
        ;;
esac
exit $RETVAL
39、如何实现对MySQL数据库进行分库备份,请用脚本实现
#!/bin/bash

# 备份压缩
mysqldump -uusername -ppassword DatabaseName | gzip > /home/backup/DatabaseName_$(date +%Y%m%d_%H%M%S).sql.gz

# 备份
mysqldump -uusername -ppassword DatabaseName > /home/backup/DatabaseName_$(date +%Y%m%d_%H%M%S).sql

# 备份还原
mysql -u root -p Test<Test0809.sql

# 定时任务 crontab
# crontab -e
# 10 0 * * * /home/backup/bkDatabaseName.sh
# 每天零点十分执行一次
# 日志 tail -f /var/log/cron
40、如何实现对MySQL数据库进行分库加分表备份,请用脚本实现
#!/bin/bash

flag=0
user=root
pass=test

mysql -u$user -p"$pass" -e "show databases;" &>/dev/null
[ $? -ne 0  ] && read -p "Mysql do not running,start it?(`echo -e "\033[32myes/no\033[0m"`):" choice && flag=1
[[ "choice" -eq "yes" ]] && service mysqld start &>/dev/null && flag=0
[ $flag -eq 1 ] && exit 2
database=`mysql -u$user -p$pass  -e "show databases;"|sed 1d|grep -v 'schema'`

echo -e "\033[32m==================backup start=====================\033[0m"
for i in $database
do
  tables=`mysql -u$user -p"$pass" -e "use $i;show tables;"|sed 1d`
  for j in $tables
  do
    mysqldump -u$user -p"$pass"   -B --databases $i --tables $j > /tmp/${i}-${j}-`date +%F`.sql
   [ $? -eq 0 ] && echo $i $j ok >>/tmp/table.log||echo $i $j failed >>/tmp/table.log
   [ $? -eq 0 ] && echo -e "$i $j \033[32mok\033[0m" ||echo -e "$i $j \033[31mfailed\033[0m"
  done

done
echo -e "\033[32m===================backup stop=======================\033[0m"
41、bash for循环打印下面这句话中字母数不大于6的单词。 I am oldboy teacher welcome to oldboy training class.
#!/usr/bin/env bash

input="I am oldboy teacher welcome to oldboy training class. "
arr=($input)
# 数组中所有元素${arr[*]}
for var in  ${arr[*]}
do
# ${#var} 字符串长度
    if [ ${#var} -le 6 ];then
        echo $var
    fi
done
posted @ 2020-02-25 18:06  xyztank  阅读(91)  评论(0)    收藏  举报