commit 01fc2d259d2840908072aaf00b4421de9f4a4fa2 Author: tu <2843180578@qq.com> Date: Wed May 29 10:07:22 2024 +0800 上传文件至 shell-MD diff --git a/shell-MD/shell三剑客.md b/shell-MD/shell三剑客.md new file mode 100644 index 0000000..208f735 --- /dev/null +++ b/shell-MD/shell三剑客.md @@ -0,0 +1,623 @@ +

shell三剑客

+ +作者:行癫(盗版必究) + +------ + +## 一:非交互式编辑器Sed + +#### 1.sed介绍 + +![image-20230408155357663](https://xingdian-image.oss-cn-beijing.aliyuncs.com/xingdian-image/image-20230408155357663.png) + +​ sed 是一种在线的、非交互式的编辑器,它一次处理一行内容。处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。接着处理下一行,这样不断重复,直到文件末尾。文件内容并没有改变,除非你使用重定向存储输出;Sed主要用来自动编辑一个或多个文件;简化对文件的反复操作;编写转换程序等 + +#### 2.语法格式 + +```shell +sed [options] 'command' in_file[s] +``` + +options部分 + +``` + -n 静默输出(不打印默认输出) sed -n '1p' a.txt 想显示第几行就显示第几行 + -e 给予sed多个命令的时候需要-e选项 + #sed -e 's/root/haha/g' -e 's/bash/wwwww/g' passwd > passwd.bak + 如果不用-e选项也可以用分号“;”把多个命令隔开。 + #sed 's/haha/ro/g ; s/wwwww/kkkk/g' passwd | less 这个是-e的结果 + -i -i后面没有扩展名的话直接修改文件,如果有扩展名备份源文件,产生以扩展名结尾的新文件 + #sed -iback1 -e 's/root/rottt/g' -e 's/bash/wwwww/g' passwd //选项-i后面没有空格 + [root@localhost 桌面]# ls + manifest.txt passwdback1 + -f 当有多个要编辑的项目时,可以将编辑命令放进一个脚本里,再使用sed搭配-f选项 + [root@localhost 桌面]# cat s.sed + s/bin/a/g + s/ftp/b/g + s/mail/c/g + [root@localhost 桌面]# sed -f s.sed passwd | less +``` + +注意: + +​ 基本正则 sed + +​ 扩展正则 sed -r 无论是扩展正则还是基本正则,全部加r参数 + +command部分 + +```shell + p 打印行 1p 输出再打印一遍第一行 1~2 打印奇数 0~2打印偶数 + d 删除文本 + #sed '1 d' passwd + #sed '$ d' passwd + #sed '1,3 d' passwd + #sed '1,/^dian/ d' passwd + a 追加文本(后) + #sed '2 a nihao' passwd + #sed '/^dian/ a nihao' passwd + i 前插 + # sed -i '1 i nihao' passwd + c 替换 sed '/zhong/c abc' 将zhong这一行替换成abc + #sed -i '1 c no' passwd +``` + +#### 3.sed案例 + +```shell +1. sed可以从stdin中读取内容 +$ cat filename | sed 's/pattern/replace_string/' + +2. 选项-i会使得sed用修改后的数据替换原文件 +$ sed -i 's/pattern/replace_string/' filename + +3. g标记可以使sed执行全局替换 +$ sed 's/pattern/replace_string/g' filename + +4. g标记可以使sed匹配第N次以后的字符被替换 +$ echo "thisthisthisthis" | sed 's/this/THIS/2g' + +5. sed中的分隔符可以替换成别的字符, 因为s标识会认为后面的字符为分隔符 +$ sed 's:text:replace_text:' +$ sed 's|text|replace_text|' + +6. sed可以利用指令来删除文件中的空行 +$ sed '/^$/d' filename + +7. 替换指定的字符串或数字 +$ cat sed_data.txt +11 abc 111 this 9 file contains 111 11 99 numbers 0000 +$ sed -i 's/\b[0-9]\{3\}\b/NUMBER/g' sed_data.txt +$ cat sed_data.txt +11 abc NUMBER this 9 file contains NUMBER 11 99 numbers 0000 + +8. 由于在使用-i参数时比较危险, 所以我们在使用i参数时在后面加上.bak就会产生一个备份的文件,以防后悔 +$ sed -i.bak 's/pattern/replace_string/' filename +``` + +## 二:文本处理awk + +#### 1.awk介绍 + +​ awk 是一种编程语言,用于在linux/unix下对文本和数据进行处理。数据可以来自标准输入、一个或多个文件,或其它命令的输出。它支持用户自定义函数和动态正则表达式等先进功能,是linux/unix下的一个强大编程工具。它在命令行中使用,但更多是作为脚本来使用。awk的处理文本和数据的方式是这样的,它逐行扫描文件,从第一行到最后一行,寻找匹配的特定模式的行,并在这些行上进行你想要的操作。如果没有指定处理动作,则把匹配的行显示到标准输出(屏幕),如果没有指定模式,则所有被操作所指定的行都被处理。awk分别代表其作者姓氏的第一个字母。因为它的作者是三个人,分别是Alfred Aho、Brian Kernighan、Peter Weinberger。gawk是awk的GNU版本,它提供了Bell实验室和GNU的一些扩展 + +#### 2.语法格式 + +```shell +awk [options] 'commands' filenames +``` + +options部分 + +```shell +POSIX options: GNU long options: (standard) + -f progfile --file=progfile 指定awk脚本文件 + -F fs --field-separator=fs 定义输入字段分隔符,默认的分隔符是空格或制表符(tab) + -v var=val --assign=var=val 定义变量并赋值 +``` + +command部分 + +```shell +awk BEGIN{} {} END{} 文件 +BEGIN{} {} END{} +行处理前 行处理 行处理后 +``` + +​ BEGIN{} 所有文本内容读入之前要执行的命令 可以不需要后面跟文件,因为他是在读入文件之前的操作 + +​ {} 主输入循环 读入一行命令执行一次循环 + +​ END{} 所有文本都读入完成之后执行的命令 必须要读入文件,因为他是在读入文件之后的操作 + +案例: + +```shell +# awk 'BEGIN{print 1/2} {print "ok"} END{print "-----------"}' /etc/hosts +0.5 +ok +ok +ok +----------- + +BEGIN{} 通常用于定义一些变量,例如BEGIN{FS=":";OFS="---"} +``` + +常用案例: + +```shell +awk 'pattern' filename 示例:awk -F: '/root/' /etc/passwd +awk '{action}' filename 示例:awk -F: '{print $1}' /etc/passwd +awk 'pattern {action}' filename 示例:awk -F: '/root/{print $1,$3}' /etc/passwd + 示例:awk 'BEGIN{FS=":"} /root/{print $1,$3}' /etc/passwd +command |awk 'pattern {action}' 示例:df -P| grep '/' |awk '$4 > 25000 {print $4}' +``` + +#### 3.工作原理 + +```shell +[root@xingdiancloud ~]# awk -F: '{print $1,$3}' /etc/passwd +(1)awk使用一行作为输入,并将这一行赋给内部变量$0,每一行也可称为一个记录,以换行符结束 + +root : x : 0 : 0 : root : /root : /bin/bash +1 2 3 4 5 6 7 +(2)然后,行被:(默认为空格或制表符)分解成字段(或域),每个字段存储在已编号的变量中,从$1开始,最多达100个字段 + +(3)awk如何知道用空格来分隔字段的呢? 因为有一个内部变量FS来确定字段分隔符。初始时,FS赋为空格 + +(4)awk打印字段时,将以设置的方法使用print函数打印,awk在打印的字段间加上空格,因为$1,$3之间有一个逗号。逗号比较特殊,它映射为另一个内部变量,称为输出字段分隔符OFS,OFS默认为空格 + +(5)awk输出之后,将从文件中获取另一行,并将其存储在$0中,覆盖原来的内容,然后将新的字符串分隔成字段并进行处理。该过程将持续到所有行处理完毕 +``` + +#### 4.内建变量 + +```shell +$0: awk变量$0保存当前记录的内容 +[root@xingdiancloud ~]# awk -F: '{print $0}' /etc/passwd +NR: The total number of input records seen so far. +[root@xingdiancloud ~]# awk -F: '{print NR, $0}' /etc/passwd /etc/hosts +FNR: The input record number in the current input file +[root@xingdiancloud ~]# awk -F: '{print FNR, $0}' /etc/passwd /etc/hosts +NF: 保存记录的字段数,$1,$2...$100 +[root@xingdiancloud ~]# awk -F: '{print $0,NF}' /etc/passwd +FS: 输入字段分隔符,默认空格 +[root@xingdiancloud ~]# awk -F: '/alice/{print $1, $3}' /etc/passwd +[root@xingdiancloud ~]# awk -F'[ :\t]' '{print $1,$2,$3}' /etc/passwd +[root@xingdiancloud ~]# awk 'BEGIN{FS=":"} {print $1,$3}' /etc/passwd +OFS: 输出字段分隔符 +[root@xingdiancloud ~]# awk -F: '/alice/{print $1,$2,$3,$4}' /etc/passwd +[root@xingdiancloud ~]# awk 'BEGIN{FS=":"; OFS="+++"} /^root/{print $1,$2,$3,$4}' passwd +RS The input record separator, by default a newline. 默认是回车 +[root@xingdiancloud ~]# awk -F: 'BEGIN{RS=" "} {print $0}' a.txt +ORS The output record separator, by default a newline. +[root@xingdiancloud ~]# awk -F: 'BEGIN{ORS=""} {print $0}' passwd +``` + +注意: + +​ 字段分隔符: FS OFS 默认空格或制表符 + +​ 记录分隔符: RS ORS 默认换行符 + +案例: + +```shell +[root@xingdiancloud ~]# awk 'BEGIN{ORS=" "} {print $0}' /etc/passwd +#将文件每一行合并为一行 +ORS默认输出一条记录应该回车,加了一个空格 + +[root@xingdiancloud ~]# head -1 /etc/passwd > passwd1 +[root@xingdiancloud ~]# cat passwd1 +root:x:0:0:root:/root:/bin/bash +[root@xingdiancloud ~]# +[root@xingdiancloud ~]# awk 'BEGIN{RS=":"} {print $0}' passwd1 +root +x +0 +0 +root +/root +/bin/bash + +[root@xingdiancloud ~]# awk 'BEGIN{RS=":"} {print $0}' passwd1 |grep -v '^$' > passwd2 +``` + +#### 5.格式化输出 + +print函数 + +```shell +[root@xingdiancloud ~]# date |awk '{print "Month: " $2 "\nYear: " $NF}' +[root@xingdiancloud ~]# awk -F: '{print "username is: " $1 "\t uid is: " $3}' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{print "\tusername and uid: " $1,$3 "!"}' /etc/passwd +``` + +printf函数 + +```shell +[root@xingdiancloud ~]# awk -F: '{printf "%-15s %-10s %-15s\n", $1,$2,$3}' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{printf "|%-15s| %-10s| %-15s|\n", $1,$2,$3}' /etc/passwd + +%s 字符类型 +%d 数值类型 +%f 浮点类型 +占15字符 +- 表示左对齐,默认是右对齐 +printf默认不会在行尾自动换行,加\n +``` + +#### 6.awk模式和动作 + +​ 任何awk语句都由模式和动作组成。模式部分决定动作语句何时触发及触发事件。处理即对数据进行的操作。如果省略模式部分,动作将时刻保持执行状态。模式可以是任何条件语句或复合语句或正则表达式。模式包括两个特殊字段 BEGIN和END。使用BEGIN语句设置计数和打印头。BEGIN语句使用在任何文本浏览动作之前,之后文本浏览动作依据输入文本开始执行。END语句用来在awk完成文本浏览动作后打印输出文本总数和结尾状态 + +##### 模式 + +​ 正则表达式 + +```shell +匹配记录(整行):~匹配 +[root@xingdiancloud ~]# awk '/^alice/' /etc/passwd +[root@xingdiancloud ~]# awk '$0 ~ /^alice/' /etc/passwd +[root@xingdiancloud ~]# awk '!/alice/' passwd +[root@xingdiancloud ~]# awk '$0 !~ /^alice/' /etc/passwd + +匹配字段:匹配操作符(~ !~) +[root@xingdiancloud ~]# awk -F: '$1 ~ /^alice/' /etc/passwd +[root@xingdiancloud ~]# awk -F: '$NF !~ /bash$/' /etc/passw +``` + +​ 比较表达式 + +​ 比较表达式采用对文本进行比较,只有当条件为真,才执行指定的动作。比较表达式使用关系运算符,用于比较数字与字符串 + +```shell +运算符 含义 示例 +< 小于 x= 大于等于 x>=y +> 大于 x>y +``` + +```shell +[root@xingdiancloud ~]# awk -F: '$3 == 0' /etc/passwd +[root@xingdiancloud ~]# awk -F: '$3 < 10' /etc/passwd +[root@xingdiancloud ~]# awk -F: '$NF == "/bin/bash"' /etc/passwd +[root@xingdiancloud ~]# awk -F: '$1 == "alice"' /etc/passwd +[root@xingdiancloud ~]# awk -F: '$1 ~ /alic/ ' /etc/passwd +[root@xingdiancloud ~]# awk -F: '$1 !~ /alic/ ' /etc/passwd +[root@xingdiancloud ~]# df -P | grep '/' |awk '$4 > 25000' +``` + +​ 条件表达式 + +```shell +[root@xingdiancloud ~]# awk -F: '$3>300 {print $0}' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{ if($3>300) {print $0} }' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{ if($3>300) {print $3} else{print $1} }' /etc/passwd +``` + +​ 算术运算 + +```shell ++ - * / %(模) ^(幂2^3) + +[root@xingdiancloud ~]# awk -F: '$3 * 10 > 500' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{ if($3*10>500){print $0} }' /etc/passwd +``` + +​ 逻辑操作符和复合模式 + +```shell +&& 逻辑与 a&&b +|| 逻辑或 a||b +! 逻辑非 !a 除了这个以外的 + +[root@xingdiancloud ~]# awk -F: '$1~/root/ && $3<=15' /etc/passwd +[root@xingdiancloud ~]# awk -F: '$1~/root/ || $3<=15' /etc/passwd +[root@xingdiancloud ~]# awk -F: '!($1~/root/ || $3<=15)' /etc/passwd +``` + +##### 示例 + +```ini +[root@xingdiancloud ~]# awk '/west/' datafile +[root@xingdiancloud ~]# awk '/^north/' datafile +[root@xingdiancloud ~]# awk '$3 ~ /^north/' datafile +[root@xingdiancloud ~]# awk '/^(no|so)/' datafile +[root@xingdiancloud ~]# awk '{print $3,$2}' datafile + +[root@xingdiancloud ~]# awk '{print $3 $2}' datafile +[root@xingdiancloud ~]# awk '{print $0}' datafile +[root@xingdiancloud ~]# awk '/northeast/{print $3,$2}' datafile +[root@xingdiancloud ~]# awk '/E/' datafile + +[root@xingdiancloud ~]# awk '/^[ns]/{print $1}' datafile +[root@xingdiancloud ~]# awk '$5 ~ /\.[7-9]+/' datafile +[root@xingdiancloud ~]# awk '$2 !~ /E/{print $1,$2}' datafile +[root@xingdiancloud ~]# awk '$3 ~ /^Joel/{print $3 " is a nice boy."}' datafile +[root@xingdiancloud ~]# awk '$8 ~ /[0-9][0-9]$/{print $8}' datafile + +[root@xingdiancloud ~]# awk '$4 ~ /Chin$/{print "The price is $" $8 "."}' datafile +[root@xingdiancloud ~]# awk '/Tj/{print $0}' datafile +[root@xingdiancloud ~]# awk '{print $1}' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{print $1}' /etc/passwd +[root@xingdiancloud ~]# awk '{print "Number of fields: "NF}' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{print "Number of fields: "NF}' /etc/passwd +[root@xingdiancloud ~]# awk -F"[ :]" '{print NF}' /etc/passwd +[root@xingdiancloud ~]# awk -F"[ :]+" '{print NF}' /etc/passwd +[root@xingdiancloud ~]# awk '$7 == 5' datafile +[root@xingdiancloud ~]# awk '$2 == "CT" {print $1, $2}' datafile +[root@xingdiancloud ~]# awk '$7 != 5' datafile + +[root@xingdiancloud ~]# cat b.txt +xingdian sheng:is a::good boy! +[root@xingdiancloud ~]# awk '{print NF}' b.txt +4 +[root@xingdiancloud ~]# awk -F: '{print NF}' b.txt +4 +[root@xingdiancloud ~]# awk -F"[ :]" '{print NF}' b.txt +7 +[root@xingdiancloud ~]# awk -F"[ :]+" '{print NF}' b.txt +6 + +[root@xingdiancloud ~]# awk '$7 < 5 {print $4, $7}' datafile #{if($7<5){print $4,$7}} +[root@xingdiancloud ~]# awk '$6 > 9 {print $1,$6}' datafile +[root@xingdiancloud ~]# awk '$8 <= 17 {print $8}' datafile +[root@xingdiancloud ~]# awk '$8 >= 17 {print $8}' datafile +[root@xingdiancloud ~]# awk '$8 > 10 && $8 < 17' datafile + +[root@xingdiancloud ~]# awk '$2 == "NW" || $1 ~ /south/ {print $1, $2}' datafile +[root@xingdiancloud ~]# awk '!($8 == 13){print $8}' datafile #$8 != 13 +[root@xingdiancloud ~]# awk '/southem/{print $5 + 10}' datafile +[root@xingdiancloud ~]# awk '/southem/{print $8 + 10}' datafile +[root@xingdiancloud ~]# awk '/southem/{print $5 + 10.56}' datafile + +[root@xingdiancloud ~]# awk '/southem/{print $8 - 10}' datafile +[root@xingdiancloud ~]# awk '/southem/{print $8 / 2 }' datafile +[root@xingdiancloud ~]# awk '/southem/{print $8 / 3 }' datafile +[root@xingdiancloud ~]# awk '/southem/{print $8 * 2 }' datafile +``` + +#### 7.脚本编程-条件判断 + +if语句 + +```shell +{if(表达式){语句;语句;...}} +[root@xingdiancloud ~]# awk -F: '{if($3==0) {print $1 " is administrator."}}' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{if($3>0 && $3<1000){count++;}} END{print count}' /etc/passwd +``` + +if...else语句 + +```shell +{if(表达式){语句;语句;...}else{语句;语句;...}} +[root@xingdiancloud ~]# awk -F: '{if($3==0){print $1} else {print $7}}' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{if($3==0) {count++} else{i++} }' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{if($3==0){count++} else{i++}} END{print "管理员个数: "count ; print "系统用户数: "i}' /etc/passwd +``` + +if...else if...else语句 + +```shell +{if(表达式1){语句;语句;...}else if(表达式2){语句;语句;...}else if(表达式3){语句;语句;...}else{语句;语句;...} +[root@xingdiancloud ~]# awk -F: '{if($3==0){i++} else if($3>999){k++} else{j++}} END{print i; print k; print j}' /etc/passwd +[root@xingdiancloud ~]# awk -F: '{if($3==0){i++} else if($3>999){k++} else{j++}} END{print "管理员个数: "i; print "普通用个数: "k; print "系统用户: "j}' /etc/passwd +``` + +#### 8.脚本编程-循环 + +while: + +```shell +[root@xingdiancloud ~]# awk 'BEGIN{ i=1; while(i<=10){print i; i++} }' +[root@xingdiancloud ~]# awk -F: '/^root/{i=1; while(i<=7){print $i; i++}}' passwd +[root@xingdiancloud ~]# awk '{i=1; while(i<=NF){print $i; i++}}' /etc/hosts +[root@xingdiancloud ~]# awk -F: '{i=1; while(i<=10) {print $0; i++}}' /etc/passwd //将每行打印10次 +[root@xingdiancloud ~]# cat b.txt +111 222 +333 444 555 +666 777 888 999 +[root@xingdiancloud ~]# awk '{i=1; while(i<=NF){print $i; i++}}' b.txt //分别打印每行的每列 +111 +222 +333 +444 +555 +666 +777 +888 +999 +``` + +for: + +```she +[root@xingdiancloud ~]# awk 'BEGIN{for(i=1;i<=5;i++){print i} }' //C风格for +1 +2 +3 +4 +5 +[root@xingdiancloud ~]# awk -F: '{ for(i=1;i<=10;i++) {print $0} }' /etc/passwd //将每行打印10次 +[root@xingdiancloud ~]# awk -F: '{ for(i=1;i<=NF;i++) {print $i} }' passwd //分别打印每行的每列 +root +x +0 +0 +root +/root +/bin/bash +bin +x +1 +1 +bin +/bin +/sbin/nologin +``` + +#### 9.脚本编程-数组 + +案例一: + +```shell +[root@xingdiancloud ~]# awk -F: '{username[i++]=$1} END{print username[1]}' /etc/passwd +bin +[root@xingdiancloud ~]# awk -F: '{username[i++]=$1} END{print username[0]}' /etc/passwd +root +``` + +数组遍历: + +​ 按元素个数遍历 + +```shell +[root@xingdiancloud ~]# awk -F: '{username[x++]=$1} END{for(i=0;i,\(\),\{\}, \+, \| +egrep(或grep -E): 使用扩展元字符集 ?, +, { }, |, ( ) +注:grep也可以使用扩展集中的元字符,仅需要对这些元字符前置一个反斜线 + +\w 所有字母与数字,称为字符[a-zA-Z0-9] 'l[a-zA-Z0-9]*ve' 'l\w*ve' +\W 所有字母与数字之外的字符,称为非字符 'love[^a-zA-Z0-9]+' 'love\W+' +\b 词边界 '\' '\blove\b' +``` + +#### 3.grep示例 + +```shell +[root@xingdiancloud ~]# egrep 'N\W' datafile +[root@xingdiancloud ~]# egrep '^n' datafile +[root@xingdiancloud ~]# egrep '4$' datafile +[root@xingdiancloud ~]# egrep '5\..' datafile +[root@xingdiancloud ~]# egrep '\.5' datafile +[root@xingdiancloud ~]# egrep '^[we]' datafile +[root@xingdiancloud ~]# egrep '[^0-9]' datafile +[root@xingdiancloud ~]# egrep '[A-Z][A-Z] [A-Z]' datafile +[root@xingdiancloud ~]# egrep 'ss* ' datafile +[root@xingdiancloud ~]# egrep '[a-z]{9}' datafile +[root@xingdiancloud ~]# egrep '\' datafile +[root@xingdiancloud ~]# egrep '\<[a-r].*n\>' datafile +[root@xingdiancloud ~]# egrep '^n\w*\W' datafile +[root@xingdiancloud ~]# egrep '\bnorth\b' datafile +[root@xingdiancloud ~]# egrep '3+' datafile +[root@xingdiancloud ~]# egrep '2\.?[0-9]' datafile +[root@xingdiancloud ~]# egrep '(no)+' datafile +[root@xingdiancloud ~]# egrep 'S(h|u)' datafile +``` + +#### 4.grep参数 + +```shell +-i, --ignore-case 忽略大小写 +-l, --files-with-matches 只列出匹配行所在的文件名 +-n, --line-number 在每一行前面加上它在文件中的相对行号 +-c, --count 显示成功匹配的行数 +-s, --no-messages 禁止显示文件不存在或文件不可读的错误信息 +-q, --quiet, --silent 静默--quiet, --silent +-v, --invert-match 反向查找,只显示不匹配的行 +-R, -r, --recursive 递归针对目录 +--color 颜色 +-o, --only-matching 只显示匹配的内容 +``` + +示例: + +```shell +[root@xingdian ~]# grep -R 'ifcfg' /etc 目录 + +[root@xingdian ~]# egrep 'root' /etc/passwd /etc/shadow /etc/hosts +/etc/passwd:root:x:0:0:root:/root:/bin/bash +/etc/passwd:operator:x:11:0:operator:/root:/sbin/nologin +/etc/shadow:root:$6$gcO6Vp4t$OX9LmVgpjtur67UQdUYfw7vJW.78.uRXCLIxw4mBk82Z99:7::: + +[root@xingdian ~]# egrep -l 'root' /etc/passwd /etc/shadow /etc/hosts +/etc/passwd +/etc/shadow + +[root@xingdian ~]# egrep -n 'root' /etc/passwd /etc/shadow /etc/hosts +/etc/passwd:1:root:x:0:0:root:/root:/bin/bash +/etc/passwd:11:operator:x:11:0:operator:/root:/sbin/nologin +/etc/shadow:1:root:$6$gcO6Vp4t$OX9LmVgpjtur67UQdUy8.M78.uRXCLIxw4mBk82ZrNlxyf54 + + +[root@xingdian ~]# egrep -R '54:04:A6:CE:C2:1F' /etc/sysconfig/ + +[root@xingdian ~]# egrep '^IPADDR' /etc/sysconfig/network-scripts/ifcfg-eth0 |egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' +192.168.2.254 +[root@xingdian ~]# egrep '^IPADDR' /etc/sysconfig/network-scripts/ifcfg-eth0 |egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' +192.168.2.254 +``` + + + + + diff --git a/shell-MD/shell函数.md b/shell-MD/shell函数.md new file mode 100644 index 0000000..8b7f6e8 --- /dev/null +++ b/shell-MD/shell函数.md @@ -0,0 +1,230 @@ +

shell函数

+ +作者:行癫(盗版必究) + +------ + +## 一:函数 + +#### 1.函数介绍 + +​ Shell 函数的本质是一段可以重复使用的脚本代码,这段代码被提前编写好了,放在了指定的位置,使用时直接调取即可 + +#### 2.语法格式 + +```shell +function name() { + statements + [return value] +} +``` + +​ function是 Shell 中的关键字,专门用来定义函数(可以省略) + +​ name是函数名 + +​ statements是函数要执行的代码,也就是一组命令 + +​ return value表示函数的返回值,其中 return 是 Shell 关键字,专门用在函数中返回一个值(可以省略) + +#### 3.函数定义 + +```shell +myfunc(){ +echo "This is a new function" +} +``` + +#### 4.函数调用 + +​ 直接用函数名字调用函数 + +#### 5.函数传参 + +```shell +[root@xingdiancloud ~]# cat hello.sh +#!/bin/bash +hello(){ + echo $1 +} +hello xingdian +[root@xingdiancloud ~]# bash hello.sh +xingdian +``` + +#### 6.函数变量 + +```shell +[root@xingdiancloud ~]# cat hello.sh +#!/bin/bash +i=0 +echo "$a" +hello(){ + a=1 + local d=3 + echo "$i $a $b $c $d" +} +hello +b=2 +echo "$a $d" +[root@xingdiancloud ~]# bash hello.sh + +0 1 3 +1 +``` + +注意: + +​ 默认,函数里的变量会在函数外面生效 + +​ 注意脚本中内容按上下文顺序执行 + +​ local定义的变量只在函数内生效 + +#### 7.调用函数 + +​ 创建功能函数 + +```shell +[root@xingdiancloud ~]# cat hello.sh +#!/bin/bash +hello(){ + echo "This is one" +} +``` + +​ 另一个脚本调用该脚本中函数 + +```shell +[root@xingdiancloud ~]# cat xingdian.sh +#!/bin/bash +source ./hello.sh +hello +[root@xingdiancloud ~]# bash xingdian.sh +This is one +``` + +#### 8.函数案例 + +```shell +#!/bin/bash +#v1.24.5.27.1 +#作者:行癫 + +list() +{ + echo "+++++++++++++++++++++++++++++++++" + echo "+++++++ 百宝箱 ++++++++" + echo "+++++++++++++++++++++++++++++++++" + echo "|||||||||||||||||||||||||||||||||" + echo "=================================" + echo "= 1.yum仓库初始化 =" + echo "= 2.上课笔记工具安装 =" + echo "= 3.kvm虚拟机安装 =" + echo "= 4.vmware虚拟机安装 =" + echo "= 5.vs code安装 =" + echo "= 6.google浏览器安装 =" + echo "= 7.vnc-server的安装 =" + echo "= 8.一键安装所有 =" + echo "= 9.退出 =" + echo "=================================" +} +yum-install(){ + echo "====正在执行yum初始化操作请耐心等待!====" + rm -rf /etc/yum.repos.d/* + curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo > /dev/null + yum -y install wget > /dev/null + wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo + echo "====正在清空缓存,请耐心等待!====" + yum clean all + echo "====正在重新加载,请耐心等待!====" + yum makecache + echo "====successed====" +} + +cherrytree(){ + echo "====正在进行安装......=====" + yum -y install cherrytree > /dev/null + if [ $? -eq 0 ];then + echo "====successed====" + else + echo "==== failed ====" + echo "====检查网络和yum仓库====" + exit + fi +} + +kvm-install(){ + echo "====正在安装kvm虚拟机====" + yum -y install libvirt* virt-manager >> /dev/null && yum -y groupinstall 'Virtualization Host' >> /dev/null + echo "==== successed ====" +} + +vmware-install(){ + echo "====请将vmware安装包放到当前目录下====" + chmod +x + echo "......." + echo "..........." + echo ".................100%" + +} + +data=`date | awk '{print $4}'` +read -p "当前时间为${data},你是否要进行电脑初始化,继续请按回车(已记录你的初始时间):" + +ping -c1 www.baidu.com 1> /dev/null + +if [ $? -eq 0 ];then + echo "网络状况良好,请继续~" +else + echo "网络状况不佳,检查网络~" + exit +fi + +echo "xingdian" > user.txt +echo "dianye" > password.txt + +read -p "欢迎使用行癫工具箱,进行安装部署操作:" + +read -p "请输入用户名:" name + +username=`cat user.txt | awk '{print $1}'` +passwd=`cat password.txt | awk '{print $1}'` + +if [ "${name}" == "${username}" ];then + read -p "请输入密码:" password + if [ "${password}" == "${passwd}" ];then + echo "登陆成功,进入工具箱" + while : + do + list + read -p "请选择你要使用的工具代码:" num + case $num in + 1) + yum-install + sleep 3 + ;; + 2) + cherrytree + sleep 3 + ;; + 3) + ;; + 4) + ;; + 9) + break + ;; + esac + done + data2=`date | awk '{print $4}'` + echo "结束时间为${data2};感谢您的使用!" + else + echo "用户名密码错误,请重新执行脚本!" + exit + fi +else + echo "用户名输入错误,请重新输入!" + exit +fis +``` diff --git a/shell-MD/shell数组.md b/shell-MD/shell数组.md new file mode 100644 index 0000000..1c9455b --- /dev/null +++ b/shell-MD/shell数组.md @@ -0,0 +1,205 @@ +

shell数组

+ +作者:行癫(盗版必究) + +------ + +## 一:数组 + +#### 1.数组介绍 + +​ 是若干数据的集合,其中的每一份数据都称为元素 + +​ shell不限制数组的大小,理论上可以存放无限量的数据 + +#### 2.数组分类 + +​ 普通数组 + +​ 只能使用整数作为数组索引/下标(从0开始) + +​ 关联数组 + +​ 可以使用字符串作为数组索引/下标 + +#### 3.定义数组 + +##### 普通数组 + +​ 方法一: 一次赋一个值 + +```shell +数组名[索引]=变量值 +[root@xingdiancloud ~]# array1[0]=pear +[root@xingdiancloud ~]# array1[1]=apple +[root@xingdiancloud ~]# array1[2]=orange +[root@xingdiancloud ~]# array1[3]=peach +``` + +​ 方法二: 一次赋多个值 + +```shell +[root@xingdiancloud ~]# array2=(tom jack alice) +[root@xingdiancloud ~]# array5=(tom jack alice "bash shell") +[root@xingdiancloud ~]# colors=($red $blue $green $recolor) +[root@xingdiancloud ~]# array5=(1 2 3 4 5 6 7 "linux shell" [20]=saltstack) +[root@xingdiancloud ~]# array8=`cat /etc/passwd` +``` + +##### 关联数组 + +​ 申明该数组为关联数组 + +```shell +[root@xingdiancloud ~]# declare -A ass_array1 +[root@xingdiancloud ~]# declare -A ass_array2 +``` + +​ 方法一: 一次赋一个值 + +```shell +数组名[索引]=变量值 +[root@xingdiancloud ~]# ass_array1[index1]=pear +[root@xingdiancloud ~]# ass_array1[index2]=apple +[root@xingdiancloud ~]# ass_array1[index3]=orange +[root@xingdiancloud ~]# ass_array1[index4]=peach +``` + +​ 方法二: 一次赋多个值 + +```shell +[root@xingdiancloud ~]# ass_array2=([index1]=tom [index2]=jack [index3]=alice [index4]='bash shell') +``` + +​ 一步走 + +```shell +[root@xingdiancloud ~]# declare -A ass_array1='([index4]="peach" [index1]="pear" [index2]="apple" [index3]="orange" )' +[root@xingdiancloud ~]# declare -A ass_array2='([index4]="bash shell" [index1]="tom" [index2]="jack" [index3]="alice" )' +``` + +#### 4.访问数组元素 + +##### 普通数组 + +```shell +[root@xingdiancloud ~]# echo ${array1[0]} 访问数组中的第一个元数 +[root@xingdiancloud ~]# echo ${array1[@]} 访问数组中所有元数 等同于 echo ${array1[*]} +[root@xingdiancloud ~]# echo ${#array1[@]} 统计数组元数的个数 +[root@xingdiancloud ~]# echo ${!array2[@]} 获取数组元数的索引 +[root@xingdiancloud ~]# echo ${array1[@]:1} 从数组下标1开始 +[root@xingdiancloud ~]# echo ${array1[@]:1:2} 从数组下标1开始,访问两个元素 +``` + +##### 关联数组 + +```shell +[root@xingdiancloud ~]# echo ${ass_array2[index2]} 访问数组中的第二个元数 +[root@xingdiancloud ~]# echo ${ass_array2[@]} 访问数组中所有元数 等同于 echo ${array1[*]} +[root@xingdiancloud ~]# echo ${#ass_array2[@]} 获得数组元数的个数 +[root@xingdiancloud ~]# echo ${!ass_array2[@]} 获得数组元数的索引 +``` + +#### 5.数组遍历 + +​ 方法一: 通过数组元数的个数进行遍历 + +​ 方法二: 通过数组元数的索引进行遍历 + +案例一:利用元素进行遍历 + +```shell +#!/bin/bash +#定义数组 +array=(Mon Tue Wed Thur Fir Sat Sun) +#数组遍历 +for day in ${array[*]} +do + echo $day +done +``` + +案例二:利用索引进行遍历 + +``` +[root@xingdiancloud ~]# cat hello.sh +#!/bin/bash +for line in `cat /etc/hosts` +do + hosts[++j]=$line +done + +for i in ${!hosts[@]} +do + echo "$i : ${hosts[i]}" +done +[root@xingdiancloud ~]# bash hello.sh +1 : 127.0.0.1 +2 : localhost +3 : localhost.localdomain +4 : localhost4 +5 : localhost4.localdomain4 +6 : ::1 +7 : localhost +8 : localhost.localdomain +9 : localhost6 +10 : localhost6.localdomain6 +``` + +​ 定义换行符 + +```shell +[root@xingdiancloud ~]# cat hello.sh +#!/bin/bash +IFS=$'\n' +for line in `cat /etc/hosts` +do + hosts[++j]=$line +done + +for i in ${!hosts[@]} +do + echo "$i : ${hosts[i]}" +done +[root@xingdiancloud ~]# bash hello.sh +1 : 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 +2 : ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 +``` + +#### 6.项目案例 + +​ 通过数组统计性别:把要统计的对象作为数组的索引 + +```shell +[root@xingdiancloud ~]# cat sex.txt +zhangsan f +lisi m + +[root@xingdiancloud ~]# cat sex.sh +#!/usr/bin/bash +declare -A sex +while read line +do + type=`echo $line | awk '{print $2}'` + let sex[$type]++ +done < sex.txt +#m作为数组的索引 + +for i in ${!sex[@]} +do + echo "$i : ${sex[$i]}" +done +``` + + + + + + + + + + + + + diff --git a/shell-MD/shell脚本案例 (1).md b/shell-MD/shell脚本案例 (1).md new file mode 100644 index 0000000..d5fd7f5 --- /dev/null +++ b/shell-MD/shell脚本案例 (1).md @@ -0,0 +1,379 @@ +

shell脚本案例

+ +作者:行癫(盗版必究) + +------ + +## 一:脚本案例 + +#### 1.配置静态IP案例 + +```shell +#!/bin/bash +# This script configures a static IP address on CentOS 7 + +# Define variables for the IP address, netmask, gateway, and DNS servers +IP_ADDRESS=192.168.1.100 +NETMASK=255.255.255.0 +GATEWAY=192.168.1.1 +DNS_SERVERS="8.8.8.8 114.114.114.114" + +# Backup the original network configuration file +cp /etc/sysconfig/network-scripts/ifcfg-ens33 /etc/sysconfig/network-scripts/ifcfg-ens33.bak + +# Modify the network configuration file with the static IP address, netmask, gateway, and DNS servers +cat << EOF > /etc/sysconfig/network-scripts/ifcfg-ens33 +TYPE=Ethernet +BOOTPROTO=none +NAME=ens33 +DEVICE=ens33 +ONBOOT=yes +IPADDR=$IP_ADDRESS +NETMASK=$NETMASK +GATEWAY=$GATEWAY +DNS1=${DNS_SERVERS%% *} +DNS2=${DNS_SERVERS##* } +EOF + +# Restart the network service to apply the changes +systemctl restart network + +# Display the new network configuration +ip addr show ens33 +``` + +centos stream 9 + +```shell +[root@xingdiancloud ~]# bash network.sh +#!/bin/bash +#auther:xingdian +NET_DIR=`ls /etc/NetworkManager/system-connections/` +NET_PATH="/etc/NetworkManager/system-connections/" +read -p "请输入IP地址: " ipadd +read -p "请输入子网掩码,例如24: " netmask +read -p "请输入默认网关: " gateway +read -p "请输入dns地址: " dns +read -p "输入设备名字: " name +# 备份原配置 +if [ -f ${NET_PATH}${name}.nmconnection.bak ];then + rm -rf ${NET_PATH}${name}.nmconnection.bak +else + cp ${NET_PATH}${NET_DIR} ${NET_PATH}${NET_DIR}.bak +fi +cat > ${NET_PATH}${name}.nmconnection < /dev/null + + if [ $? -eq 0 ];then + echo "防火墙已经成功关闭....." + else + echo "防火墙关闭失败,请手动关闭!!!" + fi + + setenforce 0 && sed -i '/^SELINUX/c SELINUX=disabled' /etc/selinux/config + + if [ $? -eq 0 ];then + echo "selinux已经成功关闭....." + else + echo "selnux关闭失败,请手动关闭!!!" + fi +echo + +# 外网检测 +echo "正在检测网络是否能上外网......" + +echo + + ping -c 2 www.baidu.com &> /dev/null + + if [ $? -eq 0 ];then + echo "网络正常" + else + echo "网络不可达!" + fi +echo + +# 配置yum源-这里选用阿里源 + +echo "配置yum源中....." +echo + yum install -y wget &> /dev/null + if [ $? -ne 0 ];then + echo "wget 安装失败........." + systemctl restart network + yum repolist &> /dev/null + sleep 2 + fi + mkdir -p /root/YUM_backup + mv /etc/yum.repos.d/* /root/YUM_backup + wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo &>/dev/null + wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo &>/dev/null + yum clean all &>/dev/null && yum reppolist &>/dev/null + echo "你的yum源有:" $(ls /etc/yum.repos.d) + sleep 2 + +# 配置主机名和host文件 + +echo "正在配置你的主机名..." + +echo + read -p "请输入你的主机名:" host + + hostname(){ + hostnamectl set-hostname $host + } + hostname host && echo -e "主机名设置成功!!" + +echo "正在配置你的hosts文件..." + ip=$(ip a | grep ens33 |grep inet |awk '{print $2}' | awk -F"/" '{print $1}') + echo "$ip $host" >> /etc/hosts + echo "hosts配置完成!!!" + +# 安装基础软件包 + + echo "安装基础软件包中....." + echo + + yum install -y vim wget unzip yum_utils &>/dev/null + if [ $? -eq 0 ];then + echo "安装完成....." + else + echo "安装失败..... " + fi +# 时间同步 +echo + echo "时间同步中……" + yum install -y ntpdate &> /dev/null + ntpdate cn.pool.ntp.org &> /dev/null + file=$(who | head -1 | cut -d" " -f1) + echo "* */1 * * * /usr/sbin/ntpdate cn.pool.ntp.org" > /var/spool/cron/$file + if [ $? -eq 0 ];then + echo "时间同步成功!!!" + echo "unset MAILCHECK" >> /etc/profile + source /etc/profile &> /dev/null + else + echo "时间同步失败!!!" + fi +``` + +#### 3.获取系统信息 + +```shell +#!/bin/bash +#此脚本获取系统centos7.x/centos stream9.x +#auther:xingdian + +#查看服务器硬件型号 +hard_type=`dmidecode |grep "Product Name"|tr "\n" " "` #获取服务器型号 +sn=`dmidecode |grep -A 3 "Product Name" |grep "Serial Number"|grep -v "None"` #获取硬件序列码 + +##系统信息 +version=`cat /etc/redhat-release` #版本 +kernel=`uname -r` #内核 + +##cpu +phy_cpu_num=`grep 'physical id' /proc/cpuinfo | sort | uniq | wc -l` #物理CPU数量 +nuclear=`grep vendor_id /proc/cpuinfo|wc -l` #逻辑核数(线程) + +##内存\Swap +mem=`free -m|grep Mem|awk '{print $2"M"}'` #内存总大小 +user_mem=`free -m|grep Mem|awk '{print $3"M"}'` #已用内存大小 +swap=`free -m |grep Swap|awk '{print $2"M"}'` #swap总大小 +user_swap=`free -m |grep Swap|awk '{print $3"M"}'` #已用swap大小 + +#最大支持内存数 +max_memory=`dmidecode|grep -P 'Maximum\s+Capacity'` + +##负载 +loadavg=`uptime |awk -F: '{print $NF}'` #系统负载 + +##网络 +network=`[[ $(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" www.baidu.com) -eq 200 ]] && echo yes || echo no` #根据curl www.baidu.com的返回状态码来判断是否能上网 +ip_addr=`ip address|grep -w "inet"|grep -v "127.0.0.1"|awk -F "[ /]+" '{print $3,$NF}'` #获取除了回环地址之外的所有网卡的ip地址和对应的网卡名 +##磁盘 +disk_zong=`df -Th | grep -w '/' | awk '{print $3}'` #获取系统盘的总大小 +disk_user=`df -Th | grep -w '/' | awk '{print $4}'` #获取系统盘已用大小 +disk_lsbl=`lsblk` #硬盘分区分布 +##其他 +system_time=`awk '{a=$1/86400;b=($1%86400)/3600;c=($1%3600)/60;d=$1%60} {printf("%ddays, %d:%d:%d\n",a,b,c,d)}' /proc/uptime` #开机时长 +sys_begin=`date -d "$(awk -F. '{print $1}' /proc/uptime) second ago" +"%Y-%m-%d %H:%M:%S"` #开机时间 +##日志 +system_log=`du -sh /var/log/ |awk '{print $1}'` #系统日志大小 +#进程 +tasks=`top -n1 |grep Tasks |awk '{print $2,$4,6}'` #总 运行 休眠 + +system(){ +echo " +|硬件型号: +$hard_type +|序列号: +$sn +|版本: $version +|内核: $kernel + +|物理CPU个数:$phy_cpu_num 逻辑核数: $nuclear"个" +|负载:$loadavg + +|内存: $mem #最大支持内存:$max_memory +|已用: $user_mem +|swap: $swap +|已用: $user_swap + +|是否可以上网: $network +|本地IP地址: +$ip_addr + +|系统磁盘大小: $disk_zong +|系统磁盘已用: $disk_user +|日志: 系统日志大小为$system_log +|开机: $sys_begin +|至今: $system_time +硬盘分区 +---------------------------------------------------------------------- +$disk_lsbl +---------------------------------------------------------------------- + +---------------------------------------------------------------------- +" +} +system +##端口扫描 +echo "监听的端口扫描 +----------------------------------------------------------------------" +portarray=(`sudo netstat -tnlp|egrep -i "$1"|awk {'print $4'}|awk -F':' '{if ($NF~/^[0-9]*$/) print $NF}'|sort|uniq`) +length=${#portarray[@]} #统计元素个数 +printf "{\n" +printf '\t'port":" +for ((i=0;i<$length;i++)) +do +printf '\n\t\t{' +printf "\"{#TCP_PORT}\":\"${portarray[$i]}\"}" +if [ $i -lt $[$length-1] ];then +printf ',' +fi +done +printf "\n\t\n" +printf "}\n" +echo "---------------------------------------------------------------------- +" +``` + +#### 4.sshpass登录远程服务器与验证 + +```shell +sshpass安装后,可以在控制台输入sshpass命令查看所有选项参数: + +$ sshpass + +Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters + +-f filename Take password to use from file + +-d number Use number as file descriptor for getting password + +-p password Provide password as argument (security unwise) + +-e Password is passed as env-var "SSHPASS" + +With no parameters - password will be taken from stdin + +-P prompt Which string should sshpass search for to detect a password prompt + +-v Be verbose about what you're doing +-h Show help (this screen) +-V Print version information +At most one of -f, -d, -p or -e should be used +如上所示,command parameters为你要执行的需要交互式输入密码的命令,如:ssh、scp等。当sshpass没有指定参数时会从stdin获取密码,几个密码输入相关参数如下: +-f filename:从文件中获取密码 +-d number:使用数字作为获取密码的文件描述符 +-p password:指定明文本密码输入(安全性较差) +-e:从环境变量SSHPASS获取密码 + +远程连接指定ssh的端口: +[root@linuxcool ~]# sshpass -p "password" ssh username@ip +本地执行远程机器的命令: +[root@linuxcool ~]# sshpass -p "password" ssh -p 8443 username@ip +从密码文件读取文件内容作为密码去远程连接主机: +[root@linuxcool ~]# sshpass -p xxx ssh root@192.168.11.11 "ethtool eth0" +从远程主机上拉取文件到本地: +[root@linuxcool ~]# sshpass -p '123456' scp root@host_ip:/home/test/t ./tmp/ +``` + +#### 5.免密脚本 + +```shell +yum -y install expect +#生成并拷贝ssh_key到远程机器 +rm -rf /root/.ssh/* +/usr/bin/expect <
shell脚本案例
+ +作者:行癫(盗版必究) + +------ + +## 一:脚本案例 + +#### 1.配置静态IP案例 + +```shell +#!/bin/bash +# This script configures a static IP address on CentOS 7 + +# Define variables for the IP address, netmask, gateway, and DNS servers +IP_ADDRESS=192.168.1.100 +NETMASK=255.255.255.0 +GATEWAY=192.168.1.1 +DNS_SERVERS="8.8.8.8 114.114.114.114" + +# Backup the original network configuration file +cp /etc/sysconfig/network-scripts/ifcfg-ens33 /etc/sysconfig/network-scripts/ifcfg-ens33.bak + +# Modify the network configuration file with the static IP address, netmask, gateway, and DNS servers +cat << EOF > /etc/sysconfig/network-scripts/ifcfg-ens33 +TYPE=Ethernet +BOOTPROTO=none +NAME=ens33 +DEVICE=ens33 +ONBOOT=yes +IPADDR=$IP_ADDRESS +NETMASK=$NETMASK +GATEWAY=$GATEWAY +DNS1=${DNS_SERVERS%% *} +DNS2=${DNS_SERVERS##* } +EOF + +# Restart the network service to apply the changes +systemctl restart network + +# Display the new network configuration +ip addr show ens33 +``` + +centos stream 9 + +```shell +[root@xingdiancloud ~]# bash network.sh +#!/bin/bash +#auther:xingdian +NET_DIR=`ls /etc/NetworkManager/system-connections/` +NET_PATH="/etc/NetworkManager/system-connections/" +read -p "请输入IP地址: " ipadd +read -p "请输入子网掩码,例如24: " netmask +read -p "请输入默认网关: " gateway +read -p "请输入dns地址: " dns +read -p "输入设备名字: " name +# 备份原配置 +if [ -f ${NET_PATH}${name}.nmconnection.bak ];then + rm -rf ${NET_PATH}${name}.nmconnection.bak +else + cp ${NET_PATH}${NET_DIR} ${NET_PATH}${NET_DIR}.bak +fi +cat > ${NET_PATH}${name}.nmconnection < /dev/null + + if [ $? -eq 0 ];then + echo "防火墙已经成功关闭....." + else + echo "防火墙关闭失败,请手动关闭!!!" + fi + + setenforce 0 && sed -i '/^SELINUX/c SELINUX=disabled' /etc/selinux/config + + if [ $? -eq 0 ];then + echo "selinux已经成功关闭....." + else + echo "selnux关闭失败,请手动关闭!!!" + fi +echo + +# 外网检测 +echo "正在检测网络是否能上外网......" + +echo + + ping -c 2 www.baidu.com &> /dev/null + + if [ $? -eq 0 ];then + echo "网络正常" + else + echo "网络不可达!" + fi +echo + +# 配置yum源-这里选用阿里源 + +echo "配置yum源中....." +echo + yum install -y wget &> /dev/null + if [ $? -ne 0 ];then + echo "wget 安装失败........." + systemctl restart network + yum repolist &> /dev/null + sleep 2 + fi + mkdir -p /root/YUM_backup + mv /etc/yum.repos.d/* /root/YUM_backup + wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo &>/dev/null + wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo &>/dev/null + yum clean all &>/dev/null && yum reppolist &>/dev/null + echo "你的yum源有:" $(ls /etc/yum.repos.d) + sleep 2 + +# 配置主机名和host文件 + +echo "正在配置你的主机名..." + +echo + read -p "请输入你的主机名:" host + + hostname(){ + hostnamectl set-hostname $host + } + hostname host && echo -e "主机名设置成功!!" + +echo "正在配置你的hosts文件..." + ip=$(ip a | grep ens33 |grep inet |awk '{print $2}' | awk -F"/" '{print $1}') + echo "$ip $host" >> /etc/hosts + echo "hosts配置完成!!!" + +# 安装基础软件包 + + echo "安装基础软件包中....." + echo + + yum install -y vim wget unzip yum_utils &>/dev/null + if [ $? -eq 0 ];then + echo "安装完成....." + else + echo "安装失败..... " + fi +# 时间同步 +echo + echo "时间同步中……" + yum install -y ntpdate &> /dev/null + ntpdate cn.pool.ntp.org &> /dev/null + file=$(who | head -1 | cut -d" " -f1) + echo "* */1 * * * /usr/sbin/ntpdate cn.pool.ntp.org" > /var/spool/cron/$file + if [ $? -eq 0 ];then + echo "时间同步成功!!!" + echo "unset MAILCHECK" >> /etc/profile + source /etc/profile &> /dev/null + else + echo "时间同步失败!!!" + fi +``` + +#### 3.获取系统信息 + +```shell +#!/bin/bash +#此脚本获取系统centos7.x/centos stream9.x +#auther:xingdian + +#查看服务器硬件型号 +hard_type=`dmidecode |grep "Product Name"|tr "\n" " "` #获取服务器型号 +sn=`dmidecode |grep -A 3 "Product Name" |grep "Serial Number"|grep -v "None"` #获取硬件序列码 + +##系统信息 +version=`cat /etc/redhat-release` #版本 +kernel=`uname -r` #内核 + +##cpu +phy_cpu_num=`grep 'physical id' /proc/cpuinfo | sort | uniq | wc -l` #物理CPU数量 +nuclear=`grep vendor_id /proc/cpuinfo|wc -l` #逻辑核数(线程) + +##内存\Swap +mem=`free -m|grep Mem|awk '{print $2"M"}'` #内存总大小 +user_mem=`free -m|grep Mem|awk '{print $3"M"}'` #已用内存大小 +swap=`free -m |grep Swap|awk '{print $2"M"}'` #swap总大小 +user_swap=`free -m |grep Swap|awk '{print $3"M"}'` #已用swap大小 + +#最大支持内存数 +max_memory=`dmidecode|grep -P 'Maximum\s+Capacity'` + +##负载 +loadavg=`uptime |awk -F: '{print $NF}'` #系统负载 + +##网络 +network=`[[ $(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" www.baidu.com) -eq 200 ]] && echo yes || echo no` #根据curl www.baidu.com的返回状态码来判断是否能上网 +ip_addr=`ip address|grep -w "inet"|grep -v "127.0.0.1"|awk -F "[ /]+" '{print $3,$NF}'` #获取除了回环地址之外的所有网卡的ip地址和对应的网卡名 +##磁盘 +disk_zong=`df -Th | grep -w '/' | awk '{print $3}'` #获取系统盘的总大小 +disk_user=`df -Th | grep -w '/' | awk '{print $4}'` #获取系统盘已用大小 +disk_lsbl=`lsblk` #硬盘分区分布 +##其他 +system_time=`awk '{a=$1/86400;b=($1%86400)/3600;c=($1%3600)/60;d=$1%60} {printf("%ddays, %d:%d:%d\n",a,b,c,d)}' /proc/uptime` #开机时长 +sys_begin=`date -d "$(awk -F. '{print $1}' /proc/uptime) second ago" +"%Y-%m-%d %H:%M:%S"` #开机时间 +##日志 +system_log=`du -sh /var/log/ |awk '{print $1}'` #系统日志大小 +#进程 +tasks=`top -n1 |grep Tasks |awk '{print $2,$4,6}'` #总 运行 休眠 + +system(){ +echo " +|硬件型号: +$hard_type +|序列号: +$sn +|版本: $version +|内核: $kernel + +|物理CPU个数:$phy_cpu_num 逻辑核数: $nuclear"个" +|负载:$loadavg + +|内存: $mem #最大支持内存:$max_memory +|已用: $user_mem +|swap: $swap +|已用: $user_swap + +|是否可以上网: $network +|本地IP地址: +$ip_addr + +|系统磁盘大小: $disk_zong +|系统磁盘已用: $disk_user +|日志: 系统日志大小为$system_log +|开机: $sys_begin +|至今: $system_time +硬盘分区 +---------------------------------------------------------------------- +$disk_lsbl +---------------------------------------------------------------------- + +---------------------------------------------------------------------- +" +} +system +##端口扫描 +echo "监听的端口扫描 +----------------------------------------------------------------------" +portarray=(`sudo netstat -tnlp|egrep -i "$1"|awk {'print $4'}|awk -F':' '{if ($NF~/^[0-9]*$/) print $NF}'|sort|uniq`) +length=${#portarray[@]} #统计元素个数 +printf "{\n" +printf '\t'port":" +for ((i=0;i<$length;i++)) +do +printf '\n\t\t{' +printf "\"{#TCP_PORT}\":\"${portarray[$i]}\"}" +if [ $i -lt $[$length-1] ];then +printf ',' +fi +done +printf "\n\t\n" +printf "}\n" +echo "---------------------------------------------------------------------- +" +``` + +#### 4.sshpass登录远程服务器与验证 + +```shell +sshpass安装后,可以在控制台输入sshpass命令查看所有选项参数: + +$ sshpass + +Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters + +-f filename Take password to use from file + +-d number Use number as file descriptor for getting password + +-p password Provide password as argument (security unwise) + +-e Password is passed as env-var "SSHPASS" + +With no parameters - password will be taken from stdin + +-P prompt Which string should sshpass search for to detect a password prompt + +-v Be verbose about what you're doing +-h Show help (this screen) +-V Print version information +At most one of -f, -d, -p or -e should be used +如上所示,command parameters为你要执行的需要交互式输入密码的命令,如:ssh、scp等。当sshpass没有指定参数时会从stdin获取密码,几个密码输入相关参数如下: +-f filename:从文件中获取密码 +-d number:使用数字作为获取密码的文件描述符 +-p password:指定明文本密码输入(安全性较差) +-e:从环境变量SSHPASS获取密码 + +远程连接指定ssh的端口: +[root@linuxcool ~]# sshpass -p "password" ssh username@ip +本地执行远程机器的命令: +[root@linuxcool ~]# sshpass -p "password" ssh -p 8443 username@ip +从密码文件读取文件内容作为密码去远程连接主机: +[root@linuxcool ~]# sshpass -p xxx ssh root@192.168.11.11 "ethtool eth0" +从远程主机上拉取文件到本地: +[root@linuxcool ~]# sshpass -p '123456' scp root@host_ip:/home/test/t ./tmp/ +``` + +#### 5.免密脚本 + +```shell +yum -y install expect +#生成并拷贝ssh_key到远程机器 +rm -rf /root/.ssh/* +/usr/bin/expect <