shell脚本实例-系统
更多脚本下载:https://opszzfwordpress.club/script/
1、系统巡检脚本:包括系统负载、内存使用率、分区使用率、僵尸进程、日志报错
#!/bin/bash #usage:巡检脚本 #author:XXX #date:2022.03.25 system_information(){ echo "检查时间:`date +%F`" echo "ip:`ifconfig | awk -F' ' 'NR==2{print $2}'`" echo "主机名:`hostname`" } average_load(){ load1=`uptime | awk -F"[, ]+" '{print $(NF-2)}'` load5=`uptime | awk -F"[, ]+" '{print $(NF-1)}'` load15=`uptime | awk -F"[, ]+" '{print $NF}'` average=`printf "%.2f" "$(echo "scale=2;((${load1}+${load5}+${load15})/3)" | bc)"` cpu_core=`cat /proc/cpuinfo| grep "cpu cores"| uniq | awk -F":" '{print $2}'` cpu_number=`cat /proc/cpuinfo| grep "physical id"| sort| uniq| wc -l` all_cpu_core=`echo "($cpu_core*$cpu_number*2)" | bc` load_com=`expr "$average > $all_cpu_core" | bc` if [ "$load_com" -eq 1 ];then echo "!!!系统负载过高,请注意:$average!!!" else echo "系统负载正常:$average" fi } mem_status(){ total_mem=`free | awk -F" " 'NR==2{print $2}'` availabe=`free | awk -F" " 'NR==2{print $7}'` used=`echo "($total_mem-$availabe)" | bc` percentused=`printf "%.0f" "$(echo "scale=2;($used/$total_mem)*100" | bc)"` C6_buffer_cache=$(free | awk -F" " 'NR==3{print $4}') c6_used=$(echo "($total_mem-$C6_buffer_cache)" | bc) c6_percentused=`printf "%.0f" "$(echo "scale=2;(${c6_used}/${total_mem})*100" | bc)"` version=`cat /etc/redhat-release 2>/dev/null | awk -F" " '{print $(NF-1)}' | awk -F"." '{print $1}'` if [ "$version" == "7" ];then if [ "$percentused" -ge 70 ];then echo "!!!系统内存使用率已达:$percentused%,请注意!!!" elif [ "$percentused" -ge 60 ] && [ "$percentused" -lt 70 ];then echo "!!系统内存使用率已达:$percentused%,请注意!!" elif [ "${percentused}" -ge 50 ] && [ "${percentused}" -lt 60 ];then echo "系统内存使用率已达:$percentused%,请注意!" else echo "系统内存使用率正常:$percentused%" fi else if [ "$c6_percentused" -ge 70 ];then echo "!!!系统内存使用率已达:$c6_percentused,请注意!!!" elif [ "$c6_percentused" -ge 60 ] && [ "$c6_percentused" -lt 70 ];then echo "!!系统内存使用率已达:$c6_percentused,请注意!!" elif [ "$c6_percentused" -ge 50 ] && [ "$c6_percentused" -lt 60 ];then echo "!系统内存使用率已达:$c6_percentused,请注意!#" else echo "系统内存使用率正常:$c6_percentused%" fi fi } Disk_status(){ Disk_value=`df -hP | awk 'NR>2{print line}{line=$0} END{print line}' | awk -F" " '{print $5}' | awk -F"%" '{print $1}' | sort -nr | head -1` Disk_used_70=`df -hP | awk -F"[ %]+" '{if($5>=70) print }' | grep -v Filesystem | awk -F" " '{ print "mounted:" $6 ":" $5 " " "Filesys:"$1 }' | sort -k3 -nr -t":"` Disk_used_60=`df -hP | awk -F"[ %]+" '{if($5>=60) print }' | grep -v Filesystem | awk -F" " '{ print "mounted:" $6 ":" $5 " " "Filesys:"$1 }' | sort -k3 -nr -t":" ` Disk_used_50=`df -hP | awk -F"[ %]+" '{if($5>=50) print }' | grep -v Filesystem | awk -F" " '{ print "mounted:" $6 ":" $5 " " "Filesys:"$1 }' | sort -k3 -nr -t":" ` if [ "$Disk_value" -lt 50 ];then echo "各分区使用率正常" elif [ "$Disk_value" -ge 50 ] && [ "$Disk_value" -lt 60 ];then echo "!分区使用率已高于50%,请注意!" echo "$Disk_used_50" elif [ "$Disk_value" -ge 60 ] && [ "$Disk_value" -lt 70 ];then echo "!!分区使用率已高于60%,请注意!!" echo "$Disk_used_60" elif [ "$Disk_value" -ge 70 ];then echo "!!!分区使用率已高于70%,请注意!!!" echo "$Disk_used_70" fi } zombie=`top -b -n 1 | awk -F"[, ]+" 'NR==2{print $(NF-1)}' | awk -F" " 'NR==1{print $1}'` Zombie_status(){ if [ "$zombie" -eq 0 ];then echo "系统不存在僵尸进程" else echo "!!!存在僵尸进程${zombie}个,请注意!!!" fi } log_error(){ log=`grep -i error /var/log/messages` if [ -n "$log" ];then echo "$log" echo "!日志存在报错,请检查!" else echo "日志无报错" fi } cmd(){ echo "+++++++++++++++++++++++++6+2重要系统巡检情况++++++++++++++++++++++++++++" echo " " echo "--------------------------------检查开始--------------------------------" sleep 2 echo " " echo "################################系统信息################################" sleep 2 system_information echo " " echo "##############################负载负载情况##############################" sleep 2 average_load echo " " echo "###############################内存情况#################################" sleep 2 mem_status echo " " echo "#############################分区使用情况###############################" sleep 2 Disk_status echo " " echo "#############################僵尸进程情况###############################" sleep 2 Zombie_status echo " " echo "#############################错误日志情况###############################" sleep 2 log_error echo " " sleep 2 echo "+++++++++++++++++++++++++检查结束,请关注问题++++++++++++++++++++++++++++" } cmd
2、系统初始化脚本:关闭防火墙selinux;更换yum源,安装epel源;安装基本命令;内核调优;同步时间;更改主机名称;配置登录用户;禁止root用户远程登录;更改端口
#!/bin/bash # #usage:系统初始化安装设置 #关闭防火墙、selinux cat <<EOF 系统初始化包括: 1、关闭防火墙selinux; 2、更换yum源,安装epel源; 3、安装基本命令 4、内核调优 5、同步时间 6、更改主机名称 7、配置登录用户 8、禁止root用户远程登录 9、更改端口 EOF echo "是否继续 [y/n]" while read con;do if [ "$con" = "y" ] || [ "$con" = "" ];then echo "系统初始化现在开始" sleep 2 break elif [ "$con" = "n" ];then echo "现在退出系统初始化" sleep 2 exit 10 else echo "输入错误,请输入y或n" fi done if [ ! -f "/etc/redhat-release" ];then echo "系统不是redhat或centos的,不符合要求" sleep 2 exit 10 fi fire(){ systemctl disable --now firewalld sed -in 's/^SELINUX=.*$/SELINUX=disabled/g' /etc/selinux/config } #更换阿里yum源、安装epel源 Base(){ rm -rf /etc/yum.repos.d/* curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo yum -y install epel-release yum -y remove epel-release yum -y install epel-release } #安装lsof、httpd、vim、ifconfig、wget、iostat、net-tools、telnet、openssl-devel、ntpdate inst(){ yum -y install lsof yum -y install httpd yum -y install vim yum -y install ntpdate yum -y install htop iotop sysstat-10.1.5-19.el7.x86_64 telnet yum -y install net-tools.x86_64 yum -y install lrzsz-0.12.20-36.el7.x86_64 yum -y install wget } #系统调优 #设置好系统最大文件打开数65535 sysctl(){ cat > /etc/security/limits.conf <<EOF * soft nofile 65535 * hard nofile 65535 EOF #设置好常用的内核调优参数 cat > /etc/sysctl.conf <<EOF fs.file-max = 6815744 net.ipv4.tcp_syncookies = 1 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_tw_recycle = 1 net.ipv4.tcp_fin_timeout = 30 net.ipv4.tcp_keepalive_time = 1200 net.ipv4.ip_local_port_range = 10000 65000 net.ipv4.tcp_max_syn_backlog = 8192 net.ipv4.tcp_max_tw_buckets = 5000 EOF #sysctl -p echo "参数配置完成,请重启后生效" sleep 3 #历史命令显示时间HISTTIMEFORMAT="%T %F $(whoame)" export HISTTIMEFORMAT="%F %T" #禁止定时发送邮件MAILTO echo "unset MAILCHECK" >> /etc/profile source /etc/profile } #SSH链接调优、并设置超过五分钟没有动作自动断开,echo “TMOUT=300” >> /etc/profile #echo "TMOUT=300" >> /etc/profile #校正时间 ntp_time(){ ntpdate cn.pool.ntp.org if [ $? -eq 0 ];then echo "successful" fi } echo "是否关闭防火墙及selinux [y/n]" while read A;do if [ "$A" = "y" ] || [ "$A" = "" ];then fire break elif [ "$A" = "n" ];then : break else echo "输入错误,请输入y或n" fi done echo "是否更换国内源,安装epel源 [y/n]" while read B;do if [ "$B" = "y" ] || [ "$B" = "" ];then Base break elif [ "$B" = "n" ];then : break else echo "输入错误,请输入y或n" fi done echo "是否安装命令 [y/n]" while read C;do if [ "$C" = "y" ] || [ "$C" = "" ];then inst break elif [ "$C" = "n" ];then : break else echo "输入错误,请输入y或n" fi done echo "是否进行系统参数调优:内核调优、历史命令显示时间、禁止定时发送邮件 [y/n]" while read D;do if [ "$D" = "y" ] || [ "$D" = "" ];then sysctl break elif [ "$D" = "n" ];then : break else echo "输入错误,请输入y或n" fi done echo "是否校正时间 [y/n]" while read E;do if [ "$E" = "y" ] || [ "$E" = "" ];then ntp_time break elif [ "$E" = "n" ];then : break else echo "输入错误,请输入y或n" fi done #修改系统名称 sys_name(){ echo "请输入系统名称" read AA hostnamectl set-hostname $AA } #创立用户并提权 user_name(){ echo "请输入用户名称" while read BB;do us_na=`grep -w "$BB" /etc/passwd | awk -F":" '{print $1}'` if [ "$BB" = "" ];then echo "值为空,请重新输入" elif [ "$BB" = "$us_na" ];then echo "用户已存在" else useradd $BB break fi done echo "请输入密码" while read -s CC;do echo -e "\n请重新输入密码" read -s PP if [ "$CC" != "$PP" ];then echo -e "\n两次密码不一致" echo -e "\n请输入密码" else echo $CC | passwd --stdin $BB echo "密码设置成功" break fi done echo "是否提权 [y/n]]" while read EE;do sudoerfile="/etc/sudoers.d/$BB" if [ "$EE" = "" ] || [ "$EE" = "y" ];then echo "$BB ALL=(ALL) NOPASSWD: ALL" >> $sudoerfile break elif [ "$E" = "n" ];then : break else echo "输入错误,请输入y或n" fi done } #禁止root远程登录 Permit_root(){ sshdfile="/etc/ssh/sshd_config" sed -i "s/^#PermitRootLogin yes/PermitRootLogin no/g" $sshdfile systemctl restart sshd } #修改端口 PORT(){ sshdfile="/etc/ssh/sshd_config" echo "请输入端口号" while read DD;do n1=`echo $DD | sed 's/[0-9]//g'` port_num=`netstat -antp | awk -F" " '{print $4}' | grep -wc ${DD}` if [ ! -z $n1 ];then echo "格式不正确,请重新输入" elif [ "$DD" = "" ];then echo "值为空,请重新输入" elif [ "$DD" -lt 1 ] || [ "$DD" -gt 65535 ];then echo "输入的端口号不在范围内" elif [ "$port_num" -gt 0 ];then echo "端口已被占用" else sed -i "s/^#Port.*$/Port $DD/g" $sshdfile break fi done } echo "是否进行用户、系统名称、端口设置 [y/n]" read F if [ "$F" = "y" ] || [ "$F" = "" ];then : else echo "退出初始化设置" sleep 2 exit 10 fi echo "是否修改系统名称 [y/n]" read G if [ "$G" = "y" ] || [ "$G" = "" ];then sys_name fi echo "是否创建用户 [y/n]" read H if [ "$H" = "y" ] || [ "$H" = "" ];then user_name else : fi echo "是否禁止root远程登录 [y/n]" read J if [ "$J" = "y" ] || [ "$J" = "" ];then Permit_root else : fi echo "是否修改端口号 [y/n]" read K if [ "$K" = "y" ] || [ "$K" = "" ];then PORT else : fi echo "配置已完成,是否重启系统 [y/n]" read L if [ "$L" = "y" ] || [ "$L" = "" ];then echo "现在重启系统" sleep 5 reboot else echo "系统初始化已完成" fi
3、建立/删除逻辑卷:执行建立/删除脚本,按照提示输入逻辑卷名称、大小、挂载目录等信息
#!/bin/bash echo "现在开始划分逻辑卷" sleep 2 echo "请输入逻辑卷名称" read LVS if [ "$LVS" = "" ];then echo "值为空,请检查" exit 99 fi echo "请输入逻辑卷大小" read LVSIZE if [ "$LVSIZE" = "" ];then echo "值为空,请检查" exit 99 fi echo "请输入挂载目录,格式/\$dir/\$dir" read DIR if [ "$DIR" = "" ];then echo "值为空,请检查" exit 99 fi echo "请输入文件系统,ext4、xfs" read filesys if [ "$filesys" = "" ];then echo "值为空,请检查" exit 99 fi value_name=`lsblk | grep disk | awk '{print substr($1,1,1)}' | head -1` value_disk=`lsblk | grep disk | awk '{print $1}' | grep -v "${value_name}da"` Disk_create(){ if [ ! -b "/dev/${value_disk}1" ];then fdisk /dev/$value_disk &>/dev/null <<EOF n p wq EOF fi } Disk_create pv_create(){ pvs | grep "$value_disk" &>/dev/null if [ $? -ne 0 ];then pvcreate /dev/${value_disk}1 if [ $? -ne 0 ];then echo '物理卷创建失败,请检查' sleep 2 exit 10 fi else echo "物理卷已存在" fi } pv_create vg_create(){ vgs | grep 'vg_data' &>/dev/null if [ $? -ne 0 ];then vgcreate vg_data /dev/${value_disk}1 if [ $? -ne 0 ];then echo '卷组创建失败,请检查' sleep 2 exit 10 fi else echo '卷组已存在' fi } vg_create lv_judge(){ lvs | awk 'NR>2{print line}{line=$0} END{print line}' | awk '{print $1}' | grep -w "$LVS" >/dev/null &> /dev/null if [ $? != 0 ];then echo "逻辑卷名称没有问题" else echo "逻辑卷名称已存在,请更换" exit 99 fi } lv_judge dir(){ if [ ! -d $DIR ];then echo "现在开始建立目录" mkdir $DIR else dir_num=`ls $DIR | wc -l` if [ "$dir_num" != 0 ];then echo "挂载目录存在文件,请检查" exit 99 fi fi check_dir=`mount | awk -F" " '{print $3}' | grep -w "$DIR" | wc -l` if [ "$check_dir" != 0 ];then echo "目录已被挂载,请检查" exit 99 fi } dir lv_cre(){ lvcreate -L +$LVSIZE -n $LVS vg_data &>/dev/null if [ $? = 0 ];then echo "逻辑卷建立成功" else echo "逻辑卷建立失败,请检查" exit 99 fi } lv_cre lv_mou(){ fst="/dev/vg_data/$LVS $DIR $filesys defaults 0 0" mkfs.$filesys /dev/vg_data/$LVS &>/dev/null if [ $? = 0 ];then echo "格式化成功" else echo "格式化失败,请检查" exit 99 fi echo "$fst" >> /etc/fstab mount -a if [ $? = 0 ];then echo "逻辑卷挂载成功" else echo "逻辑卷挂载失败,请检查" sed "/$fst/d" /etc/fstab exit 99 fi } lv_mou #if [ $? = 0 ];then # echo "逻辑卷创建成功" #fi
#!/bin/bash echo "现在开始删除逻辑卷" sleep 2 echo "请输入逻辑卷名称" read lvm if [ "$lvm" = "" ];then echo "值为空,请检查" exit 99 fi DIR=`df -h | grep -wi $lvm | awk '{print $NF}'` #临时卸载逻辑卷 umount $DIR if [ $? -eq 0 ];then echo "逻辑卷临时卸载成功" else echo "逻辑卷临时卸载失败,请检查" exit 99 fi #永久卸载,注释掉fstab中相关内容 sed -i "/\/dev\/vg1\/$lvm/d" /etc/fstab if [ $? -eq 0 ];then echo "逻辑卷卸载成功" else echo "逻辑卷卸载失败,请检查" exit 99 fi #删除逻辑卷 lvremove /dev/vg1/$lvm -y if [ $? -eq 0 ];then echo "逻辑卷删除成功" else echo "逻辑卷删除失败,请检查" exit 99 fi echo "是否删除$DIR目录 yes|no" read DEL if [ "$DEL" = yes ];then echo "现在删除$DIR目录" rm -rf $DIR echo "目录删除成功" else echo "不能删除目录,请检查" fi
4、生成随机数设置密码,执行方式:sh pass_user.sh $user_name(用户名称,自动判断是否已经建立)
#!/bin/bash #建立用户生成随机密码 PASS=`openssl rand -base64 20 | cut -c 5-15` user_name=$1 if [ "$user_name" == "" ];then echo "!!User name is null,please check!!" exit fi id $user_name &>/dev/null if [ $? -eq 0 ];then read -p "$user_name is exist,whether to repair $user_name password [y/n]" REPA if [ "$REPA" = "y" ];then : elif [ "$REPA" = "n" ];then echo "!!Exit!!" exit 10 else echo "!!Error,exit!!" exit 10 fi else read -p "$user_name is not exist,whether to set up [y/n]" USET if [ "$USET" = "y" ];then echo "set up user now" useradd $user_name &>/dev/null elif [ "$USET" = "n" ];then echo "!!Exit!!" exit 10 else echo "!!error,exit!!" exit 10 fi fi echo "$PASS" | passwd --stdin $user_name &>/dev/null echo "The $user_name password is:$PASS"
5、批量创建用户并设置密码
首先在脚本的同一目录下创立userlist文件,并将需要建立的用户名称写进去
执行create_user.sh脚本
在同目录下的passlist.txt文件中查看新建立的用户密码
#!/bin/bash #批量创建用户并设置密码 if [ ! -f "userlist.txt" ];then echo "!!userlist is not exist,please check!!" exit 10 fi user_file=`cat userlist.txt` #pass=`head -c 20 /dev/urandom | base64 | cut -c 5-19` for i in $user_file;do useradd $i &>/dev/null if [ $? -eq 0 ];then echo "$i set success" else echo "!!$i is failed to create,please check!!" continue fi for A in `head -c 20 /dev/urandom | base64 | cut -c 5-19`;do echo $i password: $A >> passlist.txt echo "$A" | passwd --stdin $i &>/dev/null done done echo "please view password in passlist.txt"
检测主机是否存活,先在/root下建立一个ip.txt的文件,将要检测的主机ip填进去,然后执行脚本
#!/bin/bash echo "###The script is begining to execute###" server_ip=`cat /root/ip.txt` for ip in $server_ip;do ping -c2 $ip &>/dev/null if [ $? -eq 0 ];then echo "$ip connect" >> /tmp/`date +%F`_ip.txt else echo "$ip disconnect" >> /tmp/`date +%F`_ip.txt fi done echo "###The script is finsihed to execute###"
6、系统工具箱脚本
执行方式:sh systatus [options] num 1 num 2
options:
all:输出所有参数的内容
clo:系统负载数值情况
cuse:系统cpu占用情况
muse:系统内存占用情况
swu:系统swap分区占用情况
psd:系统D状态进程情况
help:查看帮助
num1:指定执行循环间隔时间:默认间隔时间为5s
num2:指定执行循环次数,默认循环执行5次
脚本内容:systatus
7、DNS解析判断
判断DNS是否可以解析为指定ip
需要在脚本的同一路径下,将域名以及希望解析的ip地址写入 "domain_list.txt" 文件中
#!/bin/bash IFS=$'\n' domain_all=`cat domain_list.txt | grep -v "^#"` ##读取域名解析列表文件 if [ ! -n "$domain_all" ];then echo "error: domain name list not exist" exit 11 fi num=1 checknum=1 for i in ${domain_all};do domain=`echo "$i" | awk '{print $1}'` ip=`echo "$i" | awk '{print $2}'` ##判断列表文件中ip是否为空 if [ ! -n "$ip" ] ;then if [ "$checknum" = 1 ];then ip_new="$domain" else ip_new="$ip_old\n$domain" ##将ip为空的域名记录下来 fi ip_old="$domain" let checknum++ fi nslookup $domain | grep -w "$ip" &>/dev/null ##判断域名是否可以解析为指定的ip if [ $? -ne 0 ];then if [ "$num" = 1 ];then dom_new="$domain - $ip" else dom_new="$dom_old\n$domain - $ip" ##将解析异常的域名,ip记录下来 fi dom_old="$domain - $ip" let num++ fi done if [ -n "$ip_new" ] || [ -n "$dom_new" ];then ##输出解析异常的域名,ip if [ -n "$ip_new" ];then echo "----domain name not point ip----" echo -e "$ip_new" echo '' fi if [ -n "$dom_new" ];then echo "----domain name reslove error----" echo -e "$dom_new" fi exit 21 fi