文章目录
Linux shell 脚本整理
1. 检查系统版本
#!/bin/bash
# 检查系统版本
function check_version {
VERSION=`awk '{print $1,$4}' /etc/redhat-release | cut -d. -f1`
if [ "$VERSION" == "CentOS 7" ];then
echo "centos 7"
return $VERSION
else [ "$VERSION" == "CentOS 8" ]
echo "this is Centos 8"
fi
}
check_version
2. 判断并配置阿里云 yum 源
#!/bin/bash
# 说明:检查当前yum源是否为阿里云,如果不是则依据系统配置对应的阿里源
# 判断是否安装 wget
rpm -qa | grep wget
[ $? -ne 0 ] && yum install wget -y
# 如果默认源文件存在则备份源文件
if [ -e CentOS-Base.repo ];then
cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
else
echo "Please contact the administrator "
fi
# 判断当前系统版本
NUM=`cat /etc/redhat-release | awk '{print $4}' | cut -d. -f 1`
case $NUM in
7)
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
;;
6)
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
;;
5)
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-5.repo
;;
esac
# 重新加载 yum 源
yum clean all
yum makecache
3. 判断 iconv 支持的字符集中有哪些是可以将指定文件转换为指定字符集的
#!/bin/bash
# 判断 iconv 支持的字符集中有哪些是可以将指定文件转换为指定字符集的
iconv --list | sed 's/\/\/$//' | sort > encodings.list
for a in `cat encodings.list`;do
# echo "$a "
iconv -f $a -t UTF-8 /tmp/22.txt > /dev/null 2>&1 && echo "ok: $a" || echo "fail: $a"
done | tee result.txt
4. 系统初始化脚本
#!/bin/bash
# 说明:linux 系统初始化
#管理安全策略
function close_selinux {
cat /etc/sysconfig/selinux | grep "SELINUX=disabled"
[ $? -ne 0 ] && sed -i.bak 's/^SELINUX=enforcing$/SELINUX=disabled/g' /etc/sysconfig/selinux
reboot
}
# 关闭防火墙
function close_Firewalld {
systemctl stop firewalld
systemctl disable firewalld
}
#设置历史命令时间戳
function set_history_time {
echo 'export HISTTIMEFORMAT="%F %T `whoami`"' >> /etc/profile
#sed -i.bak '$a export HISTTIMEFORMAT="%F %T `whoami`"' /etc/profile
source /etc/profile
}
############################
# 初始化设置固定 ip 地址,并判断是否能够联网
############################
#设置固定 IP 地址
function set_ipaddr {
cat /etc/sysconfig/network-scripts/ifcfg-${ADAPTER_NAME} | egrep '^BOOTPROTO="static"$'
[ $? -ne 0 ] sed -i.bak 's/^BOOTPROTO="dhcp"$/BOOTPROTO="static"/' /etc/sysconfig/network-scripts/ifcfg-$ADAPTER_NAME
cat >> /etc/sysconfig/network-scripts/ifcfg-$ADAPTER_NAME <<EOF
IPADDR="$IPADDR"
GATEWAY="$GATEWAY"
NETMASK="255.255.255.0"
DNS="8.8.8.8"
EOF
systemctl restart network
}
function input_Ipaddr {
# 提示用户在 10 秒内输入地址,超时则继续
read -p 'IPADDR: ' -t 10 IPADDR
read -p 'GATEWAY: ' -t 10 GATEWAY
}
function check_Ipaddr {
ping -c 3 -i 3 www.baidu.com &>/dev/null
if [ $? -eq 0 ]; then
echo "Internet access"
else
echo -e "\033[31m ERROR Network impassability \033[0m"
exit 1
fi
}
function change_Ipaddr {
# 网卡名称
ADAPTER_NAME=`ifconfig | head -1 | awk -F: '{print $1}'`
#ADAPTER_NAME=`ifconfig | awk -F: 'NR==1 {print $1}'`
i=0
while ((i < 3))
do
ipaddr_Input
if [ -n "$IPADDR" ]; then
# 判断输入的 ip 是否满足正则匹配
echo $IPADDR | egrep '(^([1-9]|1[0-9]|1[1-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]{1,2}|1[1-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([0-9]{1,2}|1[1-9]{2}|2[0-5][0-9]|25[0-4])$' >/dev/null
if [ $? -eq 0 ]; then
set_ipaddr
break
else
((i=i+1))
continue
fi
else
((i=i+1))
continue
fi
done
check_Ipaddr
}
##########################################
# 说明:检查当前yum源是否为阿里云,如果不是则依据系统配置对应的阿里源
##########################################
function check_aliyun {
# 判断是否可以联网
check_Ipaddr
# 判断是否安装 wget
rpm -qa | grep wget
[ $? -ne 0 ] && yum install wget -y
# 如果默认源文件存在则备份源文件
if [ -e CentOS-Base.repo ];then
cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
else
echo "Please contact the administrator "
fi
# 判断当前系统版本
NUM=`cat /etc/redhat-release | awk '{print $4}' | cut -d. -f 1`
case $NUM in
7)
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
;;
6)
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
;;
5)
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-5.repo
;;
esac
# 重新加载 yum 源
yum clean all
yum makecache
}
function main {
change_Ipaddr
check_aliyun
set_history_time
close_Firewalld
close_selinux
}
main
5. 磁盘挂载
#!/bin/bash
# vg 卷组名称
vgName="vg_data"
# lv 逻辑卷名称
lvName="lv_data"
# 挂载目录
mountDir="/data"
# 自动对磁盘分区
function diskPartition {
fdisk /dev/$diskName << EOF
n
p
1
t
8e
wq
EOF
# 创建 PV 物理卷
pvcreate /dev/$diskName\1
# 创建 VG 卷组
vgcreate $vgName /dev/$diskName\1
# 查看 VG 大小
vgTotal=`vgdisplay /dev/$vgName | grep -w Total | grep -v grep | awk '{print $3}'`
# 创建 Lv 逻辑卷
lvcreate -n $lvName -l $vgTotal $vgName
# 格式化 LV
mkfs.ext4 /dev/$vgName/$lvName
# 创建挂载目录
if [ -d $mountDir ]; then
echo "/dev/mapper/$vgName-$lvName $mountDir ext4 defaults 0 0" >> /etc/fstab
else
mkdir -p $mountDir
echo "/dev/mapper/$vgName-$lvName $mountDir ext4 defaults 0 0" >> /etc/fstab
fi
mount /dev/$vgName/$lvName /$mountDir
}
# 查看磁盘名称
diskNameList=`lsblk | grep disk | awk '{print $1}'`
for diskName in $diskNameList
do
diskNameNum=`fdisk -l | grep -v grep | grep -c $diskName`
if [ $diskNameNum -eq 1 ]; then
diskPartition
else
echo "$diskName is alery mount"
fi
done
6. 查看指定用户家目录下有多少不属于当前用户的文件或者目录
#!/bin/sh
##################################################################################
# 脚本名称: checkUserDiffFile
# 创建者:dongxx
# 适用平台: AIX/Linux
# 功能描述: 查看系统指定用户家目录下有多少不属于当前用户的文件数量
# 当前版本:v1.0
# 修改历史
#---------------------------------------------------------------------------------
# 日期 版本号 修改人 修改内容
#
##################################################################################
# ################################################################################
# 定义脚本所需参数
# ################################################################################
# 检查时间
vCheckTime=`date "+%F %T"`
# 判断系统
osType=`uname | tr '[a-z]' '[A-Z]'`
# ######################################
# 自定义部分,采集检测值
# ######################################
# 用户存放文件
userFile="/tmp/userNameFile.txt"
# 配置用户
uNameList="user1 user2 user3 user4 user5 user6 user7 user8 user9 user10"
# 将用户写入配置文件
function writeUNameFile {
for uName in $uNameList
do
echo $uName >> $userFile
done
}
# 判断用户文件是否存在,存在防止文件内容错误,将文件删除重新创建
function checkUNameFile {
if [ -f "$userFile" ]; then
rm -rf $userFile
writeUNameFile
else
writeUNameFile
fi
}
# 查看家目录下有多少是不属于当前用户的文件
function checkUserDiffFile_Linux {
while read userName
do
userNum=`cat /etc/passwd | grep -wc ${userName}`
if [ $userNum -ne 0 ]; then
# 这里使用 $1~/^'"${userName}"' 这样的写法是为了防止出现不同用户家目录相同的情况
userHome=`cat /etc/passwd | grep -w ${userName} | awk -F: '$1~/^'"${userName}"'/ {print $6}'`
if [ $userHome != "/" ]; then
if [ -d "$userHome" ]; then
cd $userHome
fileNum=`ls -l | wc -l`
if [ $fileNum -gt 1 ]; then
# 找到用户家目录下不属于当前用户的文件或目录
diffNum=`find $userHome ! -user ${userName} | wc -l`
message="{'key':'"${userName}"','value':'"$userHome\ 下有\ ${diffNum}\ 个不同的文件"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
else
message="{'key':'"${userName}"','value':'"$userHome\ 目录下没有文件"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
else
message="{'key':'"$userName"','value':'"$userHome\ 用户家目录不存在"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
else
message="{'key':'"$userName\ 家目录为\ $userHome\ ,请检查"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
else
message="{'key':'"$userName\ 用户不存在"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
done < ${userFile}
}
function checkUserDiffFile_AIX {
while read userName
do
userNum=`cat /etc/passwd | grep -wc ${userName}`
if [ $userNum -ne 0 ]; then
userHome=`cat /etc/passwd | grep -w ${userName} | awk -F: '$1~/^'"${userName}"'/ {print $6}'`
if [ $userHome != "/" ]; then
if [ -d "$userHome" ]; then
cd $userHome
fileNum=`ls -l | wc -l`
if [ $fileNum -gt 1 ]; then
# 找到用户家目录下不属于当前用户的文件或目录
diffNum=`find $userHome ! -user ${userName} | wc -l`
message="{'key':'"${userName}"','value':'"${userHome}\ 下有\ ${diffNum}\ 个不同的文件"','cptime':'"$vCheckTime"'}"
echo "${message},\c"
else
message="{'key':'"$Object"','value':'"${userHome}\ 目录下没有文件"','cptime':'"$vCheckTime"'}"
echo "${message},\c"
fi
else
message="{'key':'"$userName"','value':'"$userHome\ 用户家目录不存在"','cptime':'"$vCheckTime"'}"
echo "${message},\c"
fi
else
message="{'key':'"$userName\ 家目录为\ $userHome\ ,请检查"','cptime':'"$vCheckTime"'}"
echo "${message},\c"
fi
else
message="{'userName':'"$userName\ 用户不存在"','cptime':'"$vCheckTime"'}"
echo "${message},\c"
fi
done < ${userFile}
}
function main_linux {
echo -e "[\c"
checkUNameFile
checkUserDiffFile_Linux
echo "]"
}
function main_aix {
echo "[\c"
checkUNameFile
checkUserDiffFile_AIX
echo "]"
}
case ${osType} in
LINUX)
main_linux
;;
AIX)
main_aix
;;
*)
echo "[{'key':'"系统检查异常,请联系管理员"','cptime':'"$vCheckTime"'}]"
exit
esac
7. yum 安装 mysql 5.7 版本
#!/bin/bash
#
# 说明:使用 yum 安装 mysql
# 本脚本适用于 centos 7 系统,其他系统未经测试。
# 安装过程中可以通过 tail -f /opt/mysqlInstall/install.log 查看安装日志
MysqlFile="/opt/mysqlInstall"
[ ! -e $MysqlFile ] && mkdir $MysqlFile
MYSQL_LOG=$MysqlFile/install.log
MYSQL_RPM=mysql57-community-release-el7-11.noarch.rpm
MYSQL_URL=https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
# 习惯 root(其实不好)
check_user () {
USER=`whoami`
[ "${USER}" != "root" ] && exit 1
}
check_wget () {
rpm -qa | grep wget &>/dev/null
if [ $? -ne 0 ];then
yum install wget -y &>/dev/null
fi
}
# 配置阿里源
check_yum_aliyun () {
check_wget
AliNUM=`cat /etc/yum.repos.d/CentOS-Base.repo | grep -i aliyun | wc -l`
if [ "${AliNUM}" == "0" ];then
local VERSION=`awk '{print $1,$4}' /etc/redhat-release | cut -d . -f1`
if [ "${VERSION}" == "CentOS 7" ];then
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo &>/dev/null
# 重新加载 yum 源
yum clean all &>/dev/null
yum makecache &>/dev/null
else
echo "Please confirm the system version"
exit 1
fi
fi
}
# 检查 mysql 是否已经安装
check_mysql_install () {
MYSQL_NUM=`rpm -qa | grep mysql | wc -l`
# 注:如果 rpm -Uvh $MYSQL_RPM 这步执行成功 rpm -qa | grep mysql | wc -l 就会有至少一个内容,所以判断 mysql 是否安装需要大于 1,正常安装完成依赖是大于 1 个的
if [ $MYSQL_NUM -gt 1 ];then
echo "mysql is alery install"
exit 1
fi
}
# 安装 mysql
mysql_install () {
check_user
check_yum_aliyun
cd $MysqlFile
if [ -f $MYSQL_RPM ];then
rm -rf $MYSQL_RPM
fi
n=0
while ((n < 2))
do
wget -P $MysqlFile $MYSQL_URL &>$MYSQL_LOG
if [ $? -eq 0 ];then
rpm -Uvh $MYSQL_RPM &>/dev/null
#yum repolist all | grep mysql &>$MYSQL_LOG
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022
i=0
while ((i < 2))
do
yum install mysql-community-server -y &>$MYSQL_LOG
if [ $? -eq 0 ];then
systemctl start mysqld
NUM=`ps -ef | grep mysqld | grep -v grep | wc -l`
if [ ${NUM} -ne 0 ];then
echo "mysql install is sucess"
exit
else
echo "ERROR start mysqld faild ,There are no related processes"
exit
fi
else
if [ $i -lt 2 ]; then
echo "ERROR yum install mysql-community-server is faild ,Try again in 2 seconds"
sleep 2
((i=i+1))
continue
else
echo "ERROR yum install mysql-community-server is faild"
exit
fi
fi
done
else
if [ $n -lt 2 ]; then
echo "wget mysql rpm is faild ,Try again in 2 seconds"
sleep 2
((n=n+1))
continue
else
echo "ERROR yum install mysql-community-server is faild"
exit
fi
fi
done
}
function main {
check_mysql_install
mysql_install
}
main
8. 检查文件权限
#!/bin/sh
##################################################################################
# 脚本名称: checkUserFileRight
# 创建者:xxx
# 适用平台: AIX/Linux
# 功能描述: 查看系统中指定用户家目录的权限是不是为指定权限
# 当前版本:v1.0
# 修改历史
#---------------------------------------------------------------------------------
# 日期 版本号 修改人 修改内容
#
##################################################################################
# ################################################################################
# 定义脚本所需参数
# ################################################################################
# 检查时间
vCheckTime=`date "+%F %T"`
# 判断系统
osType=`uname | tr '[a-z]' '[A-Z]'`
# ######################################
# 自定义部分,采集检测值
# ######################################
# 用户存放文件
userFile="/home/userNameFile.txt"
# 配置用户
uNameList="user1 user2 user3 user4 user5 user6 user7 user8 user9 user10"
# 将用户写入配置文件
function writeUNameFile {
for uName in $uNameList
do
echo $uName >> $userFile
done
}
# 判断用户文件是否存在,存在防止文件内容错误,将文件删除重新创建
function checkUNameFile {
if [ -f "$userFile" ]; then
rm -rf $userFile
writeUNameFile
else
writeUNameFile
fi
}
directoryRight="drwxr-xr-x"
# 检查用户目录是不是 指定 权限
function checkUserDirRight_Linux {
while read userName
do
userNum=`cat /etc/passwd | grep -w ${userName} | awk -F: '$1~/^'"${userName}"'/' | wc -l`
if [ $userNum -ne 0 ]; then
userHomePath=`cat /etc/passwd | grep -w ${userName} | awk -F: '$1~/^'"${userName}"'/ {print $6}'`
if [ $userHomePath != "/" ]; then
# userDir=`cat /etc/passwd | grep -w ${userName} | awk -F: '{print $6}'`
if [ -d "$userHomePath" ]; then
cd $userHomePath
userHomeDir=`echo $userHomePath | awk -F"/" '{print $NF}'`
# -n 判断变量是否为空,防止家目录格式为 /home/user1/ ,这样的话上面的 userHomeDir 就会为空
if [ -n "$userHomeDir" ]; then
userHomeDirName=`ls -l ../ | grep -w $userHomeDir | awk '$1~/^d/ {if ($1 != "'"$directoryRight"'" && $1 != "'"${directoryRight}"'." ) print $NF}'`
if [ -n "$userHomeDirName" ]; then
message="{'key':'"$userName"','value':'"$userHomePath\ 权限不正确"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
else
message="{'key':'"$userName"','value':'"$userHomePath\ 权限检查正常"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
else
# 如果家目录格式为 /home/user1/ 则在取值时需要取倒数第二位的内容
userHomeDir=`echo $userHomePath | awk -F"/" '{print $(NF-1)}'`
userHomeDirName=`ls -l ../ | grep -w $userHomeDir | awk '$1~/^d/ {if ($1 != "'"$directoryRight"'" && $1 != "'"${directoryRight}"'." ) print $NF}'`
if [ -n "$userHomeDirName" ]; then
message="{'key':'"$userName"','value':'"$userHomePath\ 权限不正确"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
else
message="{'key':'"$userName"','value':'"$userHomePath\ 权限检查正常"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
fi
else
message="{'key':'"$userName"','value':'"$userHomePath\ 目录不存在"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
else
message="{'key':'"$userName"','value':'"$userName\ 家目录为\ $userHomePath\ ,请检查"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
else
message="{'key':'"$userName"','value':'"$userName\ 用户不存在"','cptime':'"$vCheckTime"'}"
echo -e "${message},\c"
fi
done < ${userFile}
}
function main_linux {
echo -e "[\c"
checkUNameFile
checkUserDirRight_Linux
echo "]"
}
main_linux
9.在脚本中切换用户执行当前用户
#!/bin/bash
userName=`whoami`
echo $userName
echo 000
if [ $userName == "root" ]; then
su - user1 -s "$(realpath $0)"
exit
fi
echo 111
pwd
echo 222
10. shell脚本超时控制
shell脚本超时控制
写脚本的时候,经常需要用到超时控制。看《shell专家编程》时看到一个好例:修改了一下,
1.超过timeout时间还没执行完,则kill进程,发邮件告警:
set -x
#mailSend()
#{
# mailContent="xxxx Web response time over 5 seconds"
# echo $mailContent | mail -s "xxxxxx Web TimeOut" xxxxx@xxx.cion
#}
mailSend()
{
mailContent="xxxx Web response time over 5 seconds"
echo $mailContent
}
timeout()
{
waitfor=3
# command=$*
command=`sleep 100`
$command &
commandpid=$!
( sleep $waitfor ; kill -9 $commandpid > /dev/null 2>&1 && mailSend ) &
watchdog=$!
sleeppid=$PPID
wait $commandpid > /dev/null 2>&1
kill $sleeppid > /dev/null 2>&1
}
#测试的函数
test123()
{
sleep 20
}
timeout test123
2.超过timeout时间还没执行完,只发邮件告警,程序正常执行:
mailSend()
{
mailContent="xxxxe Web response time over 5 seconds,Please have a check !"
echo $mailContent | mail -s "xxxxx WEB response time over 5 senconds" $mailTo
}
timeout()
{
waitfor=6
command=$*
$command &
commandpid=$!
( sleep $waitfor ; mailSend ) &
watchdog=$!
sleeppid=$PPID
wait $commandpid > /dev/null 2>&1
kill -9 $watchdog > /dev/null 2>&1
kill $sleeppid > /dev/null 2>&1
}
转载于:https://my.oschina.net/u/3415127/blog/1510194