2.shell

shell开发

shell脚本文件

shell脚本文件,第一行必须指定想要用的shell。

#!/bin/bash

shell脚本里,#号是注释行,shell不会处理脚本中的注释行,然而第一行例外,该写法会通知shell用哪个解释器来运行脚本。

shell脚本中可以书写你想要执行的命令,且可以添加注释行。

[root@web01 ~]# cat test.sh
#!/bin/bash
# This is test script
date
whoami
echo "It's Over."

执行脚本

用解释器读取脚本

[root@web01 ~]# sh test.sh
Mon Sep 28 09:34:28 CST 2020
root
It's Over.


[root@web01 ~]# bash test.sh
Mon Sep 28 09:34:36 CST 2020
root
It's Over.

直接运行文件,需要赋予权限

[root@web01 ~]# ./test.sh
-bash: ./test.sh: Permission denied

[root@web01 ~]# ll test.sh
-rw-r--r-- 1 root root 64 Sep 28 09:34 test.sh
[root@web01 ~]# chmod +x test.sh
[root@web01 ~]#
[root@web01 ~]# ll test.sh
-rwxr-xr-x 1 root root 64 Sep 28 09:34 test.sh

# 执行
[root@web01 ~]# ./test.sh
Mon Sep 28 09:35:35 CST 2020
root
It's Over.

当以./test.sh该形式执行脚本,则以文件第一行的shebang指定的解释器执行文件。

常用echo

在shell脚本里,shell命令会有自己的输出,若是你想要自定义内容打印,以告知用户,当前脚本在做什么事。

可以通过echo命令来实现,注意单引号双引号

使用变量与echo

脚本里,可以在环境变量名称前加上$来使用环境变量。

转义符

当一些情况,我们不希望shell解析一些符号,可以使用单引号转义符对符号不做解析。

变量再赋值

变量每次被引用的时候,都会输出赋予的值,需要加上$

若是忘记用美元符,则结果就错误了。

命令替换

shell一大特性就是可以从命令中提取结果,再赋予给变量,这样处理脚本数据特别方便。

有两个方式将命令输出赋予给变量

反引号 ``

$() 格式

$符号

[root@web01 ~]# cat test.sh
#!/bin/bash
testing=$(date)
echo "The date and time are:" $testing

# 结果
[root@web01 ~]# ./test.sh
The date and time are: Mon Sep 28 10:31:39 CST 2020

反引号

反引号和$()的作用相同,用于命令替换(command substitution),即完成引用的命令的执行,将其结果替换出来,与变量替换差不多。比如:

[root@web01 ~]# echo `date '--date=1 hour ago' +%Y-%m-%d-%H`

等同于
[root@web01 ~]# echo $(date '--date=1 hour ago' +%Y-%m-%d-%H)

数值计算

编程语言都支持数字计算,但是对于shell来说,数值计算稍微麻烦点。

算数运算符

请添加图片描述
请添加图片描述

(2.shell.assets/image-20210308143733046.png)]

运算符命令

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4iXOBYlu-1687519233321)(2.shell.assets/image-20210308143808429.png)]

Shell if参数

shell 编程中使用到得if语句内判断参数
–b 当file存在并且是块文件时返回true
-c 当file存在并且是字符文件时返回true
-d 当pathname存在并且是一个目录时返回true
-e 当pathname指定的文件或目录存在时返回true
-f 当file存在并且是文件时返回true
-g 当由pathname指定的文件或目录存在并且设置了SGID位时返回为true
-h 当file存在并且是符号链接文件时返回true,该选项在一些老系统上无效
-k 当由pathname指定的文件或目录存在并且设置了“粘滞”位时返回true
-p 当file存在并且是命令管道时返回为true
-r 当由pathname指定的文件或目录存在并且可读时返回为true
-s 当file存在文件大小大于0时返回true
-u 当由pathname指定的文件或目录存在并且设置了SUID位时返回true
-w 当由pathname指定的文件或目录存在并且可执行时返回true。一个目录为了它的内容被访问必然是可执行的。
-o 当由pathname指定的文件或目录存在并且被子当前进程的有效用户ID所指定的用户拥有时返回true。
UNIX Shell 里面比较字符写法:
-eq 等于
-ne 不等于
-gt 大于
-lt 小于
-le 小于等于
-ge 大于等于
-z 空串
= 两个字符相等
!= 两个字符不等
-n 非空串

双括号(())

效率极高,常用方法
请添加图片描述

请添加图片描述

(2.shell.assets/image-20210308144033950.png)]

案例,注意必须是整数,双括号不支持浮点数,浮点数需要其他命令计算

# 加减乘除
[root@chaogelinux shell_program]# echo $((3+4))
7
[root@chaogelinux shell_program]# echo $((5-3))
2
[root@chaogelinux shell_program]# echo $((5*3))
15
[root@chaogelinux shell_program]# echo $((5/3)) # 取商,除法
1
[root@chaogelinux shell_program]# echo $((5**2))
25
[root@chaogelinux shell_program]# echo $((7%4)) # 取余数,取模计算
3

# 变量计算
[root@chaogelinux shell_program]# ((i=5))
[root@chaogelinux shell_program]# ((i=i*i))
[root@chaogelinux shell_program]# echo $i
25

# 复杂数学运算
[root@chaogelinux shell_program]# ((a=2+2**3-4%3))
[root@chaogelinux shell_program]#
[root@chaogelinux shell_program]#
[root@chaogelinux shell_program]# echo $a
9

# 变量定义在括号外,写法2
[root@chaogelinux shell_program]# b=$((2+2**3-4%3))
[root@chaogelinux shell_program]# echo $b
9

# 不用变量赋值,直接看结果,一定记得用$符号
[root@chaogelinux shell_program]# echo $((2+2**3-4%3))
9

#结果判断,真假值,1为真,0位假
[root@chaogelinux shell_program]# echo $((3<4))
1
[root@chaogelinux shell_program]# echo $((3>4))
0
[root@chaogelinux shell_program]# echo $((3==4))
0

特殊运算符

++ 加一

– 减一

注意这里有坑

++a 是先计算加一,然后赋值a

a++ 是先对变量a操作,再加一

注意这个先后顺序

[root@chaogelinux shell_program]# a=5
[root@chaogelinux shell_program]# echo $((++a)) # 这是先对a变量,加一,然后再赋值
6

[root@chaogelinux shell_program]# echo $a
6

# 先打印,再赋值
[root@chaogelinux shell_program]# echo $((a++))
6
[root@chaogelinux shell_program]# echo $a
7

案例,对用户输入判断是否是整数的脚本

利用read命令,获取用户输入

# [-n string] or [string] “string”的长度为非零non-zero则为真 
# -p 后面跟提示信息,即在输入前打印提示信息。
# 状态码不为0 就是表示有错误



[root@chaogelinux shell_program]# cat is_int.sh
#!/bin/bash
print_usage(){
    printf "Please enter an integer\n"
    exit 1
}

# 接受用户输入
read -p "Please input first number: " firstnum


# 如果用户输入,去掉了整数部分,为空,说明是一个纯数字
# if的-n参数,如果 string 长度非零,则为真
# 如果该字符串不为空,那么if逻辑成立,说明用户输入的不是一个纯数字

# 逻辑判断,限制用户必须输入一个纯数字
if [ -n "`echo $firstnum|sed 's/[0-9]//g'`" ];then
    print_usage
fi

read -p "Please input the operators: " operators

# 判断运算符
if [ "${operators}" != "+" ] && [ "${operators}" != "-" ] && [ "${operators}" != "*" ] && [ "${operators}" != "/" ];then
    echo  "Please use {+|-|*|/}"
    exit 2
fi

# 输入第二个数字
read -p "Please input second number: " secondnum
if [ -n "`echo $secondnum|sed 's/[0-9]//g'`" ];then
    print_usage
fi

# 最后数值计算
echo "${firstnum}${operators}${secondnum}结果是:$((${firstnum}${operators}${secondnum}))"

执行

[root@chaogelinux shell_program]# bash is_int.sh
Please input first number: 12
Please input the operators: +
Please input second number: 4
12+4结果是:16

一个简单的玩法,直接对用户输入计算

[root@chaogelinux shell_program]# cat jisuan.sh
#!/bin/bash
echo $(($1))
[root@chaogelinux shell_program]# bash jisuan.sh 3+4
7

[root@chaogelinux shell_program]# bash jisuan.sh "3*4"
12

let命令

let命令等同于双括号计算,"((赋值表达式))"

但是双括号效率更高

[root@chaogelinux shell_program]# # 计算变量相加
[root@chaogelinux shell_program]# i=2
[root@chaogelinux shell_program]# i=i+8
[root@chaogelinux shell_program]# echo $i
i+8
[root@chaogelinux shell_program]# unset i
[root@chaogelinux shell_program]# i=2
[root@chaogelinux shell_program]# let i=i+8
[root@chaogelinux shell_program]# echo $i
10

# 上述等同于
[root@chaogelinux shell_program]# i=2
[root@chaogelinux shell_program]# echo $((i=i+8))
10

实际脚本开发,检测nginx服务状态

[root@chaogelinux shell_program]# cat check_nginx_status.sh
#!/bin/bash

# 定义功能函数
CheckUrl(){
timeout=5
fails=0
success=0
while true
    do
        wget --timeout=$timeout --tries=1 http://pythonav.cn/ -q -O /dev/null
        # 如果上述状态码不等于0,表示出错
        if [ $? -ne 0 ]
            then
                let fails=fails+1 # 失败错误次数+1
        else
                let success+=1
        fi

        if [ $success -ge 1 ]
            then
                   echo "It's success."
                   exit 0
        fi

        # 如果出错次数大于2,报警
        if [ $fails -ge 2 ];then
            echo "该网站一定是挂了,超哥快去检查下你的服务器!"
            exit 2
        fi
done
}
CheckUrl
[root@chaogelinux shell_program]#

expr命令

expr命令允许在命令行处理数学表达式,简单的计算器命令

查看帮助

expr --help

注意参数之间必须有空格

[root@web01 ~]# expr 1 + 5
6

# expr并不是很好用,比较麻烦
# 很多符号在shell里有特殊含义因此必须得转义使用
[root@web01 ~]# expr 5 * 2
expr: syntax error
[root@web01 ~]# expr 5 \* 2
10

# 求长度
[root@web01 ~]# expr length 123132134524asdqweqweqewqfgdfgdfgdf
35

# 逻辑判断,必须加上引号
[root@web01 ~]# expr 33 '>'  3
1
[root@web01 ~]# expr 33 '>'  333
0

# 除法
[root@web01 ~]# expr 50 / 5
10

expr模式匹配

expr支持模式匹配,也就是如同正则的作用

有2个模式符号
冒号,计算字符串中的字符数

.* 任意字符串重复0次或多次

语法

统计字符串的字符个数

expr 字符串 : “.*”

实践

# 统计yc.jpg字符个数
[root@chaogelinux ~]# expr yc.jpg ":"  ".*"
6

# 统计jpg后缀的文件,字符个数,找不到符合的就为0
# 无论jpg后面有多少个字符,只匹配到jpg这3个字符结尾
[root@chaogelinux ~]# expr yc.jpg   ":"  ".*\.jpg"
6
[root@chaogelinux ~]# expr yc.jpg123123   ":"  ".*\.jpg"
6
# 找不到的情况
[root@chaogelinux ~]# expr yc.jpwg123123   ":"  ".*\.jpg"
0

expr案例

expr判断文件名是否符合要求

[root@chaogelinux shell_program]# cat expr1.sh
#!/bin/bash

if expr "$1" : ".*\.jpg" &> /dev/null
    then
        echo "This is jpg file"
else
    echo "这不是jpg文件"
fi

# 执行
[root@chaogelinux shell_program]# bash expr1.sh 蔡徐坤.jpg
This is jpg file

[root@chaogelinux shell_program]# bash expr1.sh t1.sh
这不是jpg文件

找出字符长度不大于6的单词

[root@chaogelinux shell_program]# cat word_length.sh
#!/bin/bash
# 注意后面这个变量,别加引号
for str in I am Yu Chao, I teach you to learn linux
do
    if [ `expr length $str` -le 6  ]
        then
            echo $str
    fi
done

test命令

test 命令最短的定义可能是评估一个表达式;如果条件为真,则返回一个 0 值。如果表达式不为真,则返回一个大于 0 的值 — 也可以将其称为假值。检查最后所执行命令的状态的最简便方法是使用 $? 值。

参数:

1. 关于某个文件名的『类型』侦测(存在与否),如 test -e filename 

-e 该『文件名』是否存在?(常用) 
-f 该『文件名』是否为文件(file)?(常用) 
-d 该『文件名』是否为目录(directory)?(常用) 
-b 该『文件名』是否为一个 block device 装置? 
-c 该『文件名』是否为一个 character device 装置? 
-S 该『文件名』是否为一个 Socket 文件? 
-p 该『文件名』是否为一个 FIFO (pipe) 文件? 
-L 该『文件名』是否为一个连结档? 

2. 关于文件的权限侦测,如 test -r filename 

-r 侦测该文件名是否具有『可读』的属性? 
-w 侦测该文件名是否具有『可写』的属性? 
-x 侦测该文件名是否具有『可执行』的属性? 
-u 侦测该文件名是否具有『SUID』的属性? 
-g 侦测该文件名是否具有『SGID』的属性? 
-k 侦测该文件名是否具有『Sticky bit』的属性? 
-s 侦测该文件名是否为『非空白文件』? 

3. 两个文件之间的比较,如: test file1 -nt file2 

-nt (newer than)判断 file1 是否比 file2 新 
-ot (older than)判断 file1 是否比 file2 旧 
-ef 判断 file2 与 file2 是否为同一文件,可用在判断 hard link 的判定上。 主要意义在判定,两个文件是否均指向同一个 inode 哩! 

4. 关于两个整数之间的判定,例如 test n1 -eq n2 

-eq 两数值相等 (equal) 
-ne 两数值不等 (not equal) 
-gt n1 大于 n2 (greater than) 
-lt n1 小于 n2 (less than) 
-ge n1 大于等于 n2 (greater than or equal) 
-le n1 小于等于 n2 (less than or equal) 

5. 判定字符串的数据 

test -z string 判定字符串是否为 0 ?若 string 为空字符串,则为 true 
test -n string 判定字符串是否非为 0 ?若 string 为空字符串,则为 false。
注: -n 亦可省略 
test str1 = str2 判定 str1 是否等于 str2 ,若相等,则回传 true 
test str1 != str2 判定 str1 是否不等于 str2 ,若相等,则回传 false 

6. 多重条件判定,例如: test -r filename -a -x filename 

-a (and)两状况同时成立!例如 test -r file -a -x file,则 file 同时具有 r 与 x 权限时,才回传 true。 
-o (or)两状况任何一个成立!例如 test -r file -o -x file,则 file 具有 r 或 x 权限时,就可回传 true。 
! 反相状态,如 test ! -x file ,当 file 不具有 x 时,回传 true

test命令对于shell脚本是重要的命令,提供了在if-then语句里测试不同条件的路径。

我们来看用法,条件为真,返回0,条件不成立,返回大于0的值

1.判断文件存在
[root@web01 ~]# test hello.sh
[root@web01 ~]# echo $?
0

2.判断目录
[root@web01 ~]# test -d data
[root@web01 ~]# echo $?
0

3.测试可写权限
[root@web01 ~]# test -w hello.sh
[root@web01 ~]# echo $?
0

4.测试执行权限
[root@web01 ~]# test -x hello.sh
[root@web01 ~]#
[root@web01 ~]#
[root@web01 ~]# echo $?
1

5.测试文件是否有内容,有则0,无则1
[root@web01 ~]# cat hello.sh
#!/bin/bash
echo 'hello 超哥,你讲的课真有意思'
[root@web01 ~]#
[root@web01 ~]# test -s hello.sh
[root@web01 ~]#
[root@web01 ~]# echo $?
0

结合控制语句

[root@web01 ~]# cat test.sh
#!/bin/bash
# Testing the test command
my_var="Full"
if test $my_var
then
    echo "The $my_var expression returns a True."
else
    echo "The $my_var expression returns a False."
fi
[root@web01 ~]#
[root@web01 ~]#
[root@web01 ~]# bash test.sh
The Full expression returns a True.


若是删除my_var变量,该脚本,就False了。

简洁测试方法

# 注意空格
if [ 条件 ]
then
    commands
fi

在中括号里,写入测试条件。

符合条件测试

[ 条件 ] && [ 条件2 ]

[ 条件 ] || [ 条件2 ]

布尔运算符

案例

[root@web01 ~]# cat test.sh
#!/bin/bash
# 超哥带你学shell

if [ -d $HOME ] && [ -w $HOME/testing ]
then
    echo "The file exists and you can write to it."
else
    echo "I cannot wirte to the file."
fi
[root@web01 ~]#
[root@web01 ~]#
[root@web01 ~]# bash test.sh
I cannot wirte to the file.

# 对文件创建,修改权限测试

判断字符串

字符串比较

格式1:
[ "str1" = "str2" ]
[ "str1" != "str2" ]


格式2:
-z:字符串内容为空
-n:字符串内容不为空

[ -n "" ]
[ -z "luobo" ]


# 用此命令查看结果是否正确,0为正确,其他为错。
echo $?

特殊的shell变量

预定义变量:
$0:当前执行的进程/程序名
$#:命令行中位置变量的个数
$*:所有位置变量的内容
$?:上一条命令执行后返回的状态,当返回状态值为0时表示执行正常,非0表示执行异常或出错

双括号特性

双小括号

bash支持双括号,写入高级数学表达式。
请添加图片描述(2.shell.assets/image-20200928172157775.png)]

可以在if语句里使用双括号,可以用在普通的命令。

# 10的平方是100,脚本

[root@web01 ~]# cat test.sh
#!/bin/bash
# 超哥带你学shell

val1=10
if (( $val1 ** 2 > 90 ))
then
    (( val2 = $val1**2 ))
    echo "The square of $val1 is $val2"
fi


[root@web01 ~]# bash test.sh
The square of 10 is 100

# 注意双括号里不需要转义,val2语句是赋值语句

双方括号

双方括号提供了针对字符串的高级特性,模式匹配,正则表达式的匹配。

[root@web01 ~]# cat test.sh
#!/bin/bash
# 超哥带你学shell

if [[ $USER == r* ]]
then
    echo "Hello $USER"
else
    echo "Sorry,I do not know you."
fi


[root@web01 ~]# bash test.sh
Hello root

在双中括号里,进行了==双等号,进行字符串匹配r*,也就找到了root

读取用户输入

在前面的实战脚本中,超哥已经讲了read命令的基础用法。

shell变量除了直接赋值,或者脚本传参,还有就是read命令读取。

read也是内置命令。

-p 设置提示信息

-t 等待用户输入超时,timeout

read -p "请输入: " vars

实践

[root@chaogelinux ~]# read -t 5 -p "我给你五秒钟时间输入密码:" my_pwd
我给你五秒钟时间输入密码:[root@chaogelinux ~]#

# 正确输入
[root@chaogelinux ~]# read -t 5 -p "我给你五秒钟时间输入密码:" my_pwd
我给你五秒钟时间输入密码:chaoge888

[root@chaogelinux ~]# echo $my_pwd
chaoge888

# 输入多个变量,注意用空格分割
[root@chaogelinux ~]# read -t 5 -p "请输入你的账户,密码:" my_user  my_pwd
请输入你的账户,密码:yu chaoge888

[root@chaogelinux ~]# echo $my_user $my_pwd
yu chaoge888

条件判断

if语法1:

if [ 条件 ]; then

xxxxxx

fi

if语法2:

if [ 条件 ]; then

xxxx

else

yyyy

fi

if语法3:

if [ 条件1 ]; then

xxx

elif [ 条件2 ]; then

yyy

else

zzz

fi

代码演示1

[root@bogon scripts]# cat test1.sh 
#! /bin/bash
if [[ 5 > 3 ]];then
    echo "正确"
fi


// 正确

代码演示2

[root@bogon scripts]# cat test1.sh 
#! /bin/bash
if [[ 5 < 3 ]];then
    echo "正确"
else
    echo "错误"
fi

// 错误

代码演示3

[root@bogon scripts]# cat test1.sh 
#! /bin/bash
read -p "请输入成绩:" num
if [[ $num > 90 ]]; then
    echo "真棒"
elif [[ $num > 70 ]]; then
    echo "还不错"
elif [[ $num > 60 ]]; then
    echo "继续努力"
else
   echo "辣鸡"
fi

循环

for循环

语法:

for 变量名 in 取值列表 do

xxxx

done

# 代码演示
[root@bogon scripts]# cat test1.sh 
#! /bin/bash
for i in {1..10}; do
    echo $i
done

while循环

语法:

while 条件测试操作 do

xxxx

done

# 代码演示
[root@bogon scripts]# cat test1.sh 
#! /bin/bash
while true; do
    echo "萝卜"
done

控制循环

  • break:跳出当前循环
  • continue:用于跳过某次循环,当条件满足时,然后继续循环。

case语句

语法:

case 变量值 in

模式1)

命令序列1

;;

模式2)

命令序列2

;;

模式3)

命令序列3

;;

*)

默认命令序列

esac

# 代码演示

[root@bogon scripts]# cat case.sh 
#! /bin/bash
read -p "请输入一个数字(0-9):" NUM
case $NUM in
	1)
	echo "your name is 1"
	;;
	2)
	echo "num is 2"
	;;
	[3-8])
	echo "num is $NUM"
	;;
	9|0)
	echo "num is $NUM"
	;;
	*)
	echo "必须是数字{0-9}"
esac

正则字符

^  以什么开头 ^help
$  以什么结尾 help$
.  单个任意字符
\  转义             如果本来就想匹配.,那要先转义    \** 左边乘号,右边正则
*  匹配左侧表达式0个或任意个 ip*           可以匹配 i   ip   ipp
+          匹配到左侧表达式1个或者任意个(扩展正则)ip+  ip ipp,不可能匹配到i
[]  范围选择匹配选择符,匹配信息不再是任意,匹配集合中的   f[a|b|c]d    fad fbd fcd 匹配其中一个
[x-y]  匹配结合范围内的                [a-z] [0-9] [A-Z]      ^[a-zA-Z] 以字母开头,符号不要写里面
[^]  匹配不在集合范围内的     ^[^0-9] 不能以数字开头
{}   匹配左侧表达式的个数,{}需要在shell中转义
[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+  可以把除了数字的字符都筛出去,但是没有办法控制数字的个数
\{3\} 匹配左侧表达式3个      6\{3\} 666
\{3,\} 匹配左侧表达式3个或者任意个     6\{3,\}    666  66666
\{1,3\}   匹配左侧表达式 ,最少出现1次,最多出现3次    6 66 666

脚本

批量设置用户密码

echo “123123” | passwd --stdin test

[root@bogon scripts]# cat /scripts/user 
zhangsan1
zhangsan2
zhangsan3


[root@bogon scripts]# cat /scripts/for.sh 
#! /bin/bash
for i in `cat /scripts/user`
do
	useradd $i
	echo "123123" |passwd --stdin $i &> /dev/null
done

批量测试网络通不通

[root@bogon scripts]# cat ip.txt 
10.0.1.111
10.0.1.112
www.baidu.com
asjldfk.asfdjl.asjdfl


[root@bogon scripts]# cat ip.sh 
#! /bin/bash
for i in `cat /scripts/ip.txt`
do
	ping -c 1 $i &> /dev/null
	if [ $? -eq 0 ]
	then 
		echo "$i网站ping的通"
	else
		echo "$i网站ping不通"
	fi
done

猜大小

[root@bogon scripts]# cat cai.sh 
#! /bin/bash
# 定义价格的随机变量
JIAGE=`expr $RANDOM % 1000`
echo "$JIAGE"
i=0
while true
let i++
read -p "猜测商品的价格:" NUM
do
	if [ $NUM -gt $JIAGE ]
	then
		echo "大了"
	elif [ $NUM -lt $JIAGE ]
	then	
		echo "小了"
	else
		echo "恭喜你,猜对了,猜了$i次"
		exit
	fi
done

判断是否为数字或字符

[root@bogon scripts]# cat anniu.sh 
#! /bin/bash
read -p "请输入一个字符" STR
case $STR in
	[0-9])
	echo "输入的是数字"
	;;
	*)
	echo "输入的是字符"
esac

脚本管理服务

[root@bogon scripts]# cat sys.sh 
#! /bin/bash
read -p "请输入启动的服务:" NAME

if [ -e /etc/init.d/$NAME ]
echo "1:启动服务"
echo "2:停止服务"
echo "3:查看服务"
read -p "请输入数字:" I
then    
        case $I in 
                1)
                        /etc/init.d/$NAME start
                ;;
                2)
                        /etc/init.d/$NAME stop
                ;;
                3)
                        /etc/init.d/$NAME status
esac
fi

dhcp自动化部署脚本

#! /bin/bash
# 查看网段
IP=`ifconfig ens33 |grep netmask |awk '{print $2}'`
echo "你的IP:$IP"

# 光盘
# echo "开始挂载光盘"
umount /dev/sr0
mount /dev/sr0 /mnt


# 删除自带的下载源配置
echo "开始删除下载源"
mkdir /etc/yum.repos.d/bak
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak/

# 生成本地下载源
echo "开始生成本地源"
touch /etc/yum.repos.d/local.repo
cat >> /etc/yum.repos.d/local.repo << EOF
[local_repo]
name=local_repo
gbgcheck=0
baseurl=file:///mnt/
EOF


# 清理缓存
echo "清理缓存"
yum clean all

# 下载dhcp服务
echo "下载dhcp服务"
yum install dhcp -y


# 修改配置文件
echo "开始修改配置文件"
read -p "请输入你的开始ip:" start
read -p "请输入你的结束ip:" over
cat >>/etc/dhcp/dhcpd.conf << EOF
option domain-name-servers 1.2.4.8;
subnet 10.0.1.0 netmask 255.255.255.0 {
range 10.0.1.$start 10.0.1.$over;
option subnet-mask 255.255.255.0;
option routers 10.0.1.2;}
EOF

# 启动dhcp服务
echo "启动dhcp服务"
systemctl start dhcpd.service 

# 删除脚本中定义的变量
unset IP start over

系统初始化

vim  initialize.sh
#! /bin/bash

# 挂载光盘
umount /dev/sr0 &> /dev/null
mount /dev/sr0 /mnt &> /dev/null

# 删除自带的下载源配置
mkdir /etc/yum.repos.d/bak &> /dev/null
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak/

# 生成本地下载源
touch /etc/yum.repos.d/local.repo
cat >> /etc/yum.repos.d/local.repo << EOF
[local_repo]
name=local_repo
gbgcheck=0
baseurl=file:///mnt/
EOF

# 清理缓存
yum clean all &> /dev/null

# 锁定系统关键文件
chattr +i  /etc/passwd  /etc/group  /etc/shadow /etc/gshadow /etc/inittab

# 定时清理clientmqueue
echo "find /var/spool/clientmqueue/ -type f|xargs rm -f" >/scripts/del_sys_file.sh
echo "00 00 * * 0 /bin/sh /scripts/del_sys_file.sh &> /dev/null" >/var/spool/cron/root

# 关闭selinux
sed -i  's/enforcing/disabled/g' /etc/selinux/config 

# 设置系统语言编码为utf-8
# 临时生效
export LC_ALL=zh_CN.UTF-8
# 永久生效
echo 'LANG="zh_CN.UTF-8"' > /etc/locale.conf

# 关闭防火墙
systemctl stop firewalld
systemctl disable firewalld

# 时间同步更新;
# 下载命令
yum install ntp -y &> /dev/null
ntpdate -u ntp.aliyun.com &> /dev/null
mv /etc/localtime{,.bak}
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 

samba脚本

vim samba.sh
#!/bin/bash
yum -y install samba\*
read -p "public name:" NAME
read -p "public dir:" DIR
read -p "user name:" USER
useradd $USER
mkdir -p $DIR
echo -e "test\ntest" | pdbedit -a -t -u $USER
sed -i '$a \['$NAME'\]' /etc/samba/smb.conf
sed -i '$a path='$DIR'' /etc/samba/smb.conf
sed -i '$a public=no' /etc/samba/smb.conf
sed -i '$a read only=yes' /etc/samba/smb.conf
systemctl restart smb nmb

/mnt/
EOF

清理缓存

yum clean all &> /dev/null

锁定系统关键文件

chattr +i /etc/passwd /etc/group /etc/shadow /etc/gshadow /etc/inittab

定时清理clientmqueue

echo “find /var/spool/clientmqueue/ -type f|xargs rm -f” >/scripts/del_sys_file.sh
echo “00 00 * * 0 /bin/sh /scripts/del_sys_file.sh &> /dev/null” >/var/spool/cron/root

关闭selinux

sed -i ‘s/enforcing/disabled/g’ /etc/selinux/config

设置系统语言编码为utf-8

临时生效

export LC_ALL=zh_CN.UTF-8

永久生效

echo ‘LANG=“zh_CN.UTF-8”’ > /etc/locale.conf

关闭防火墙

systemctl stop firewalld
systemctl disable firewalld

时间同步更新;

下载命令

yum install ntp -y &> /dev/null
ntpdate -u ntp.aliyun.com &> /dev/null
mv /etc/localtime{,.bak}
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime


## samba脚本

vim samba.sh
#!/bin/bash
yum -y install samba*
read -p “public name:” NAME
read -p “public dir:” DIR
read -p “user name:” USER
useradd $USER
mkdir -p $DIR
echo -e “test\ntest” | pdbedit -a -t -u U S E R s e d − i ′ USER sed -i ' USERsedia ['KaTeX parse error: Can't use function '\]' in math mode at position 6: NAME'\̲]̲' /etc/samba/sm…a path=‘ D I R ′ ′ / e t c / s a m b a / s m b . c o n f s e d − i ′ DIR'' /etc/samba/smb.conf sed -i ' DIR′′/etc/samba/smb.confsedia public=no’ /etc/samba/smb.conf
sed -i ‘$a read only=yes’ /etc/samba/smb.conf
systemctl restart smb nmb

















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值