shell实例

简介: shell实例

1.显示系统一些基本信息
可以将该脚本加入到开机自启动里面,这样开机就会输出基本信息

!/bin/bash

info(){
system=$(hostnamectl | grep System | awk '{print $3}')
kernel_release=$(hostnamectl | grep Kernel | awk -F : '{print $2}')
Virtualization=$(hostnamectl | grep Virtualization | awk '{print $2}')
server_name=$(hostname)
ipaddr=$(hostname -I)
echo "当前系统版本是:${system}"
echo "当前系统内核是:${kernel_release}"
echo "当前虚拟平台是:${Virtualization}"
echo "当前主机名是:${server_name}"
echo "当前ip地址:${ipaddr}"
}
checkerrror(){
error_info=$(dmesg | grep error)
if [ ! -e ${error_info} ]
then
echo "无错误日志!"
else
echo ${error_info}
fi
}
info
checkerrror
2.关闭系统防火墙和SELinux
检查防火墙状态,是否安装防火墙,如果安装则关闭、关闭SELinux、清空iptables规则

!/bin/bash

close_firewalld(){
code=$(systemctl status firewalld)
if [ ${code} -eq 0 ]
then
systemctl stop firewalld
fi
}
close_selinux(){
sed -i '/^SELINUX/s/=./=disabled/' /etc/selinux/config
setenforce 0
}
close_iptables(){
iptables -F
service iptables save
service iptables restart
}
close_firewalld
close_selinux
close_iptables
3.定时任务计划:归档备份
打包压缩/var/log/nginx目录下所有内容,存放在/tmp/nginx目录里
压缩文件命名规范:yymmdd_logs.tar.gz,只保存七天内的文件,超过七天的文件会进行清理

!bin/bash

date="$(date +%Y%m%d)"
dir='/tmp/nginx'
backupfile='_logs.tar.gz'

查看/tmp/nginx是否存在,不存在则创建

checkbak(){
if [ ! -e ${dir} ]
then
mkdir ${dir}
fi
}

压缩文件

backup(){
tar -zcvf
d
i
r
/
{date}${backupfile} /var/log/nginx/ > /dev/null 2>&1
echo "${backupfile} Compressed and packaged successfully !"
}

清除七天过期文件

cleanup(){
find ${dir} -type f -mtime +7 | xagrs rm -rf
if [ $? -eq 0 ]
then
echo "Cleaned up successfully!"
else
echo "data cleaning failed error, please pay attention in time"
fi
}
checkbak
backup
cleanup
4.自动批量创建用户
批量创建user1、user2、user3.....

!/bin/bash

检查用户是否存在,不存在则创建

checkuser(){
for i in $(seq 1 20)
do
id user${i} > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "user${i} 已存在!"
else
useradd user{i} && echo "user
{i}" | passwd --stdin user${i} > /dev/null 2>&1
fi
done
}
checkuser
5.通过位置参数创建用户
$1 是执行脚本的第一个参数
$2 是执行脚本的第二个参数

!/bin/bash

checkuser(){
id ${1} > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "${1} 已存在!"
else
useradd "$1"
echo "
2
"
|
p
a
s
s
w
d


s
t
d
i
n
"
1"
fi
}
6.批量删除用户
批量删除user1...user20

!/bin/bash

检查用户是否存在,存在则删除

checkuser(){
for i in $(seq 1 20)
do
id user${i} > /dev/null 2>&1
if [ $? -eq 0 ]
then
userdel -r user${i}
else
echo "user${i} 不存在!"
fi
done
}
checkuser
7.更新系统时间,并写入硬件时间里
查看是否安装ntpdate工具
创建上海时区文件的软链接
更新时间并写入到硬件时间里

!/bin/bash

package="ntpdate"
info=
(
r
p
m

q
{package})
check_pkgs(){
if [ -e ${info} ]
then
echo "ntpdate already exists!"
else
echo "start installation!"
yum clean all > /dev/null 2>&1
fi
yum update -y && yum install -y ${package} > /dev/null 2>&1
fi
}
modify_time(){
echo "开始修改时间"
rm -rf /etc/localtime && ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
/usr/sbin/ntpdate cn.pool.ntp.org > /dev/null 2>&1 && hwclock -w
}
check_pkgs
modify_time
8.检查服务运行状态
检查某一服务是否正常运行,执行脚本的时候第一个参数为服务名

!/bin/bash

result=
(
p
i
d
o
f
1 | wc -l)

echo ${result}

if [ ${result} -eq 0 ]
then
echo "service does not exist !"
else
echo "Service is running normally !"
fi
9.对目标主机进行心跳检测
ping目标主机看是否ping得通,三次ping通表示主机正常运行
将目标主机的ip地址作为第一个参数传进去

!/bin/bash

ipaddr=$1
echo ${ipaddr}
ping_status(){
if ping -c 1 ${ipaddr} > /dev/null 2>&1
then
echo "ping ${ipaddr} is successful!"
continue
fi
}
for i in $(seq 1 3)
do
ping_status
echo "ping ${ipaddr} is failure!"
done
进阶版:对ip地址池里的主机分别进行心跳检测
ipaddr=(192.168.149.131 192.168.149.130 192.168.149.132 192.168.149.133)
for i in ${ipaddr[]}
do
echo ".... begin to ping ${i} ....."
if ping -c 3 ${i} > /dev/null 2>&1
then
echo "ping ${i} is successful!"
else
echo "ping ${i} is failure!"
fi
done
10.系统磁盘内存容量告警
根分区剩余空间小于20%(即使用空间大于80%) 输出告警信息
内存使用空间大于80% 输出告警信息
配合crond每5分钟检查一次

!/bin/bash

disk_letfspace=$(df -Th | grep -w / | awk '{print$6}' | cut -d % -f 1)
mem_used=$(free -m | grep Mem | awk '{print$3}')
mem_total=$(free -m | grep Mem | awk '{print$2}')
mem_letfspace=
[
{mem_used}*100/${mem_total}]
if [ ${disk_letfspace} -gt 80 ] #-gt大于
then
echo "Disk free space is less than 20%!"
else
echo "${disk_letfspace}% of disk space left"
fi
if [ ${mem_letfspace} -gt 80 ]
then
echo "memory space is less than 20%!"
else
echo "${mem_letfspace}% of memory space left"
fi

添加定时任务

crontab -l
/5 * /root/check_space.sh
11.操作系统信息提取

!/bin/bash

清除屏幕信息

clear
if [[ $# -eq 0 ]]
then

系统类型

os=$(uname -o)
echo "Operating System Type:" $os

系统版本和名字

os_name=$(cat /etc/issue | grep -e "Server")
echo "Check OS Release Version and Name:" $os_name

cpu架构信息

architecture=$(uname -m)
echo "Check Architecture:" $architecture

操作系统内核版本

kernerrelease=$(uname -r)
echo "Check Knerner release:" $kernerrelease

主机名

hostname=$(uname -n)
echo "Check Hostname:" $hostname

内网ip

internelip=$(hostname -I)
echo "Check Internel ip" $internalip

公网ip

externalip=$(curl -s http://ipecho.net/plain)
echo "Check External ip:" $externalip

dns信息

nameservers=$(cat /etc/resolv.conf | grep -E "<nameserver[ ]+" |awk '{print $NF}')
echo "Check DNS:" $nameservers

是否已连接到Internet

ping -c 2 baidu.com &>/dev/null && echo "Internet:Connectd" || echo "Internet:Disconnected"

检查用户登录数

who>/tmp/who
echo "Logged In Users" && cat /tmp/who
rm -f /tmp/who

#

操作系统运行状态

系统使用内存=Total-Free

应用使用内存=Total-(Free+Cached+Buffers)

system_mem_usages=$(awk '/MemTotal/{total=$2}/MemFree/{free=$2}END{print (total-free)/1024}' /proc/meminfo)
echo "system memuserages " $system_mem_usages
app_mem_usages=$(awk '/MemTotal/{total=$2}/MemFree/{free=$2}/^Cache/{caches=$2}/Buffers/{buffers=$2}END{print (total-free-cached-buffers)/1024}' /proc/meminfo)
echo "apps memuserages " $app_mem_usages

cpu负载

loadaverage=$(top -n 1 -b | grep "load average:" | awk '{print
11
12 $13}')
echo "load averages" $loadaverage

磁盘使用量

diskaverage=$(df -h | grep -vE 'Filesystem|tmpfs' | awk '{print
1
""
5}')
echo "disk averages " $diskaverage
fi
12.第三方服务监控

!/bin/bash

Nginxserver="http://192.168.47.128/nginx_status"
Check_Nginx_Server()
{
Status_code=
(
c
u
r
l

m
5

s

w
{Nginxserver} -o /dev/null)
if [
S
t
a
t
u
s
c
o
d
e

e
q
000

o
Status_code -ge 500 ];then
echo -e "Check http server erro,Response status code is" $Status_code
else
Http_content=
(
c
u
r
l

s
{Nginxserver})
echo -e "Check http server ok!\n" $Http_content
fi
}
Check_Nginx_Server
13.收集内核信息

! /bin/bash

main()
{
if [ ! "ls -A /usr/src/" == "" ];then
mkdir kernel_header
cp -rf /usr/src/ kernel_header > /dev/null 2>&1 && echo "collect kernel headers done"
cp /etc/release kernel_header > /dev/null 2>&1 && echo "collect release version done"
uname -a >>"kernel_header/uname" 2>&1
uname -r >>"kernel_header/uname" 2>&1
uname -m >>"kernel_header/uname" 2>&1
echo "collect uname version done"
which dpkg >> "kernel_header/package" 2>&1
which apt >> "kernel_header/package" 2>&1
which rpm >> "kernel_header/package" 2>&1
which yum >> "kernel_header/package" 2>&1
echo "collect package manager done"
tar zcf kernel_header.tar.gz kernel_header --remove-files
echo "collect kernel header success, please copy $(pwd)/kernel_header.tar.gz"
else
echo "/usr/src is empty, collect kernel header failed!"
fi
}
main

  1. 复制命令及其依赖到指定目录

    !/bin/bash

    #
    变量声明
    #

    如果用户没有输入目标路径,将使用如下路径

    DIR=/mnt/tmp

    提示信息

    prompt_1="Pls run as root user"
    prompt_2="路径名不能是/根目录,已将文件拷贝到默认路径"
    prompt_3="输入的命令名不正确,或者输入了多个命令名,请重新输入一个命令名"
    prompt_4="只能使用一个路径且不能是/根目录或包含空格,已将文件拷贝到默认路径"
    prompt_5="只能输入一个命令名,不能包含空格"
    #
    函数
    #

    . /etc/init.d/functions

    复制命令

    cpcmd(){
    local cmdpath=
    2
    (dirname which --skip-alias $1)
    [ -d
    c
    m
    d
    p
    a
    t
    h
    ]
    |
    |
    m
    k
    d
    i
    r

    p
    cmdpath
    cp -a which --skip-alias
    1
    cmdpath
    [ ? -eq 0 ] && action "
    1 finish copy" true || action "$1 finish copy" false
    }

    复制库

    cplib(){
    local libs=
    (
    l
    d
    d
    w
    h
    i
    c
    h


    s
    k
    i
    p

    a
    l
    i
    a
    s
    1| egrep -o "/[^ ]+")
    for i in $libs;do
    local libpath=dirname $i
    [ -d
    2
    libpath ] || mkdir -p
    2
    libpath
    cp
    i
    {2}${libpath}
    done
    [ ? -eq 0 ] && action "
    1's dependent libs finish copy" true || action "$1's dependent libs finish copy" false
    }
    #
    主体部分
    #

    判断是否是管理员

    [ $UID -ne 0 ] && { echo "$prompt_1"; exit; }

    如果命令行没有传参,提示用户重新输入

    flag=0
    while [ $flag -ne 1 ]; do
    if [ $# -eq 2 ];then
    which --skip-alias $1 &>/dev/null
    [ $? -ne 0 ] && { echo -e "\033[1;33mUsage: $0 [CMD] [PATH]\033[0m";exit 1; }
    cmd=$1

    判断输入的路径是否是根目录

    path=$2
    [ "$path" == "/" ] && { path=
    D
    I
    R
    ;
    e
    c
    h
    o

    e
    "
    \0
    33
    [
    1
    ;
    33
    m
    {prompt_2}$DIR \033[0m"; }
    flag=1
    else

    1.提示用户输入命令名

    while : ; do
    read -p "[1;32m请输入需要拷贝的命令(quit退出)[0m " cmd
    [[ "$cmd" == " " ]] && { echo -e "\033[1;33m$prompt_5\033[0m"; continue; }

    判断用户输入的是否是quit,是则退出

    tmp=${cmd^^}
    [ "$tmp" == "QUIT" ] && exit
    which --skip-alias $cmd &>/dev/null
    [ $? -eq 0 ] && break
    echo -e "\a\033[1;31m${prompt_3}\033[0m"
    done

    2.提示用户输入目标路径(默认路径$DIR):

    read -p "[1;32m请输入需要拷贝的目标路径(默认路径$DIR):[0m " path
    [ "
    p
    a
    t
    h
    "=="
    /
    "
    ]
    |
    |
    [
    [
    "
    path" == " " ]] && { path=
    D
    I
    R
    ;
    e
    c
    h
    o

    e
    "
    \0
    33
    [
    1
    ;
    33
    m
    {prompt_4}$DIR \033[0m"; }
    path=${path:=$DIR}
    [ -d
    p
    a
    t
    h
    ]
    |
    |
    m
    k
    d
    i
    r

    p
    path
    fi

    3.拷贝命令到指定目录

    cpcmd
    c
    m
    d
    path

    4.拷贝函数到指定目录

    cplib
    c
    m
    d
    path
    done
    15.重启脚本(指定重启次数和间隔时间)

    !/bin/bash

    rootPWD="testpass"
    logFile=$PWD/reboot.log
    inputSTR[0]="#!/bin/bash"
    inputSTR[1]="source /opt/times.left"
    inputSTR[2]="rm -rf /opt/times.left"
    inputSTR[3]="if [ ${timesLeft} -gt '0' ];then"
    inputSTR[4]=" echo "还剩余
    t
    i
    m
    e
    s
    L
    e
    f
    t




    ">>
    {logFile}"
    inputSTR[5]=" date >> ${logFile}"
    inputSTR[6]=" echo >> ${logFile}"
    inputSTR[7]=" echo "timesLeft=$((timesLeft-1))" > /opt/times.left"
    inputSTR[8]=" reboot"
    inputSTR[9]="else"
    inputSTR[10]=" sed -i '/./rbt.sh/d' /etc/crontab"
    inputSTR[11]=" rm -rf /opt/rbt.sh"
    inputSTR[12]=" chown
    U
    S
    E
    R
    :
    {USER} ${logFile}"
    inputSTR[13]="fi"
    echo -n -e "请输入自动重启的次数:\t"
    read timesLeft
    echo "timesLeft=
    t
    i
    m
    e
    s
    L
    e
    f
    t
    ">
    PWD/times.left
    echo
    r
    o
    o
    t
    P
    W
    D
    |
    s
    u
    d
    o

    S
    m
    v
    PWD/times.left /opt/times.left &> /dev/null
    echo -n -e "请输入重启间隔的时间(分钟):\t"
    read interval
    echo -e "Checking necessary files for auto rebooting ..."
    if [ ! -f /opt/rbt.sh ];then
    for ((i=0; i<${#inputSTR[@]}; i++))
    do
    echo
    i
    n
    p
    u
    t
    S
    T
    R
    [
    $
    i
    ]

    >
    PWD/rbt.sh
    done
    echo
    r
    o
    o
    t
    P
    W
    D
    |
    s
    u
    d
    o

    S
    m
    v
    PWD/rbt.sh /opt/rbt.sh
    echo ${rootPWD} | sudo -S chown root:root /opt/rbt.sh
    echo ${rootPWD} | sudo -S chmod a+x /opt/rbt.sh
    fi
    echo -e "\e[1;32m[ REBOOT SCRIPT OK]\e[0m"
    oldIFS=$IFS
    IFS=$'\n'
    cfgOK=$(cat /etc/crontab | grep "./rbt.sh")
    if [ ! ${cfgOK} ];then
    echo
    r
    o
    o
    t
    P
    W
    D
    |
    s
    u
    d
    o

    S
    s
    e
    d

    i
    "
    a/${interval:=2} * root cd /opt && ./rbt.sh" /etc/crontab
    fi
    IFS=$oldIFS
    echo -e "\e[1;32m[CRONTAB CONFIG OK]\e[0m"
    echo -n "请稍候,系统即将重启中……"
    read

16.关机、重启、待机、休眠测试

!/bin/bash

uid=echo "$UID";
if [ $uid -ne 0 ];then
zenity --info --text="该程序每次以ROOT身份执行";
exit;
fi;
SHUTDOWN="关机测试";
REBOOT="重启测试";
SUSPEND="待机测试";
SLEEP="休眠测试";
echo logname >/tmp/lognames;
usrname=cat /tmp/lognames;
echo "chmod 666 /sys/class/rtc/rtc0/wakealarm " >> /etc/rc.local;
SELECTION=zenity --list --radiolist --title="测试工具" --text="选择您想操作的一项功能" --column "" --column "请您选择" True "
S
H
U
T
D
O
W
N
"
F
a
s
l
e
"
REBOOT" Fasle "$SUSPEND"
Fasle "$SLEEP"
if [ -e $SELECTION ] ; then
exit;
fi
if [ "
S
E
L
E
C
T
I
O
N
"="
SHUTDOWN" ] ;then
echo -e -n "[daemon]\n TimedLoginEnable=true\n TimedLogin=$usrname\n TimedLoginDelay=0">>/etc/gdm/custom.conf;
chmod 666 /etc/gdm/custom.conf;
TestNo=zenity --entry --text="请您输入需要关机测试的次数";
if [ -e $TestNo ] ;then
exit
fi
echo $TestNo > /tmp/LogBootNo;
chmod 666 /tmp/LogBootNo;
echo "BootReplace.sh" >>/etc/rc.local;
BootTest.sh;
fi
if [ "
S
E
L
E
C
T
I
O
N
"="
REBOOT" ]; then
echo -e -n "[daemon]\n TimedLoginEnable=true\n TimedLogin=$usrname\n TimedLoginDelay=0">>/etc/gdm/custom.conf;
chmod 666 /etc/gdm/custom.conf;
TestNo=zenity --entry --text="请您输入需要重启测试的次数";
if [ -e $TestNo ] ;then
exit
fi
echo $TestNo > /tmp/LogRebootNo;
chmod 666 /tmp/LogRebootNo;
echo "RebootReplace.sh" >>/etc/rc.local;
RebootTest.sh;
fi
if [ "
S
E
L
E
C
T
I
O
N
"="
SUSPEND" ] ;then
TestNo=zenity --entry --text="请您输入需要待机测试的次数";
if [ -e $TestNo ] ;then
exit
fi
echo $TestNo > /tmp/LogSuspendNo;
chmod 666 /tmp/LogSuspendNo;
SuspendTest.sh;
fi

if [ "

S
E
L
E
C
T
I
O
N
"="
SLEEP" ] ;then
TestNo=zenity --entry --text="请您输入需要休眠测试的次数";

if [ -e $TestNo ] ;then

exit
fi
echo $TestNo > /tmp/LogSleepNo;
chmod 666 /tmp/LogSleepNo;
SleepTest.sh;

fi

17.读取1.txt文本并输出其内容

!/bin/bash

while语句应用

while read line
do
echo $line
done < 1.txt
18.示例2

!/bin/sh

xrdp X session start script (c) 2015, 2017 mirabilos

published under The MirOS Licence

if test -r /etc/profile; then
. /etc/profile
fi
if test -r /etc/default/locale; then
. /etc/default/locale
test -z "${LANG+x}" || export LANG
test -z "${LANGUAGE+x}" || export LANGUAGE
test -z "${LC_ADDRESS+x}" || export LC_ADDRESS
test -z "${LC_ALL+x}" || export LC_ALL
test -z "${LC_COLLATE+x}" || export LC_COLLATE
test -z "${LC_CTYPE+x}" || export LC_CTYPE
test -z "${LC_IDENTIFICATION+x}" || export LC_IDENTIFICATION
test -z "${LC_MEASUREMENT+x}" || export LC_MEASUREMENT
test -z "${LC_MESSAGES+x}" || export LC_MESSAGES
test -z "${LC_MONETARY+x}" || export LC_MONETARY
test -z "${LC_NAME+x}" || export LC_NAME
test -z "${LC_NUMERIC+x}" || export LC_NUMERIC
test -z "${LC_PAPER+x}" || export LC_PAPER
test -z "${LC_TELEPHONE+x}" || export LC_TELEPHONE
test -z "${LC_TIME+x}" || export LC_TIME
test -z "${LOCPATH+x}" || export LOCPATH
fi
if test -r /etc/profile; then
. /etc/profile
fi
test -x /etc/X11/Xsession && exec /etc/X11/Xsession
exec /bin/sh /etc/X11/Xsession

19、记录远程登录信息

!/bin/bash

PS1="whoami@hostname:"'[$PWD]'
history
USER_IP=who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'
echo $USER_IP
if [ "$USER_IP" = "" ]
then
USER_IP=hostname
fi
if [ ! -d /tmp/ruige ]
then
mkdir /tmp/ruige
chmod 777 /tmp/ruige
fi
if [ ! -d /tmp/ruige/${LOGNAME} ]
then
mkdir /tmp/ruige/${LOGNAME}
chmod 300 /tmp/ruige/${LOGNAME}
fi
export HISTSIZE=4096
DT=date '+%Y:%m:%d %r'
export HISTFILE="/tmp/ruige/
L
O
G
N
A
M
E
/
{USER_IP} ruige.$DT"
echo $HISTFILE
chmod 600 /tmp/ruige/${LOGNAME}/ruige 2>/dev/null

20、查找/tmp下大于1K的文件,并复制到/tmp1下

!/bin/bash

dir1="/tmp/"
for file in ls $dir1
do
if [ -f
d
i
r
1
file ];then
size1=ls -l
d
i
r
1
file|awk -F ' ' '{print $5}'
if [ $size1 -gt 102420 ];then
cp
d
i
r
1
file /tmp1/
fi
fi
done
或者 find /tmp -siez +1K -exec cp {} /tmp1 \;
补充:如何将目录及子目录下的大于1K文件复制到/tmp1下

21、添加一个新组为 class01,然后,添加属于这个组的 30 个用户,用户名的形式为 stdXX,其中,XX 从 01 到 30

!/bin/bash

usergroup class01
num=$(seq -w 1 1 30)
for i in $num
do
echo $i

useradd std$i -G class01

done
或者
seq -f "std%02g" 1 1 30|useradd -G class01

22、从 a.log 文件中提取包含“WARNING”或”FATAL”,同时不包含“IGNOR”的行,然后提取以“:”分割的第五个字段
grep -E 'WARNING|FATAL' a.log|grep -v 'IGNOR'|awk -F ':' '{print $5}'

23、在每个月的第一天备份并压缩/etc 目录下的所有内容,存放在/root/backup 目录里,且文件名为如下形式 yymmdd_etc,yy 为年,mm 为月,dd 为日。shell 程序 fileback存放在/usr/bin 目录下?
cd /usr/bin
vim fileback

!/bin/bash

cd /root/backup
tar -zcf date +%y%m%d"_etc.tgz" /etc

    • 1 /usr/bin/fileback >> /var/spool/cron/crontabs/root #写入root用户下的定时任务
      24、编写个 shell 脚本将当前目录下大于 10K 的文件转移到/tmp 目录下

      /bin/bash

      for FileName in ls -l |awk '$5>10240 {print $9}'
      do
      mv $FileName /tmp
      done

定时任务题
某系统管理员需每天做一定的重复工作,请按照下列要求,编制一个解决 方案 :
(1)在下午 4 :50 删除/abc 目录下的全部子目录和全部文件;
(2)从早 8:00~下午 6:00 每小时读取/xyz 目录下 x1 文件中每行第一个域的全部数据
加入到/backup 目录下的 bak01.txt 文件内;
(3)每逢星期一下午 5:50 将/data 目录下的所有目录和文件归档并压缩为文件:
backup.tar.gz;
(4)在下午 5:55 将 IDE 接口的 CD-ROM 卸载(假设:CD-ROM 的设备名为 hdc);
(5)在早晨 8:00 前开机后启动。
参考答案:
(1)用 vi 创建编辑一个名为 prgx 的 crontab 文件;
prgx 文件的内容:
50 16 rm -r /abc/
(2)、0 8-18/1 cut -f1 /xyz/x1 >> /backup/bak01.txt
(3)、50 17
tar zcvf backup.tar.gz /data
(4)、55 17 * umount /dev/hdc
(5)、由超级用户登录,用 crontab 执行 prgx 文件中的内容:
root@xxx:#crontab prgx;在每日早晨 8:00 之前开机后即可自动启动 crontab。
=====25、判断输入的文件是否是字符文件

!/bin/bash

read -p "shuru" filename
echo $filename
if [ -c $filename ];then
echo "ok"
else
echo "no"
fi
======26、case流程控制实现apache服务管理

!/bin/bash

脚本 加一个参数,通过参数判断

case "$1" in
'start')
/usr/sbin/apachectl start ;;
'stop')
/usr/sbin/apachectl stop ;;
'restart')
/usr/sbin/apachectl restart ;;
) echo "usage $0 start|stop|restart" ;; esac
======27、验证passwdxx⽂件有效性
kylin@kylin-W515:~/桌面$ cat cc
root:x:0:0:root:/root:/bin/bash
:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin::2:2:bin:/bin:/usr/sbin/nologin
x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync

kylin@kylin-W515:~/桌面$ cat cc | awk -F: '\ #使用:作为分隔符
NF != 7{\ #当域的数量不等于7时,执行下面

printf打印字符串"line ?? does not have 7 fields",并显⽰该条记录。

printf("line %d,does not have 7 fields:%s\n",NR,$0)}

如果第⼀个域没有包含任何字⺟和数字,printf打印“no alpha and numeric user id" ,并显⽰记录数和记录

$1 !~ /[A-Za-z0-9]/{printf("line %d,non alpha and numeric user id:%s\n",NR,$0)}\

如果第⼆个域是⼀个星号,就打印字符串“no passwd”,紧跟着显⽰记录数和记录本⾝

$2 == "" {printf("line %d,no password: %s\n",NR,$0)}'

line 2,non alpha and numeric user id::x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
line 3,no password: bin::2:2:bin:/bin:/usr/sbin/nologin
line 4,does not have 7 fields:x:3:3:sys:/dev:/usr/sbin/nologin

=====判断输入的压缩文件类型,并解压

!/bin/bash ftype=`file

1

c
a
s
e
ftype in "
1
:
Z
i
p
a
r
c
h
i
v
e
"

)
u
n
z
i
p
1;; "
1
:
g
z
i
p
c
o
m
p
r
e
s
s
e
d
"

)
g
u
n
z
i
p
1;; "
1
:
b
z
i
p
2
c
o
m
p
r
e
s
s
e
d
"

)
b
u
n
z
i
p
2
1;; *) echo "file $1 can not be uncompressed with smartzip";; esac

=====

!/bin/bash

function:一键部署nginx

请以root用户身份执行

systemctl stop firewalld.service
systemctl disable firewalld.service
sed -i 's/SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux
systemctl stop nginx
if [ -d /usr/local/nginx ]; then
rm -rf /usr/local/nginx
fi
read -p "部署开始(nginx=1/tengine=2):" App
if [ $App -eq 1 ];then
echo "开始部署nginx服务...."
echo "正在安装依赖包,请稍等...."
yum -y install gcc-c++ && yum install -y pcre pcre-devel && yum install -y zlib zlib-devel && yum install -y openssl openssl-devel
mkdir /usr/local/nginx && cd /usr/local/nginx
useradd -s /sbin/nologin -M nginx
echo "正在解压安装包,请稍等...."
cd /root
tar xvfz nginx-1.18.0.tar.gz
echo "正在配置,请稍等...."
cd nginx-1.18.0 && ./configure --prefix=/usr/local/nginx/ --user=nginx --group=nginx --with-http_stub_status_module --with-http_ssl_module --with-file-aio --with-http_realip_module --with-stream
echo "正在安装服务请稍等..."
make && make install
/usr/local/nginx/sbin/./nginx -t
fi
if [ $App -eq 2 ];then
echo "开始部署nginx服务...."
if [ ! -f /usr/local/BabaSSL/libssl.pc ]; then
if [ ! -d /usr/local/src ]; then
mkdir /usr/local/src
fi
cp /root/BabaSSL-master.tar.gz /usr/local/src
cd /usr/local/src
tar -xzf BabaSSL-master.tar.gz -C /usr/local
cd /usr/local/BabaSSL
./config enable-ntls
make && make install
mkdir /usr/local/nginx && cd /usr/local/nginx
echo "正在解压安装包,请稍等...."
cd /root
tar xvfz tengine-master.tar.gz
cd tengine-master && ./configure --prefix=/usr/local/nginx/--user=nginx --group=nginx --add-module=modules/ngx_openssl_ntls --with-openssl=/usr/local/BabaSSL --with-openssl-opt="--strict-warnings enable-ntls" --with-http_ssl_module --with-stream --with-stream_ssl_module --with-stream_sni
echo "正在安装服务请稍等..."
make && make install
/usr/local/nginx/sbin/./nginx -t
fi
read -p "是否部署服务开机自启(yes=1/no=2):" fw
if [ $fw -eq 1 ];then
echo "开始部署服务开机自启...."
[kod.shinlax.com)
[kod.cp-investment.com)
[kod.876787.com)
[kod.diyikejian.com)
[kod.bccs0769.com)
[kod.ttianyouhui.com)
[kod.g-millingmachine.com)
[kod.2ni1.com)
echo "
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target" > /lib/systemd/system/nginx.service
systemctl start nginx.service && systemctl enable nginx.service && systemctl enable nginx.service
systemctl status nginx.service
echo "服务及开机自启部署成功,请输入ifconfig | grep inet | cut -d " " -f 10 | head -1测试"
fi
if [ $fw -eq 2 ];then
echo "即将开启服务并退出脚本..."
echo "
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target" > /lib/systemd/system/nginx.service
systemctl start nginx.service && systemctl disable nginx.service && systemctl disable nginx.service
systemctl status nginx.service
echo "服务部署成功,请输入ifconfig | grep inet | cut -d " " -f 10 | head -1测试"
fi

===查找baidunetdisk进程,并杀死它 shell脚本
NAME="baidunetdisk"
echo $NAME
ID=ps -ef | grep " N A M E " | g r e p − v " 0" | grep -v "grep" | awk '{print $2}'
echo $ID
echo "start kill baidunetdisk"
for id in $ID
do
if [ "$$" = "$id" ];then
continue
else
kill -3 $id
fi
done
echo "baidunetdisk kill finished"

相关文章
|
2月前
|
SQL Shell 数据库
在TDengine容器中创建初始化数据库的Shell命令实例
以上就是在Docker容器环境中部署并初始化TDengine数据库的全过程,希望对你有所帮助。
81 0
|
6月前
|
Unix Shell Perl
技术心得:实例解析shell子进程(subshell)
技术心得:实例解析shell子进程(subshell)
|
7月前
|
存储 Unix Shell
Linux【脚本 04】Shell脚本传递参数的4种方式(位置参数、特殊变量、环境变量和命名参数)实例说明
Linux【脚本 04】Shell脚本传递参数的4种方式(位置参数、特殊变量、环境变量和命名参数)实例说明
771 0
|
Shell Docker 容器
利用shell脚本[带注释的]部署单节点多实例es集群(docker版)
利用shell脚本[带注释的]部署单节点多实例es集群(docker版)
110 0
|
Shell
shell中正则表达式中字符的应用具体实例以及详解
shell中正则表达式中字符的应用具体实例以及详解
139 3
|
监控 关系型数据库 Shell
用shell脚本写一个监控drds实例的脚本
用shell脚本写一个监控drds实例的脚本
84 1
|
运维 监控 Shell
太牛了!100个Shell脚本实例,代码清晰拿来就能用,再也不怕写不对了!
太牛了!100个Shell脚本实例,代码清晰拿来就能用,再也不怕写不对了!
|
关系型数据库 MySQL Unix
shell脚本操作实例
shell脚本操作实例
|
Shell
Shell脚本一键配置LAMP环境-脚本实例和解释
Shell脚本一键配置LAMP环境-脚本实例和解释
119 0
|
Shell Linux
shell脚本多进程并发写法实例(高阶修炼)
shell脚本多进程并发写法实例(高阶修炼)