Linux之Shell小程序(持续更新中)

列表:

1, 新装Centos系统环境快速部署
2, 查看linux系统各项系统信息
3, 统计文件空行总数
4, 检测硬盘利用率,如果超过百分之17就报警,并发送wall
5, 添加一个用户
6, 文件类型判断
7, 判断某ip是否在线
8, 显示两个文件空行数的和
9, 选择yes or no
10,批量改某路径下的文件名后缀(更改后的文件名粉色显示)
10,CentOS7 系统中 /data/路径下有大量的 jpg 小图片文件, 文件名称都是以 4 位小写字符加 4 位数字构成的,请编写一个 shell 或者 python 脚本将文件前四个小写字符相同的文件移动到以这四个字母为名字的文件夹中
11,求1-100的和(for)= seq -s + 100 | bc =echo {1..100} | tr " " + |bc
12,批量创建用户and批量删除用户(可以合成一个脚本,$0 create|del)
13,并发扫描多网段IP是否在线
14,小星星之一闪一闪亮晶晶
15,九九乘法表(正反)
16,打印等腰三角形
17,猜数字(1-10)
18,创建用户(shift)
19,监控http服务运行状况(while)
20,根据访问lastb,禁止10次以上ip访问(while)
21,磁盘利用率报警(while read)
22,点菜(select menu in ...)-可用于多脚本合成
23,比较两个参数的大小与阶乘(函数调用脚本)
24,fork bomb(自调用)
25,10个随机数取最大值最小值(for)
26,10个随机数取最大值最小值(数组)
27,10个随机数冒泡排序(数组)
28,编写脚本id.sh,计算/etc/passwd⽂件中的第5个⽤户和第9个⽤户和第15⽤户的ID之和。(eval)
29,创建一位数字加两个随机字母.html 如: 1Ab.html
30,破解已知md5sum加密字符串对应的RANDOM值
31,CA自签名证书,申请证书和颁发证书
32,SSH批量基于Key验证传送公钥至多台主机

1,新装Centos系统环境快速部署(基于两块网卡,内卡和外卡,否则YUM源检测会卡住):注意事项,虚拟机额里两块网卡会出现故障,重启后会造成ssh无法连接,手动重启网络才可以。可能是虚拟的两块网卡,另一个块没有MAC地址?

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-03-20
#FileName:                  My_Work_Environment.sh
#URL:                       https://blog.51cto.com/5033330 
#
#Desciption:                This script can quick set your work environment(Centos6,7 or other) ~/.vimrc
#
#                           When you use this Shell Script,Please make sure your ~/.bashrc not set any alias 
#                           or other,this script will overwrite ~/.bashrc
#
#                           login user is root.   
#
#                               if your system ver is 7,this script will create /etc/profile.d/environment.sh , 
#                           set the PS1 style,the HISTSIZE=2000,LANG=EN,add /data/script36 to PATH ,rename ens33 
#                           to eth0.and some alias
#                               if your system ver is 6,just like 7 but excetp rename
#
#                           Login user is common user
#                               just set some alias and set PS1 style.
#
#                           After run , source ./etc/profile.d/environment.sh or ~/.bashrc the PS1 style will change.
#                           
#Copyright(c)               2019 All rights reserved
#---------------------------------------

#set -e
#set -u
release7=7
release6=6
Start_Color="\e[1;31m"
End_Color="\e[0m"
Sysver=`cat /etc/redhat-release | grep -o "\<[1-9]\+\>"| head -1`
IPADDR7='IPADDR=172.16.36.102'
IPADDR6='IPADDR=172.16.36.103'
NETMASK='NETMASK=255.255.255.0'
GATEWAY='GATEWAY=172.16.36.1'
PackageName="gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel systemd-devel zlib-devel vim lrzsz tree screen lsof tcpdump wget ntpdate net-tools iotop bc zip unzip nfs-utils apr-devel apr-util-devel"
DIR="/data"

cat > ~/.vimrc << EOF
set ts=4
set paste
set cursorline
set softtabstop=4
set expandtab
set shiftwidth=4
set autoindent
autocmd BufNewFile *.sh exec ":call SetTitle()"
func SetTitle()
        if expand("%:e") == 'sh'
        call setline(1,"#!/bin/bash")
        call setline(2,"#")
        call setline(3,"#---------------------------------------")
        call setline(4,"#Author:                    MartinHe")
        call setline(5,"#Date:                      ".strftime("%Y-%m-%d"))
        call setline(6,"#FileName:                  ".expand("%"))
        call setline(7,"#URL:                       https://blog.51cto.com/5033330 ")
        call setline(8,"#Desciption:                The test Scirpt")
        call setline(9,"#Copyright(c)               ".strftime("%Y")." All rights reserved")
        call setline(10,"#---------------------------------------")
        call setline(11,"")
        endif
endfunc
autocmd BufNewFile * normal G
EOF

if [ ! -e /$DIR/script36 ];then 
    mkdir /$DIR/script36
    fi

if [ `id -u` = 0 ];then

    if [ "$Sysver" = "7" ];then
cat>/etc/profile.d/environment.sh<<EOF
alias cdnet="cd /etc/sysconfig/network-scripts"
alias editnet7="vim /etc/sysconfig/network-scripts/ifcfg-ens33"
alias diskscan2="echo - - - > /sys/class/scsi_host/host2/scan"
alias diskscan1="echo - - - > /sys/class/scsi_host/host1/scan"
alias diskscan0="echo - - - > /sys/class/scsi_host/host0/scan"
export PS1="\[\e[1;31m\][\d \A\n \[\e[1;32m\]\u\[\e[0m\]\[\e[1;35m\]@\h \[\e[1;33m\]\w]\\$ \[\e[0m\]"
export LANG=en_US.utf8
export HISTSIZE=2000
export HISTTIMEFORMAT="%F %T "
export PATH=/data/scripts36:'$PATH'
EOF

    grep "ifnames=0" /etc/default/grub &> /dev/null || sed -r -i.bak '/linux16.*/s@.*quiet@& net.ifnames=0@' /boot/grub2/grub.cfg &> /dev/null

    grep "ONBOOT=yes" /etc/sysconfig/network-scripts/ifcfg-ens33 &> /dev/null || sed -r -i.bak '/BOOTPROTO/s@(BOOTPROTO=).*$@\1static@;/DEVICE/s@(DEVICE=).*$@\1eth0@;/ONBOOT/s@(ONBOOT=).*$@\1yes@' /etc/sysconfig/network-scripts/ifcfg-ens33

    grep "IPADDR" /etc/sysconfig/network-scripts/ifcfg-ens33 &> /dev/null || echo -e "$IPADDR7\n$NETMASK\n$GATEWAY" >> /etc/sysconfig/network-scripts/ifcfg-ens33

    grep "^SELINUX=disabled" /etc/selinux/config &> /dev/null || sed -r -i.bak '/^SELINUX=/s@(SELINUX=).*@\1disabled@' /etc/selinux/config

    systemctl stop firewalld.service &>/dev/null
    systemctl disable firewalld.service &>/dev/null

   [ -e /etc/yum.repos.d/backup ] && cp -au /etc/yum.repos.d/* /etc/yum.repos.d/backup &>/dev/null || mkdir /etc/yum.repos.d/backup &> /dev/null;mv /etc/yum.repos.d/* /etc/yum.repos.d/backup &> /dev/null

    echo -e "$Start_Color Begain create YUM!!! $End_Color"

cat>/etc/yum.repos.d/base.repo<<EOF
[base]
name=Base $release7
baseurl=file:///media/cdrom
gpgcheck=0
cost=10

[epel]
name=aliyun epel
baseurl=https://mirrors.aliyun.com/epel/$release7/x86_64/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7
enabled = 0
cost=100
EOF

    echo -e "$Start_Color Create YUM Finish!!!$End_Color"

    [ ! -e /media/cdrom ] && mkdir /media/cdrom || true &>/dev/null
    mount /dev/sr0 /media/cdrom &> /dev/null

    echo "/dev/sr0  /media/cdrom iso9660 defaults 0 0" >> /etc/fstab

    echo -e "$Start_Color Beagin Install Package!!!$End_Color"

    echo -e "$Start_Color Wait for a moment!!!$End_Color"

    yum clean all &>/dev/null
    yum repolist all &>/dev/null
    yum install $PackageName -y

    echo -e "$Start_Color Finish Install Package,All Environment is set,Enjoy It!!!$End_Color"

    elif [ "$Sysver" = "6" ];then
cat>/etc/profile.d/environment.sh<<EOF
alias cdnet="cd /etc/sysconfig/network-scripts"
alias editnet6="vim /etc/sysconfig/network-scripts/ifcfg-eth0"
alias diskscan2="echo - - - > /sys/class/scsi_host/host2/scan"
alias diskscan1="echo - - - > /sys/class/scsi_host/host1/scan"
alias diskscan0="echo - - - > /sys/class/scsi_host/host0/scan"
export PS1="\[\e[1;31m\][\d \A\n \[\e[1;33m\]\u\[\e[0m\]\[\e[1;36m\]@\h \[\e[1;35m\]\w]\\$ \[\e[0m\]" 
export LANG=en_US.utf8
export HISTSIZE=2000
export HISTTIMEFORMAT="%F %T "
export PATH='/data/scripts36:$PATH'
EOF

    grep "BOOTPROTO=dhcp" /etc/sysconfig/network-scripts/ifcfg-eth0 &> /dev/null && sed -r -i.bak '/BOOTPROTO/s@(BOOTPROTO=).*$@\1static@;/DEVICE/s@(DEVICE=).*$@\1eth0@;/ONBOOT/s@(ONBOOT=).*$@\1yes@' /etc/sysconfig/network-scripts/ifcfg-eth0

    grep "IPADDR" /etc/sysconfig/network-scripts/ifcfg-eth0 &> /dev/null || echo -e "$IPADDR6\n$NETMASK\n$GATEWAY" >> /etc/sysconfig/network-scripts/ifcfg-eth0

    grep "^SELINUX=disabled" /etc/selinux/config &> /dev/null || sed -r -i.bak '/^SELINUX=/s@(SELINUX=).*@\1disabled@' /etc/selinux/config

    service network restart &> /dev/null
    service iptables stop &> /dev/null
    service iptables off &> /dev/null

    [ -e /etc/yum.repos.d/backup ] && cp -au /etc/yum.repos.d/* /etc/yum.repos.d/backup &>/dev/null || mkdir /etc/yum.repos.d/backup &> /dev/null;mv /etc/yum.repos.d/* /etc/yum.repos.d/backup &> /dev/null

echo -e "$Start_Color Begain create YUM!!! $End_Color"

cat>/etc/yum.repos.d/base.repo<<EOF
[base]
name=Base $release6
baseurl=file:///media/cdrom
gpgcheck=0
cost=10

[httpd]
name=httpd $release6
baseurl=http://172.16.36.102/Centos/$release6/x86_64/
gpgcheck=0
cost=10

[epel]
name=aliyun epel
baseurl=https://mirrors.aliyun.com/epel/$release6/x86_64/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7
enabled = 0
cost=100
EOF

    echo -e "$Start_Color Create YUM Finish!!!$End_Color"

    [ ! -e /media/cdrom ] && mkdir /media/cdrom || true &>/dev/null
    mount /dev/sr0 /media/cdrom &> /dev/null

    echo "/dev/sr0  /media/cdrom iso9660 defaults 0 0" >> /etc/fstab >/dev/null

    echo -e "$Start_Color Beagin Install Package!!!$End_Color"

    echo -e "$Start_Color Wait for a moment!!!$End_Color"

    yum clean all &>/dev/null
    yum repolist all &>/dev/null
    yum install $PackageName -y    

    echo -e "$Start_Color Finish Install Package,All Environment is set,Enjoy It!!!$End_Color"

    elif [[ "$Sysver" -gt "7" ]] && [[ "$Sysver" -lt "6" ]];then
cat>/etc/profile.d/environment.sh<<EOF
alias cdnet="cd /etc/sysconfig/network-scripts"
alias editnet7="vim /etc/sysconfig/network-scripts/ifcfg-ens33"
alias editnet6="vim /etc/sysconfig/network-scripts/ifcfg-eth0"
export PS1="\[\e[1;31m\][\d \A\n \[\e[1;33m\]\u\[\e[0m\]\[\e[1;36m\]@\h \[\e[1;35m\]\w]\\$ \[\e[0m\]" 
export LANG=en_US.utf8
export HISTSIZE=2000
export HISTTIMEFORMAT="%F %T "
export PATH=/data/scripts36:'$PATH'
EOF
    fi

else

    cp ~/.bashrc ~/.bashrc.bak

cat >~/.bashrc<<EOF
# .bashrc
# User specific 
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
alias scpp='scp -r wang@172.22.149.168:/data/script36 /root'
alias cdnet="cd /etc/sysconfig/network-scripts"
alias editnet7="vim /etc/sysconfig/network-scripts/ifcfg-ens33"
alias editnet6="vim /etc/sysconfig/network-scripts/ifcfg-eth0"
export LANG=en_US.utf8
export HISTSIZE=2000
export HISTTIMEFORMAT="%F %T "
export PATH=/data/scripts36:'$PATH'
EOF

    if [ "$Sysver" = "7" ];then
    echo 'export PS1="\[\e[1;31m\][\d \A\n \[\e[1;32m\]\u\[\e[0m\]\[\e[1;35m\]@\h \[\e[1;33m\]\w]\\$ \[\e[0m\]"' >> ~/.bashrc

    else
    echo 'export PS1="\[\e[1;31m\][\d \A\n \[\e[1;33m\]\u\[\e[0m\]\[\e[1;36m\]@\h \[\e[1;35m\]\w]\\$ \[\e[0m\]"' >> ~/.bashrc
    fi
fi
unset Sysver
unset release
unset Start_Color
unset End_Color
unset IPADDR7
unset IPADDR6
unset NETMASK
unset GATEWAY
unset PackageName

2,查看linux系统信息

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-03-16
#FileName:                  systeminfo.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
export Start_Color="\e[1;32m"
export End_Color="\e[0m"
Ipaddr=`ifconfig | grep -Eo --color=auto "(\<([1-9]|[1-9][0-9]|[1-9][0
-9]{2}|2[0-4][0-9]|25[0-5])\>\.){3}\<([1-9]|[1-9][0-9]|[1-9][0-9]{2}|2
[0-4][0-9]|25[0-5])\>"| head -1`
Version=`cut -d" "  -f4 /etc/redhat-release`
KerneVer=`uname -r`
Cpu_Info=`lscpu | grep "Model name:"|tr -s " " |cut -d: -f2`
Mem_Info=`free -mh|tr -s " "|cut -d" " -f2 |head -2| tail -1`
HD_Info=`lsblk | grep "^sd\{1,\}"| tr -s " "|cut -d" " -f1,4`
echo -e "The System Hostname is : $Start_Color `hostname` $End_Color"
echo -e "The System IP ADDER is : $Start_Color $Ipaddr $End_Color"
echo -e "The System Version  is : $Start_Color $Version $End_Color"   
echo -e "The System kerneVer is : $Start_Color $KerneVer $End_Color"
echo -e "The System Cpu_Info is :$Start_Color $Cpu_Info $End_Color"
echo -e "The System Mem_Info is : $Start_Color $Mem_Info $End_Color"
echo -e "The System HD_Info  is : $Start_Color \n$HD_Info $End_Color"
disk.sh
unset Start_Color
unset End_Color
unset Ipaddr
unset Version
unset KerneVer
unset Cpu_Info
unset Mem_Info
unset HD_Info

Linux之Shell小程序(持续更新中)


3,统计文件空行总数

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-03-20
#FileName:                  argsum.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
if [ $# -lt 1 ];then
    echo "At least one argument(must be file)."
    exit 10
elif [ -e $1 ] && [ -f $1 ];then
    Space_Line=`grep "^$" $1 | wc -l`
    echo "the $1 has ${Space_Line} space line"                        
fi

Linux之Shell小程序(持续更新中)


4,检测硬盘利用率,如果超过百分之17就报警,并发送wall

#!/bin/bash                                                           
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-03-20
#FileName:                  checkdisk.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
Use_disk=`df |grep "^/dev/sd"| grep -Eo "\<[0-9]+\>%"|tr -d %|sort -nr
|head -1`
[ $Use_disk -ge 17 ] && wall "space will full"

Linux之Shell小程序(持续更新中)


5,添加一个用户

#!/bin/bash                                                                                                      
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-03-20
#FileName:                  createuser.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
read -p "Please input a username: " USER
if id $USER &> /dev/null;then
    echo "the user is exist"
else
    useradd $USER &> /dev/null
    echo "add $USER successful"
fi

Linux之Shell小程序(持续更新中)


6,文件类型判断

#!/bin/bash                                                                                                      
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-03-20
#FileName:                  filetype.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
read -p "Plesa input(example: /etc/passwd or /etc ...) : " PATHH
if [ -z "$PATHH" ];then
    echo "there must be a filename argument"
        exit 1
elif [ ! -e "$PATHH" ];then
    echo "No such file,Are You Kidding Me?"
        exit 1
else
a=`ls -l $PATHH|grep -o "^."`
case $a in
-)
echo "common file" ;;
d)
echo "directory file" ;;
b)
echo "block file" ;;
l)
echo "sybolink file" ;;
s)
echo "socket file" ;;
p)
echo "pipe file" ;;
c)
echo "character file" ;;
*)
echo "other file" ;;
esac
fi

Linux之Shell小程序(持续更新中)


7,某ip是否在线

ping -c1 -W1 $1 &> /dev/null && echo "$1 is up" || echo "$1 is donw"

8,显示两个文件空行的和

#!/bin/bash                                                                                                      
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-03-19
#FileName:                  sumspace.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
if [ $# -lt 2 ];then
    echo "Usage: sumspace.sh /PATH/TO/SOMEFILE /PATH/TO/SOMEFILE"
    exit 10
elif [ $# -gt 2 ];then
    echo "two argument only."
    exit 20
else
    FILE1=`grep "^$" $1|wc -l`
    FILE2=`grep "^$" $2|wc -l`
    SPACE_SUM=$[$FILE1+$FILE2]
    echo "The Space SUM is: $SPACE_SUM."
fi

Linux之Shell小程序(持续更新中)


9,选择YES or NO

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-03-20
#FileName:                  yesorno.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
read -p "Do you agree?(yes or NO):" ANS
ans1=`echo $ANS | grep -E -i "^[y]([e][s])?$"|tr [:upper:] [:lower:]`
ans2=`echo $ANS | grep -E -i "^[n][o]$"|tr [:upper:] [:lower:]`
if [ "$ans1" = "yes" ];then
    echo "It's ok"
    exit
elif [ "$ans2" = "no" ];then
    echo "It's not ok"
    exit
else
    echo "Wrong input"
fi

Linux之Shell小程序(持续更新中)

10,批量改某路径下的文件名后缀(更改后的文件名粉色显示)

DIR=/data/script36/workdir/
cd $DIR
END=log
BC="\e[1;"
EC="\e[0m"
for file in *;do
    file_name=`echo $file | sed -r 's@^(.*)\..*$@\1@'`
    mv $file ${file_name}.$END
    echo -e "${BC}31m $file $EC is rename ${BC}35m ${file_name}.$END $EC success"                                                                 
done

10,CentOS7 系统中 /data/路径下有大量的 jpg 小图片文件, 文件名称都是以 4 位小写字符加 4 位数字构成的,请编写一个 shell 或者 python 脚本将文件前四个小写字符相同的文件移动到以这四个字母为名字的文件夹中

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-05-28
#FileName:                  archive.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
DIR=/tmp
cd $DIR
for k in `ls -1 | while read filename;do echo ${filename:0:4};done | sort -u`;do 
mkdir $k
done
for i in *.jpg;do
    mv $i ${i:0:4}
done
#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-05-28
#FileName:                  archive.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
DIR=/tmp
cd $DIR
ls -1 | grep -oE '^[[:alpha:]]+' |sort -u | xargs mkdir                                                                
for i in *.jpg;do
    mv $i ${i:0:4}
done

11,求1-100的和(for)(while)= seq -s + 100 | bc =echo {1..100} | tr " " + |bc

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-07
#FileName:                  sum100.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
sum=0
for i in `seq 100`;do
    let sum+=i
done
    echo "The sum(1..100) is $sum" 
#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-07
#FileName:                  sum100_for.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------

for ((sum=0,i=0; i<=100; i++));do
    let sum+=i
done
echo "the sum(1-100) is $sum"
#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-08
#FileName:                  sum100_while.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
sum=0
i=1
while [ $i -le 100 ];do
    let sum+=i
    let i++                                                                                                                                       
done
    echo "the sum(1-100) is $sum"

12,批量创建用户and批量删除用户(可以合成一个脚本,$0 create|del)

批量创建用户 首先定义一个userlist.txt

#!/bin/bash                                                                                                                                       
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-07
#FileName:                  createuser.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
BC="\e[1;"
EC="\e[0m"
for user in `cat /data/script36/userlist.txt`;do
    if id $user &> /dev/null;then
        echo -e "${BC}32m $user ${BC}5;31m exist $EC"
    else
        useradd $user
        echo $user | passwd --stdin $user &> /dev/null
        echo -e "${BC}32m $user $EC create successed"
    fi
done

批量删除用户,也需要定义一个userlist.txt

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-07
#FileName:                  deluser.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
BC="\e[1;"
EC="\e[0m"
for user in `cat /data/script36/userlist.txt`;do
    if id $user &> /dev/null;then
        userdel -r $user
        echo -e "${BC}32m $user delete success!!! $EC"                                                                                            
    else
        echo -e "${BC}32m $user ${BC}5;31m not exist!!! $EC"
    fi
done

13,并发扫描多网段IP是否在线

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-07
#FileName:                  scanip.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
NET=172.22
for SUBNET in {0..255};do
    {
    for HOST in {1..254};do
        { ping -c1 -W1 $NET.$SUBNET.$HOST &> /dev/null && echo $NET.$SUBNET.$HOST is up || echo $NET.$SUBNET.$HOST is down; }&
    done
    }&                                                                                                                                            
done
wait
echo "scan host ip is finished"

14,小星星之一闪一闪亮晶晶

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-07
#FileName:                  star.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
read -p "Please input Column num:" col
read -p "Please input Line num:" line
#col=10
#line=10
BC="\e[1;5;"
for i in `seq $line`;do
    for j in `seq $col`;do
        COL=$[RANDOM%7+31]m
        echo -e "${BC}${COL}*\c"
    done
echo -e "\e[0m"
done

15,九九乘法表(正反)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-07
#FileName:                  9x9.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
col=9
for ((i=1;i<=9;i++));do
    for ((j=1;j<=$i;j++));do
    echo -e "$j*$i=$[j*i]\t\c"                                                                                                                    
    done
    #echo "$i"
    echo
done
#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-07
#FileName:                  9x9_rev.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
col=9
for ((i=9;i>=1;i--));do                                                                                                                           
    for ((j=1;j<=$i;j++));do
    echo -e "$j*$i=$[j*i]\t\c"                                                                                                                    
    done
    #echo "$i"
    echo
done

16,打印等腰三角形

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-04
#FileName:                  showstar.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
read -p "please input the Line num:" line
read -p "please input the Column num:" col
#read -p "please input the light:" lnum                                                                                                           
#总行
#line=9 
#总列
#col=9 
# i是当前行号 每行打印的星星数位2i-1 
# space空格数为line减去当前的i行号
for i in `seq $line`;do
    light=
    space=$[line-i]
    star=$[2*i-1]
    for j in `seq $space`;do echo -e " \c"; done
    for k in `seq $star`;do  echo -e "*\c";done
    echo
done

17,猜数字(1-10)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-09
#FileName:                  guessnum.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
NUM=$[RANDOM%10+1]
while true ; do
    read -p "Please guess a num(1-10):" num
    if [ $num -lt $NUM ];then
        echo "$num small than the guess num"
    elif [ $num -gt $NUM ];then
        echo "$num bigger than the guess num"
    else
        echo "yeah,you are right"
        break
    fi
done

18,创建用户(shift)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-09
#FileName:                  createuser_shift.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
if [ -z "$1" ];then
    echo "Usage:`basename $0` username ..."
    exit
fi
while [ "$1" ];do
    if id $1 &> /dev/null;then
        echo "$1 is exist"
    else
        useradd $1
        echo $1 is added
    fi
    shift
done

19,监控http服务运行状况(while)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-09
#FileName:                  monitor.httpd_while.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
SLEEPING=20
SERVICE=httpd
LOG=/var/log/monitor_$SERVICE.log
while true;do
    if killall -0 $SERVICE &> /dev/null;then
        true
    else
        systemctl restart $SERVICE
        echo "AT `date +'%F %T'` $SERVICE restart" | tee -a $LOG | mail -s "warning $SERVICE" root
    fi
    sleep $SLEEPING
done

20,根据访问lastb,禁止10次以上ip访问(while)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-10
#FileName:                  denyip_while.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
LOG=cat /data/script36/ss.log | sed -nr '/^ESTAB/s@.* ([0-9.]+):[0-9]+.* ([0-9.]+):[0-9]+.*$@\2@p'| sort | uniq -c
cat $LOG | while read num ip;do
    if [ $num -gt 10 ];then
        iptables -A INPUT -s $ip -j REJECT
    fi
done

21,磁盘利用率报警(while read)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-08
#FileName:                  diskcheck_while.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
df | while read line;do
    DEVICE=echo $line | sed -nr '/^\/dev\/sd/s@([^ ]+).* ([0-9]+).*$@\1@p'
    USED=echo $line | sed -nr '/^\/dev\/sd/s@([^ ]+).* ([0-9]+).*$@\2@p'
    if [ $USED -gt 80 ];then
        wall $DEVICE will be full:$USED
    fi
done

22,点菜(select menu in ...)-可用于多脚本合成

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-10
#FileName:                  menu_select.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
# REPLY 是程序内部变量,用于存储用户输入的选项
PS3="Please choose a num which one you want to do: "
select menu in suancaiyu kaoquanyang yangxiezi huoguo quit;do
    case $menu in
    suancaiyu)
        echo "$menu 30 yuan"
        echo you input is $REPLY
        ;;
    kaoquanyang)
        echo "$menu 600 yuan"
        echo you input is $REPLY
        ;;
    yangxiezi)
        echo "$menu 150 yuan"
        echo you input is $REPLY
        ;;
    huoguo)
        echo "$menu 100 yuan"
        echo you input is $REPLY
        ;;
    quit)
        echo you input is $REPLY
        break
        ;;
    *)
        echo "Wrong choose,stupid!!!"
    esac
done
echo "Good job"

23,比较两个参数的大小与阶乘(函数调用脚本)

函数定义 functions

is_digit () {
    while [ "$1" ];do
        [[ ! "$1" =~ ^[0-9]+$ ]] && { echo input not a digit;return 1; }
        shift
    done                                                                                                                                          
    return
}

compare () {
    is_digit $*
    [ "$?" -eq 1 ] && return
    if [ "$1" -gt "$2" ];then
        echo $1
    else
        echo $2
    fi
}

jiecheng () {
    if [ $1 -eq 1 ];then
    echo 1
    else
        echo $[`jiecheng $[$1-1]`*$1]
    fi
}

正式脚本compare.sh

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-10
#FileName:                  compare.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
. functions
compare $1 $2 

正式脚本jiecheng.sh

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-10
#FileName:                  jiecheng.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
. functions
jiecheng $1 

24,fork bomb

:(){ :|:& };:
bomb() { bomb | bomb & }; bomb

脚本实现Bomb.sh无限调用自己,且后台执行

#!/bin/bash
./$0|./$0&

25,10个随机数取最大值最小值(for数组)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-09
#FileName:                  paixu.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
for ((i=0;i<10;i++));do
    N=$RANDOM
    if [ $i -eq 0 ];then
        MAX=$N
        MIN=$N
    else
        [ $N -gt $MAX ] && MAX=$N
        [ $N -lt $MIN ] && MIN=$N
    fi
    echo -e "$N \c"
done
echo
echo MAX=$MAX MIN=$MIN

26,10个随机数取最大值最小值(数组)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-10
#FileName:                  shuzu.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
declare -a ATTR
declare -a maopao
for ((i=0;i<10;i++));do
    ATTR[$i]=$RANDOM
    if [ $i -eq 0 ];then
        MAX=${ATTR[$i]}
        MIN=${ATTR[$i]}
    else
        [ ${ATTR[$i]} -gt $MAX ] && MAX=${ATTR[$i]}
        [ ${ATTR[$i]} -lt $MIN ] && MIN=${ATTR[$i]}
    fi
done
echo all random num is ${ATTR[*]}
echo the MAX=$MAX MIN=$MIN

27,10个随机数冒泡排序(数组)

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-10
#FileName:                  maopao.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
declare -a maopao
for ((i=0;i<10;i++));do
     maopao[$i]=$RANDOM
done
echo the RANDOM=${maopao[*]}
    for((j = 0 ; j<$[${#maopao[*]}-1]; j++));do
       # //每次内循环的比较,从0索引开始, 每次都在递减
        for((k= 0 ; k<$[${#maopao[*]}-j-1]; k++));do
          #  //比较的索引,是k和k+1
        if [ ${maopao[k]} -gt ${maopao[k+1]} ];then
            temp=${maopao[$k]}
            maopao[$k]=${maopao[$k+1]}
            maopao[$k+1]=$temp
        fi
        done
    done
echo the maopao=${maopao[*]}

28,编写脚本id.sh,计算/etc/passwd⽂件中的第5个⽤户和第9个⽤户和第15⽤户的ID之和。

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-10
#FileName:                  id1.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
sumuid=0
for i in 5 9 15;do                                                    
    uid=`eval sed -nr '${i}p' /etc/passwd|cut -d: -f3`
    let sumuid+=uid
done
echo $sumuid

29,创建一位数字加两个随机字母.html 如: 1Ab.html

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-11
#FileName:                  html.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
for i in $(seq 2);do
    name=`echo "${i}$(tr -cd [[:alpha:]] < /dev/urandom | head -c 2).html"`
    touch /data/$name
    echo "$name is created"
done

30,破解已知md5sum加密字符串对应的RANDOM值

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-11
#FileName:                  pojiemd5.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
ps1=efbaf275cd
#ps2=4be9c40b8b
#ps3=44b2395c46
#ps4=f8c8873ce0
#ps5=b902c16c8b
#ps6=ad865d2f63
echo 'num' 'random'
time=1
for i in {0..32767};do
    if [ $time -gt 1 ];then
        break
    fi
    ps=$(echo $i | md5sum | cut -c1-10)
    for j in $ps1;do
    if [ $ps == $j ];then
        echo $i $ps
        let time++
    fi
        done
done

31,CA自签名证书,申请证书和颁发证书

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-19
#FileName:                  CA_create.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------

# 根CA创建函数,内部定义自行修改
creatCA () {

expect<<EOF
spawn openssl req -new -x509 -key $DIR/private/cakey.pem -out $DIR/cacert.pem -days 3650
expect {
"Country Name" { send "CN\n";exp_continue } 
"State or Province Name" { send "beijing\n";exp_continue }
"Locality Name" { send "beijing\n";exp_continue }
"Organization Name" { send "martinhe\n";exp_continue }

"Organizational Unit Name" { send "m36\n";exp_continue}  
"Common Name" { send "ca.martinhe.com\n";exp_continue }
"Email Address" { send "admin@martinhe.com\n" }
}
    expect eof
EOF

}

# 使用私钥生成证书申请csr文件,内部定义自行修改
applyCA () {

expect<<EOF                                                                                             
spawn openssl req -new  -key ./${KEY}.key -out ./${KEY}.csr 
expect {
"Country Name" { send "CN\n";exp_continue } 
"State or Province Name" { send "beijing\n";exp_continue }
"Locality Name" { send "haidian\n";exp_continue }
"Organization Name" { send "martinhe\n";exp_continue }
"Organizational Unit Name" { send "m36_devops\n";exp_continue}  
"Common Name" { send "m36.martinhe.com\n";exp_continue }
"Email Address" { send "m36@martinhe.com\n" ;exp_continue }
"A challenge password" { send "\n";exp_continue }
"An optional company name" { send "\n" }
}                                                                                                           
        expect eof
EOF

}

BC="\e[1;32m"
EC="\e[0m"

PS3="Please choose a num which one you want to do: "

DIR="/etc/pki/CA"

select menu in createCA applyCA awardCA quit;do

case $menu in

createCA)
touch $DIR/{index.txt,serial}
echo 01 > $DIR/serial
(umask 066;openssl genrsa -out $DIR/private/cakey.pem 4096) &> /dev/null
 creatCA
   ;;

applyCA)
    echo -e "${BC}please input a private key name: ${EC}\c";read KEY
    (umask 066;openssl genrsa -out ${KEY}.key 1024)
    applyCA
    echo -e "${BC}please input the CA server IP: ${EC}\c"; read IP
    scp ${KEY}.csr ${IP}:
    ;;

awardCA)
        echo
    ls /root/*.csr
        echo
    echo -e "${BC}please input the csr name to ward(such as test): ${EC}\c";read CSR
    openssl ca -in /root/${CSR}.csr  -out $DIR/certs/$CSR.crt -days 100
  ;;
    quit)
        echo you input is $REPLY
        break
        ;;
    *)
        echo -e "${BC}Wrong choose,stupid!!!${EC}"
    esac
done

32,SSH批量基于Key验证传送公钥至多台主机。

iplist.txt

172.16.100.100
172.16.100.101

#!/bin/bash
#
#---------------------------------------
#Author:                    MartinHe
#Date:                      2019-04-19
#FileName:                  push_ssh_key.sh
#URL:                       https://blog.51cto.com/5033330 
#Desciption:                The test Scirpt
#Copyright(c)               2019 All rights reserved
#---------------------------------------
#!/bin/bash
user=root
password=centos
ssh-keygen -t rsa -N '' -f /root/.ssh/id_rsa
while read ip;do
expect <<EOF
set timeout 20
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $user@$ip
expect {
"yes/no" { send "yes\n";exp_continue }
"password" { send "$password\n" }
}
expect eof
EOF
done < iplist.txt 

转载于:https://blog.51cto.com/5033330/2367417

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值