1、字串截取
方法一
echo ${key:0:3} 語法:echo ${變量:起始位(從0開始): 長度}
[root@localhost test1]# phone=18318616159
[root@localhost test1]# echo ${phone:0:3}
183
[root@localhost test1]# echo ${phone:3:6}
186161
[root@localhost test1]# echo ${phone:3:3}
186
[root@localhost test1]#
方法二
語法:expr substr "$key" 起始位置(從1開始) 長度
[root@localhost test1]# phone=18318616159
[root@localhost test1]# expr substr "$phone" 1 3
183
[root@localhost test1]# expr substr "$phone" 6 2
61
[root@localhost test1]# expr substr "$phone" 3 3
318
[root@localhost test1]#
方法三
語法:cut -b 起始位(從1開始)—終止位
語法:cut -b 第一個位置,下一個位置,下一個位置
echo $key | cut -b 1-5
echo $key | cut -b 1,3,5
-b=--byte
[root@localhost test1]# phone=18318616159
[root@localhost test1]# echo $phone | cut -b 1-3 //第一位到第三位
183
[root@localhost test1]# echo $phone | cut -b 3-6
3186
[root@localhost test1]# echo $phone | cut -b 1,3,16 -------沒有第16位直接取空
13
[root@localhost test1]#
########
[root@localhost test1]# echo $phone | cut -b 1,3,5
138
######
-----------------------------------------------------------------------------------------------------------------------------
vim test.sh
key='abcdefghijklmnopqrstuvwxyz'
生成六位隨機數
expr substr "$key" 隨機數%26 1
- #!/bin/bash
- key='abcdefjhigklmnopqrstuvwxyz'
- for i in {1..6} // 6次
- do
- echo -n ${key:$[RANDOM]%26:1} //$[RANDOM]%26,每次循環都會取一個值。
- done
- echo
ping -c【count】 -i【interval間隔】 -W【 timeout】
- [root@svr5 ~]# vim chkhosts.sh
- #!/bin/bash
- HLIST=$(cat /root/ipadds.txt)
- for IP in $HLIST
- do
- ping -c 3 -i 0.2 -W 3 $IP &> /dev/null
- if [ $? -eq 0 ] ; then
- echo "Host $IP is up."
- else
- echo "Host $IP is down."
- fi
- done
總結:
- 語法:echo ${變量:起始位(從0開始): 長度}
- 語法:expr substr "$key" 起始位置(從1開始) 長度
- 語法:cut -b 起始位(從1開始)—終止位
- 語法:cut -b 第一個位置,下一個位置,下一個位置
PATH=命令搜索路徑
export PATH=/usr/local/mongodb/bin:$PATH------將/usr/local/mongodb/bin添加到執行文件路徑的變量:$PATH
方法四:
[root@localhost test]# basename /a/d/g/h/a.txt ------------//取文件名
a.txt
[root@localhost test]# dirname /a/b/c/v.txt -----------//取路徑
/a/b/c
2、字串替換
echo ${var/old/new} -------------替換第一個
echo ${var//old/new} ---------------全部替換
=======================================
vim中
:s/old/new //只替換光標的當前行
:%s/old/new //
tom jerry tom tom
hehe user tom
:%s/old/new/g // 替換每一行的所有
-----------------------------------------------------------------------------------------------
3.掐頭去尾
echo ${user#*:} 最短匹配掐頭
echo ${user##*:} 最長匹配掐頭
echo ${user%:*} 最短匹配去尾
echo ${user%%:*} 最長匹配去尾
一個#代表最短匹配,##代表最長匹配
[root@localhost test]# head -1 /etc/passwd
root:x:0:0:root:/root:/bin/bash
[root@localhost test]# user=`head -1 /etc/passwd`
[root@localhost test]# echo $user
root:x:0:0:root:/root:/bin/bash
[root@localhost test]# echo ${user#*:}
x:0:0:root:/root:/bin/bash
[root@localhost test]# echo ${user##*:}
/bin/bash
[root@localhost test]#
一個%代表最短匹配,%%代表最長匹配
[root@localhost test]# echo ${user%:*}
root:x:0:0:root:/root
[root@localhost test]# echo ${user%%:*}
root
[root@localhost test]#
eg:通用腳本
for i in `cat /etc/passwd`
do
echo $i 對$i去尾,:*刪除
done
#cd /var/tmp/ //最好先cd過去
touch {a,b,c,d,f}.txt
#
#
for in in `ls *.txt` //如或不cd過去,要寫絕對路徑
do
定義變量x= mv b.txt a.txt
mv $i 變量.doc
done
for in in `ls *.txt` //如或不cd過去,要寫絕對路徑
do
定義變量x={i%.*}}
mv $i 變量.doc
done
eg:
改擴展名
#!/bin/bash
for i in `ls *.txt`
do
x=${i%.*} //定義變量
mv $i $x.doc
done
改進:
#!/bin/bash
for i in `ls *.$1`
do
x=${i%.*} //定義變量
mv $i $x.$2
done
#!/bin/bash
read -p "請輸入用戶名:" user
[ -z $user ] && echo "您沒有輸入用戶名" && exit
read -s -p "請輸入密碼:" password
[ -z $password ] && echo "123" | passwd --stdin $user
useradd $user
echo $password | passwd --stdin $user
~
[root@localhost test]# echo $TTTTTTT
[root@localhost test]# echo ${TTTTTTT:-abc} //abc給變量賦初始值
abc
[root@localhost test]# TTTTTTT=123
[root@localhost test]# echo ${TTTTTTT:-abc}
123
[root@localhost test]#
vim mima.sh
#!/bin/bash
read -p "請輸入用戶名:" user
[ -z $user ] && echo "您沒有輸入用戶名" && exit
read -s -p "請輸入密碼:" password
password=${password:-123456} //如果沒有給密碼,就執行這一行命令。賦予初始值。
useradd $user
echo $password | passwd --stdin $user
: 截取
# 掐頭
% 去尾
:- 賦初始值
/etc/sysconfig/
grep "id" /proc/cpu
[root@room4pc09 桌面]# echo $[$(seq -s "+" 0 2 100)]
2550
seq -s
-s, --separator=STRING
use STRING to separate numbers (default: \n)
Top
NSD SHELL DAY04
案例1:字符串截取及切割
案例2:字符串初值的處理
案例3:使用Shell數組
案例4:expect預期交互
案例5:使用正則表達式
1 案例1:字符串截取及切割
1.1 問題
使用Shell完成各種Linux運維任務時,一旦涉及到判斷、條件測試等相關操作時,往往需要對相關的命令輸出進行過濾,提取出符合要求的字符串。
本案例要求熟悉字符串的常見處理操作,完成以下任務練習:
參考PPT示範操作,完成子串截取、替換等操作
根據課上的批量改名腳本,編寫改進版renfilex.sh:能夠批量修改當前目錄下所有文件的擴展名,修改前/後的擴展名通過位置參數$1、$2提供
1.2 方案
子串截取的三種用法:
${var:起始位置:長度}
expr substr "$var" 起始位置 長度
echo $var | cut -b 起始位置-結束位置
路徑分割:
取目錄位置:dirname "字符串"
取文檔的基本名稱:basename "字符串"
子串替換的兩種用法:
只替換第一個匹配結果:${var/old/new}
替換全部匹配結果:${var//old/new}
字符串掐頭去尾:
從左向右,最短匹配刪除:${變量名#*關鍵詞}
從左向右,最長匹配刪除:${變量名##*關鍵詞}
從右向左,最短匹配刪除:${變量名%關鍵詞*}
從右向左,最長匹配刪除:${變量名%%關鍵詞*}
1.3 步驟
實現此案例需要按照如下步驟進行。
步驟一:字符串的截取
1)方法一,使用 ${}表達式
格式:${var:起始位置:長度}
定義一個變量Phone,並確認其字符串長度:
[root@svr5 ~]# Phone="13788768897"
[root@svr5 ~]# echo ${#Phone}
11 //包括11個字符
使用${}截取時,起始位置可以省略,省略時從第一個字符開始截。比如,以下操作都可以從左側開始截取前6個字符:
[root@svr5 ~]# echo ${Phone::6}
137887
或者
[root@svr5 ~]# echo ${Phone:0:6}
137887
使用${}方式截取字符串時,起始位置是從0開始的(和數組下標編號類似) 。
因此,如果從起始位置1開始截取6個字符,那就變成這個樣子了:
[root@svr5 ~]# echo ${Phone:1:6}
378876
2)方法二,使用 expr substr
格式:expr substr "$var" 起始位置 長度
還以前面的Phone變量爲例,確認原始值:
[root@svr5 ~]# echo $Phone
13788768897
[root@svr5 ~]# echo ${#Phone}
11
使用expr substr截取字符串時,起始編號從1開始,這個要注意與${}相區分。
從左側截取Phone變量的前6個字符:
[root@svr5 ~]# expr substr "$Phone" 1 6
137887
從左側截取Phone變量的第9-11個字符:
[root@svr5 ~]# expr substr "$Phone" 9 3
897
3)方式三,使用cut分割工具
格式:echo $var | cut -b 起始位置-結束位置
選項 -b 表示按字節截取字符,其中起始位置、結束位置都可以省略。當省略起始位置時,視爲從第1個字符開始(編號也是從1開始,與expr類似),當省略結束位置時,視爲截取到最後。
還以前面的Phone變量爲例,確認原始值:
[root@svr5 ~]# echo $Phone
13788768897
[root@svr5 ~]# echo ${#Phone}
11
從左側截取前6個字符,可執行以下操作:
[root@svr5 ~]# echo $Phone | cut -b 1-6
137887
從第8個字符截取到末尾:
[root@svr5 ~]# echo $SCHOOL | cut -b 8-
8897
只截取單個字符,比如第9個字符:
[root@svr5 ~]# echo $SCHOOL | cut -b 9
8
步驟二:字符串的替換
1)只替換第1個子串
格式:${var/old/new}
以SCHOOL變量作爲測試,先確認變量值:
[root@svr5 ~]# SCHOOL="Tarena IT Group"
[root@svr5 ~]# echo $SCHOOL
Tarena IT Group.
將字符串中的第1個r替換爲RRRR:
[root@svr5 ~]# echo ${SCHOOL/r/RRRR}
TaRRRRena IT Group.
2)替換全部子串
格式:${var//old/new}
將SCHOOL字符串中的所有r都替換爲RRRR:
[root@svr5 ~]# echo ${SCHOOL//r/RRRR}
TaRRRRena IT GRRRRoup.
步驟三:字符串的匹配刪除
以處理系統默認的郵箱路徑爲例,可直接使用環境變量MAIL:
[root@svr5 ~]# echo $MAIL
/var/spool/mail/root
1)從左向右,最短匹配刪除
格式:${變量名#*關鍵詞}
刪除從左側第1個字符到最近的關鍵詞“oo”的部分,* 作通配符理解:
[root@svr5 ~]# echo ${MAIL#*oo}
l/mail/root
刪除從左側第1個字符到最近的關鍵詞“/”的部分:
[root@svr5 ~]# echo ${MAIL#*/}
var/spool/mail/root
[root@localhost test]# a=18518516128
[root@localhost test]# echo ${#a} //#號在最前面是統計總個數
11
2)從左向右,最長匹配刪除
格式:${變量名##*關鍵詞}
刪除從左側第1個字符到最遠的關鍵詞“oo”的部分:
[root@svr5 ~]# echo $MAIL //確認變量MAIL的值
/var/spool/mail/root
[root@svr5 ~]# echo ${MAIL##*oo}
t
刪除從左側第1個字符到最遠的關鍵詞“/”的部分:
[root@svr5 ~]# echo ${MAIL##*/}
root
操作 ${MAIL##*/} 的效果與使用basename命令提取基本名稱的效果相同:
[root@svr5 ~]# basename $MAIL
root
3)從右向左,最短匹配刪除
格式:${變量名%關鍵詞*}
刪除從右側最後1個字符到往左最近的關鍵詞“oo”的部分,* 做通配符理解:
[root@svr5 ~]# echo $MAIL //確認變量MAIL的值
[root@svr5 ~]# echo ${MAIL%oo*}
/var/spool/mail/r
刪除從右側最後1個字符到往左最近的關鍵詞“/”的部分:
[root@svr5 ~]# echo ${MAIL%/*}
/var/spool/mail
操作 ${MAIL%/*} 的效果與使用dirname命令提取目錄名稱的效果相同:
[root@svr5 ~]# dirname $MAIL
/var/spool/mail
4)從右向左,最長匹配刪除
格式:${變量名%%關鍵詞*}
刪除從右側最後1個字符到往左最遠的關鍵詞“oo”的部分:
[root@svr5 ~]# echo $MAIL //確認變量MAIL的值
/var/spool/mail/root
root@svr5 ~]# echo ${MAIL%%oo*}
/var/sp
刪除從右側最後1個字符到往左最遠的關鍵詞“/”的部分(刪沒了):
[root@svr5 ~]# echo ${MAIL%%/*}
[root@svr5 ~]#
步驟四:編寫renfilex.sh腳本
1)驗證原始改名腳本renfile.sh的效果
腳本用途爲:批量修改當前目錄下的文件擴展名,將.doc改爲.txt。
腳本內容參考如下:
[root@svr5 ~]# vim renfile.sh
#!/bin/bash
for FILE in *.doc
do
mv $FILE ${FILE%.doc}.txt
done
[root@svr5 ~]# chmod +x renfile.sh
創建一個測試用的文件夾rendir,並在其下建幾個測試文件
[root@svr5 ~]# mkdir rendir
[root@svr5 ~]# cd rendir
[root@svr5 rendir]# touch file1.doc abcde.doc xxyyzz.doc other1.xls killbill.mp4
[root@svr5 rendir]# ls
abcde.doc file1.doc killbill.mp4 other1.xls xxyyzz.doc
調用renfile.sh腳本,查看修改結果(原來擴展名爲.doc的文件,其擴展名都變成了.txt):
[root@svr5 rendir]# ../renfile.sh
[root@svr5 rendir]# ls
abcde.txt file1.txt killbill.mp4 other1.xls xxyyzz.txt
2)建立改進版腳本renfilex.sh
要適應不同擴展名文件的修改,並能夠反向還原。
修改前的擴展名、修改後的擴展名通過位置變量 $1、$2提供。
改進的腳本編寫參考如下:
[root@svr5 rendir]# cp ../renfile.sh ../renfilex.sh
[root@svr5 rendir]# vim ../renfilex.sh
#!/bin/bash
for FILE in "$1"
do
mv $FILE ${FILE%$1}"$2"
done
3)驗證、測試改進後的腳本
將 *.doc文件的擴展名改爲.txt:
[root@svr5 rendir]# ls //修改前
abcde.txt file1.txt killbill.mp4 other1.xls xxyyzz.txt
[root@svr5 rendir]# ../renfilex.sh .txt .doc
[root@svr5 rendir]# ls //修改後
abcde.doc file1.doc killbill.mp4 other1.xls xxyyzz.doc
將 *.mp4文件的擴展名改爲.mkv:
[root@svr5 rendir]# ls //修改前
abcde.doc file1.doc killbill.mp4 other1.xls xxyyzz.doc
[root@svr5 rendir]# ../renfilex.sh .mp4 .mkv
[root@svr5 rendir]# ls //修改後
abcde.doc file1.doc killbill.mkv other1.xls xxyyzz.doc
2 案例2:字符串初值的處理
2.1 問題
本案例要求編寫一個腳本sumx.sh,求從1-x的和,相關要求如下:
從鍵盤讀入x值
當用戶未輸入任何值時,默認按1計算
2.2 方案
2.3 步驟
實現此案例需要按照如下步驟進行。
步驟一:認識字符串初值的最常見處理方法
1)只取值,${var:-word}
若變量var已存在且非Null,則返回 $var 的值;否則返回字串“word”,原變量var的值不受影響。
變量值已存在的情況:
[root@svr5 ~]# echo $SCHOOL //查看原變量值
Tarena IT Group.
[root@svr5 ~]# echo ${SCHOOL:-Tarena} //因SCHOOL已存在,輸出變量SCHOOL的值
Tarena IT Group.
[root@svr5 ~]# echo $SCHOOL //原變量的值並不改變
Tarena IT Group.
變量值不存在的情況:
[root@svr5 ~]# unset SCHOOL //清除SCHOOL變量
[root@svr5 ~]# echo ${SCHOOL:-Tarena} //因SCHOOL已不存在,輸出“Tarena”
Tarena
[root@svr5 ~]# echo $SCHOOL //變量SCHOOL仍然不存在
[root@svr5 ~]#
2)取值+賦值,${var:=word}
若變量var已存在且非Null,則返回 $var 的值,原變量值不變;否則返回字串“word”,並將此字串賦值給變量 var。
變量值不存在的情況:
[root@svr5 ~]# echo $SCHOOL //前面已將此變量清除
[root@svr5 ~]# echo ${SCHOOL:=Tarena} //因SCHOOL不存在,輸出“Tarena”
Tarena
[root@svr5 ~]# echo $SCHOOL //且將“Tarena”賦值給變量SCHOOL
Tarena
變量值已存在的情況:
[root@svr5 ~]# echo $SCHOOL //確認當前的變量值
Tarena
[root@svr5 ~]# echo ${SCHOOL:=Tarena IT Group.} //變量已存在,輸出其值
Tarena
[root@svr5 ~]# echo $SCHOOL //原變量的值也不受影響
Tarena
步驟二:編寫sumx.sh腳本,處理read輸入的初值
用來從鍵盤讀入一個正整數x,求從1到x的和;當用戶未輸入值(直接回車)時,爲了避免執行出錯,應爲x賦初值1 。
1)腳本編寫參考如下
[root@svr5 ~]# vim sumx.sh
#!/bin/bash
read -p "請輸入一個正整數:" x
x=${x:-1}
i=1; SUM=0
while [ $i -le $x ]
do
let SUM+=i
let i++
done
echo "從1到$x的總和是:$SUM"
[root@svr5 ~]# chmod +x sumx.sh
2)驗證、測試腳本執行效果:
[root@svr5 ~]# ./sumx.sh
請輸入一個正整數:25 //輸入25,正常讀入並計算、輸出結果
從1到25的總和是:325
[root@svr5 ~]# ./sumx.sh
請輸入一個正整數:70 //輸入70,正常讀入並計算、輸出結果
從1到70的總和是:2485
[root@svr5 ~]# ./sumx.sh
請輸入一個正整數: //直接回車,設x=1後計算、輸出結果
從1到1的總和是:1
3 案例3:使用Shell數組
3.1 問題
本案例要求編寫一個Shell腳本getips.sh,相關要求如下:
能夠反覆從鍵盤輸入IP地址,保存到數組
當用戶輸入“EOF”後結束輸入,顯示數組IPADDS各元素的值
最後報告本次錄入的IP地址個數、其中第1個錄入的地址
3.2 方案
建立數組的方法:
格式1,整體賦值:數組名=(值1 值2 .. .. 值n)
格式2,單個元素賦值:數組名[下標]=值
查看數組元素的方法:
獲取單個數組元素:${數組名[下標]}
獲取所有數組元素:${數組名[@]}
獲取數組元素個數:${#數組名[@]}
獲取連續的多個數組元素:${數組名[@]:起始下標:元素個數}
獲取某個數組元素的長度:${#數組名[下標]}
截取數組元素值的一部分:${數組名[下標]:起始下標:字符數}
3.3 步驟
實現此案例需要按照如下步驟進行。
步驟一:認識數組的賦值/引用基本方法
1)定義/賦值數組
使用declare命令,結合-a選項可聲明一個數組(這個操作一般可不做),比如:
[root@svr5 ~]# declare -a SVRS
直接執行declare -a,即不指定數組名參數時,會列出當前Shell環境中已定義的所有數組設置:
[root@svr5 ~]# declare -a //查看已定義的數組
declare -a BASH_ARGC='()'
declare -a BASH_ARGV='()'
declare -a BASH_LINENO='()'
declare -a BASH_SOURCE='()'
… …
若要定義數組的成員,可以在declare聲明時定義,也可以直接整體定義。整體賦值的格式爲“數組名=(值1 值2 值3 .. ..)”,比如:
[root@svr5 ~]# MY_SVRS=(www ftp mail club)
[root@svr5 ~]# set | grep "MY_" //查看數組定義結果
MY_SVRS=([0]="www" [1]="ftp" [2]="mail" [3]="club")
Shell中的語法要求是比較鬆散的,所以我們也可以直接爲單個數組元素賦值,格式爲“數組名[下標]=值”,每個數組元素的編號(即下標)從0開始。比如,以下操作會產生一個包括3個元素的數組:
[root@svr5 ~]# WEB_SVRS[0]="www.tarena.com" //爲第1個元素賦值
[root@svr5 ~]# WEB_SVRS[1]="mail.tarena.com" //爲第2個元素賦值
[root@svr5 ~]# WEB_SVRS[2]="club.tarena.com" //爲第3個元素賦值
[root@svr5 ~]# set | grep "WEB_" //查看數組定義
WEB_SVRS=([0]="www.tarena.com" [1]="mail.tarena.com"
[2]="club.tarena.com")
爲數組元素賦值時,並不要求每個成員都需要指定,下標也可以不連續。比如,可跳過下標3,直接爲下標爲4的元素賦值:
[root@svr5 ~]# WEB_SVRS[4]="tts6.tarena.com"
[root@svr5 ~]# set | grep "WEB_" //確認設置結果
WEB_SVRS=([0]="www.tarena.com" [1]="mail.tarena.com" [2]="club.tarena.com" [4]="tts6.tarena.com")
2)查看數組、查看數組元素
輸出整個數組的內容:
[root@svr5 ~]# echo ${MY_SVRS[@]}
www ftp mail club
查看第1個(下標爲0的)數組元素:
[root@svr5 ~]# echo ${MY_SVRS[0]}
www
輸出下標爲2的數組元素:
[root@svr5 ~]# echo ${MY_SVRS[2]}
mail
輸出數組中下標從1開始的2個元素:
[root@svr5 ~]# echo ${MY_SVRS[@]:1:2}
ftp mail
查看數組的元素個數:
[root@svr5 ~]# echo ${#MY_SVRS[@]}
4
[root@svr5 ~]# echo ${#WEB_SVRS[@]}
4
步驟二:編寫getips.sh腳本
1)任務需求及思路分析
使用read命令從鍵盤讀入用戶指定的IP地址,每次讀入一個。
因爲需要讀多次,直到輸入“EOF”時結束,所以可採用while循環結構,循環條件爲輸入的字符串不爲“EOF”。
要求用數組保存每次輸入的IP地址,那肯定從下標爲0的元素開始存放,賦值操作放在循環體內,下標的遞增通過一個變量i控制。
遇“EOF”結束while循環後,輸出整個數組的內容,並顯示數組元素的個數、第1個錄入的IP地址。
2)根據實現思路編寫腳本文件
[root@svr5 ~]# vim getips.sh
#!/bin/bash
i=0 //控制下標增長的變量
while :
do
read -p "請添加IP地址(輸EOF結束):" IP
[ $IP == "EOF" ] &&break
IPADDS[$i]="$IP" //每次錄入賦值給不同的數組元素
let i++
done
echo "您已錄入的IP地址如下:"
echo ${IPADDS[@]} //輸出整個數組
echo "總共包括 ${#IPADDS[@]} 個地址," //報告數組元素的個數
echo "其中第1個IP地址是:${IPADDS[0]}" //輸出第1個元素
[root@svr5 ~]# chmod +x getips.sh
3)驗證、測試腳本
[root@svr5 ~]# ./getips.sh
請添加IP地址(輸EOF結束):192.168.4.77
請添加IP地址(輸EOF結束):172.16.16.220
請添加IP地址(輸EOF結束):218.56.57.58
請添加IP地址(輸EOF結束):192.168.1.5
請添加IP地址(輸EOF結束):192.168.1.202
請添加IP地址(輸EOF結束):220.106.0.20
請添加IP地址(輸EOF結束):EOF
您已錄入的IP地址如下:
192.168.4.77 172.16.16.220 218.56.57.58 192.168.1.5 192.168.1.202 220.106.0.20
總共包括 6 個地址,
其中第1個IP地址是:192.168.4.77
4 案例4:expect預期交互
4.1 問題
本案例要求編寫一個expect腳本,實現SSH登錄的自動交互:
提前準備好目標主機,IP地址爲192.168.4.5
用戶名爲mike、密碼爲1234567
執行腳本後自動登入,並且在目標主機建立測試文件 /tmp/mike.txt
4.2 方案
expect可以爲交互式過程(比如FTP、SSH等登錄過程)自動輸送預先準備的文本或指令,而無需人工干預。觸發的依據是預期會出現的特徵提示文本。
常見的expect指令:
定義環境變量:set 變量名 變量值
創建交互式進程:spawn 交互式命令行
觸發預期交互:expect "預期會出現的文本關鍵詞:" { send "發送的文本\r" }
在spawn建立的進程中允許交互指令:interact
4.3 步驟
實現此案例需要按照如下步驟進行。
步驟一:準備expect及SSH測試環境
1)安裝expect工具
[root@svr5 ~]# yum -y install expect //安裝expect
.. ..
Installed:
expect.x86_64 0:5.44.1.15-5.el6_4
Dependency Installed:
tcl.x86_64 1:8.5.7-6.el6
[root@svr5 ~]# which expect //確認expect路徑
/usr/bin/expect
步驟二:編寫expect_ssh腳本,實現免交互登錄
1)任務需求及思路分析
在SSH登錄過程中,如果是第一次連接到該目標主機,則首先會被要求接受密鑰,然後才提示輸入密碼:
[root@svr5 ~]# ssh [email protected] //連接目標主機
The authenticity of host '192.168.4.5 (192.168.4.5)' can't be established.
RSA key fingerprint is 58:a0:d6:00:c7:f1:34:5d:6c:6d:70:ce:e0:20:f8:f3.
Are you sure you want to continue connecting (yes/no)? yes //接受密鑰
Warning: Permanently added '192.168.4.5' (RSA) to the list of known hosts.
[email protected]'s password: //驗證密碼
Last login: Thu May 7 22:05:44 2015 from 192.168.4.5
[mike@svr5 ~]$ exit //返回客戶端
logout
Connection to 192.168.4.5 closed.
當然,如果SSH登錄並不是第一次,則接受密鑰的環節就沒有了,而是直接進入驗證密碼的過程:
[root@svr5 ~]# ssh [email protected] //連接目標主機
[email protected]'s password: //驗證密碼
Last login: Mon May 11 12:02:39 2015 from 192.168.4.5
[mike@svr5 ~]$ exit //返回客戶端
logout
Connection to 192.168.4.5 closed.
2)根據實現思路編寫腳本文件
腳本內容參考如下:
[root@svr5 ~]# vim expect_ssh.sh
#!/usr/bin/expect
set host 192.168.4.5 #//定義變量
set user mike
set password "1234567"
spawn ssh $user@$host #//創建交互式進程
expect "password:" { send "$password\r" } #//自動發送密碼
expect "\[$user\@" { send "pwd > /tmp/$user.txt ; exit\r" }
#//發送交互式命令
interact #//允許交互式環境
[root@svr5 ~]# chmod +x expect_ssh.sh
3)驗證、測試腳本
執行腳本前,目標主機上並沒有/tmp/mike.txt文件:
[root@svr5 ~]# ls /tmp/mike.txt
ls: 無法訪問/tmp/mike.txt: 沒有那個文件或目錄
執行expect_ssh.sh自動登錄腳本:
[root@svr5 ~]# ./expect_ssh.sh
spawn ssh [email protected]
[email protected]'s password:
Last login: Mon May 11 12:08:47 2015 from 192.168.4.5
pwd > /tmp/mike.txt ; exit
[mike@svr5 ~]$ pwd > /tmp/mike.txt ; exit
logout
Connection to 192.168.4.5 closed.
再次檢查目標主機,會看到已經建立了/tmp/mike.txt文件,說明expect自動登錄並遠程執行命令成功:
[root@svr5 ~]# ls -l /tmp/mike.txt
-rw-rw-r--. 1 mike mike 11 5月 11 12:17 /tmp/mike.txt
5 案例5:使用正則表達式
5.1 問題
本案例要求熟悉正則表達式的編寫,完成以下任務:
利用egrep工具練習正則表達式的基本用法
提取出httpd.conf文件的有效配置行
編寫正則表達式,分別匹配MAC地址、E-Mail郵箱地址、IP地址、主機名
5.2 方案
表-1 基本正則列表
表-1 擴展正則列表
5.3 步驟
實現此案例需要按照如下步驟進行。
步驟一:正則表達式匹配練習
1)典型的應用場合:grep、egrep檢索文本行
使用不帶-E選項的grep命令時,支持基本正則匹配模式。比如“word”關鍵詞檢索、“^word”匹配以word開頭的行、“word$”匹配以word結尾的行……等等。
輸出以“r”開頭的用戶記錄:
[root@svr5 ~]# grep '^r' /etc/passwd
root:x:0:0:root:/root:/bin/bash
rpc:x:32:32:Portmapper RPC user:/:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
輸出以“localhost”結尾的行:
[root@svr5 ~]# grep 'localhost$' /etc/hosts
127.0.0.1 localhost.localdomain localhost
若希望在grep檢索式同時組合多個條件,比如輸出以“root”或者以“daemon”開頭的行,這時候基本正則就不太方便了(“或者”必須轉義爲“\|”):
[root@svr5 ~]# grep '^root|^daemon' /etc/passwd //搜索無結果
[root@svr5 ~]#
[root@svr5 ~]# grep '^root\|^daemon' /etc/passwd //正確獲得結果
root:x:0:0:root:/root:/bin/bash
daemon:x:2:2:daemon:/sbin:/sbin/nologin
而若若使用grep -E或egrep命令,可支持擴展正則匹配模式,能夠自動識別 |、{ 等正則表達式中的特殊字符,用起來更加方便,比如:
[root@svr5 ~]# grep -E '^root|^daemon' /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:2:2:daemon:/sbin:/sbin/nologin
或者
[root@svr5 ~]# egrep '^root|^daemon' /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:2:2:daemon:/sbin:/sbin/nologin
使用grep -E 與 使用egrep命令完全等效,推薦使用後者,特別是涉及到複雜的正則表達式的時候。
2)grep、egrep命令的-q選項
選項 -q 表示 quiet(靜默)的意思,結合此選項可以只做檢索而並不輸出,通常在腳本內用來識別查找的目標是否存在,通過返回狀態 $? 來判斷,這樣可以忽略無關的文本信息,簡化腳本輸出。
比如,檢查/etc/hosts文件內是否存在192.168.4.4的映射記錄,如果存在則顯示“YES”,否則輸出“NO”,一般會執行:
[root@svr5 ~]# grep '^192.168.4.4' /etc/hosts && echo "YES" || echo "NO"
192.168.4.4 svr5.tarena.com svr5
YES
這樣grep的輸出信息和腳本判斷後的提示混雜在一起,用戶不易辨別,所以可以改成以下操作:
[root@svr5 ~]# grep -q '^192.168.4.4' /etc/hosts && echo "YES" || echo "NO"
YES
是不是清爽多了,從上述結果也可以看到,使用 -q 選項的效果與使用 &> /dev/null的效果類似。
3)基本元字符 ^、$ —— 匹配行首、行尾
輸出默認運行級別的配置記錄(以id開頭的行):
[root@svr5 ~]# egrep '^id' /etc/inittab
id:3:initdefault:
輸出主機名配置記錄(以HOSTNAME開頭的行):
[root@svr5 ~]# egrep '^HOSTNAME' /etc/sysconfig/network
HOSTNAME=svr5.tarena.com
統計本地用戶中登錄Shell爲“/sbin/nologin”的用戶個數:
[root@svr5 ~]# egrep -m10 '/sbin/nologin$' /etc/passwd //先確認匹配正確
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
[root@svr5 ~]# egrep -c '/sbin/nologin$' /etc/passwd
32 //結合 -c 選項輸出匹配的行數
使用 -c 選項可輸出匹配行數,這與通過管道再 wc -l的效果是相同的,但是寫法更簡便。比如,統計使用“/bin/bash”作爲登錄Shell的正常用戶個數,可執行:
[root@svr5 ~]# egrep -c '/bin/bash$' /etc/passwd
26
或者
[root@svr5 ~]# egrep '/bin/bash$' /etc/passwd | wc -l
26
4)基本元字符 . —— 匹配任意單個字符
以/etc/rc.local文件爲例,確認文本內容:
[root@svr5 ~]# cat /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
輸出/etc/rc.local文件內至少包括一個字符(\n換行符除外)的行,即非空行:
[root@svr5 ~]# egrep '.' /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
輸出/etc/rc.local文件內的空行(用 –v 選項將條件取反):
[root@svr5 ~]# egrep -v '.' /etc/rc.local
[root@svr5 ~]#
上述取空行的操作與下列操作效果相同:
[root@svr5 ~]# egrep '^$' /etc/rc.local
[root@svr5 ~]#
5)基本元字符 +、?、* —— 目標出現的次數
還以/etc/rc.local文件爲例:
[root@svr5 ~]# cat /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
輸出包括 f、ff、ff、……的行,即“f”至少出現一次:
[root@svr5 ~]# egrep 'f+' /etc/rc.local
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
輸出包括init、initial的行,即末尾的“ial”最多出現一次(可能沒有):
[root@svr5 ~]# egrep 'init(ial)?' /etc/rc.local
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
輸出包括stu、stuf、stuff、stufff、……的行,即末尾的“f”可出現任意多次,也可以沒有。重複目標只有一個字符時,可以不使用括號:
[root@svr5 ~]# egrep 'stuf*' /etc/rc.local
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
輸出所有行,單獨的“.*”可匹配任意行(包括空行):
[root@svr5 ~]# egrep '.*' /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
輸出/etc/passwd文件內“r”開頭且以“nologin”結尾的用戶記錄,即中間可以是任意字符:
[root@svr5 ~]# egrep '^r.*nologin$' /etc/passwd
rpc:x:32:32:Portmapper RPC user:/:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
6)元字符 {} —— 限定出現的次數範圍
創建一個練習用的測試文件:
[root@svr5 ~]# vim brace.txt
ab def ghi abdr
dedef abab ghighi
abcab CD-ROM
TARENA IT GROUP
cdcd ababab
Hello abababab World
輸出包括ababab的行,即“ab”連續出現3次:
[root@svr5 ~]# egrep '(ab){3}' brace.txt
cdcd ababab
Hello abababab World
輸出包括abab、ababab、abababab的行,即“ab”連續出現2~4次:
[root@svr5 ~]# egrep '(ab){2,4}' brace.txt
dedef abab ghighi
cdcd ababab
Hello abababab World
輸出包括ababab、abababab、……的行,即“ab”最少連續出現3次:
[root@svr5 ~]# egrep '(ab){3,}' brace.txt
cdcd ababab
Hello abababab World
7)元字符 [] —— 匹配範圍內的單個字符
還以前面的測試文件bracet.txt爲例:
[root@svr5 ~]# cat brace.txt
ab def ghi abdr
dedef abab ghighi
abcab CD-ROM
TARENA IT GROUP
cdcd ababab
Hello abababab World
輸出包括abc、abd的行,即前兩個字符爲“ab”,第三個字符只要是c、d中的一個就符合條件:
[root@svr5 ~]# egrep 'ab[cd]' brace.txt
ab def ghi abdr
abcab CD-ROM
輸出包括大寫字母的行,使用[A-Z]匹配連續範圍:
[root@svr5 ~]# egrep '[A-Z]' brace.txt
abcab CD-ROM
TARENA IT GROUP
Hello abababab World
輸出包括“非空格也非小寫字母”的其他字符的行,本例中大寫字母和 – 符合要求:
[root@svr5 ~]# egrep '[^ a-zA-Z]' brace.txt
abcab CD-ROM
8)單詞邊界匹配
以文件/etc/rc.local爲例:
[root@svr5 ~]# cat /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
輸出包括單詞“init”的行,文件中“initialization”不合要求:
[root@svr5 ~]# egrep '\binit\b' /etc/rc.local
# This script will be executed *after* all the other init scripts.
# want to do the full Sys V style init stuff.
或者:
[root@svr5 ~]# egrep '\<init\>' /etc/rc.local
# This script will be executed *after* all the other init scripts.
# want to do the full Sys V style init stuff.
輸出包括以“ll”結尾的單詞的行,使用 \> 匹配單詞右邊界:
[root@svr5 ~]# egrep 'll\>' /etc/rc.local
# This script will be executed *after* all the other init scripts.
# want to do the full Sys V style init stuff.
或者:
[root@svr5 ~]# egrep 'll\b' /etc/rc.local
# This script will be executed *after* all the other init scripts.
# want to do the full Sys V style init stuff.
9)多個條件的組合
通過dmesg啓動日誌查看與IDE接口、CDROM光盤相關的設備信息:
[root@svr5 ~]# egrep '\<IDE\>|\<CDROM\>' /var/log/dmesg
Uniform Multi-Platform E-IDE driver Revision: 7.00alpha2
PIIX4: IDE controller at PCI slot 0000:00:07.1
Probing IDE interface ide0...
Probing IDE interface ide1...
hdc: VMware Virtual IDE CDROM Drive, ATAPI CD/DVD-ROM drive
Probing IDE interface ide0...
通過dmesg啓動日誌查看藍牙設備、網卡設備相關的信息:
[root@svr5 ~]# egrep -i 'eth|network|bluetooth' /var/log/dmesg
Initalizing network drop monitor service
Bluetooth: Core ver 2.10
Bluetooth: HCI device and connection manager initialized
Bluetooth: HCI socket layer initialized
Bluetooth: HCI USB driver ver 2.9
Intel(R) PRO/1000 Network Driver - version 7.3.21-k4-3-NAPI
e1000: eth0: e1000_probe: Intel(R) PRO/1000 Network Connection
步驟二:利用正則表達式完成檢索任務
1)提取出httpd.conf文件的有效配置行
以RHEL6自帶的httpd軟件包爲例,默認的httpd.conf配置文件內提供了大量的註釋信息(# 開頭或空幾個格再 #),以及一些分隔的空行:
[root@svr5 ~]# head /etc/httpd/conf/httpd.conf //確認文件內容
#
# This is the main Apache server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
#
# Do NOT simply read the instructions in here without understanding
[root@svr5 ~]# egrep -c ".*" /etc/httpd/conf/httpd.conf
991 //總行數
[root@svr5 ~]# egrep -c "#" /etc/httpd/conf/httpd.conf
674 //含註釋的行數
[root@svr5 ~]# egrep -c "^$" /etc/httpd/conf/httpd.conf
95 //空行的數量
提取有效配置行,也就是說應排除掉註釋行、空行,根據上面的結果可得知有效配置行的數量應該是“991-674-95=222”,確認一下:
[root@svr5 ~]# egrep -c -v '#|^$' /etc/httpd/conf/httpd.conf
222
結合 > 重定向操作,提取httpd.conf的有效配置,將其保存到文件 httpd.conf.min,相關操作如下:
[root@svr5 ~]# egrep -v '#|^$' /etc/httpd/conf/httpd.conf > httpd.conf.min
[root@svr5 ~]# head httpd.conf.min //確認有效配置的前10行
ServerTokens OS
ServerRoot "/etc/httpd"
PidFile run/httpd.pid
Timeout 120
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 8
MinSpareServers 5
2)匹配MAC地址、郵箱地址、IP地址
以使用ifconfig查看的結果爲例,MAC地址的特徵是以“:”分隔的6組十六進制數,每組由2個字符組成,比如:
[root@svr5 ~]# ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:0C:29:82:09:E9
inet addr:192.168.4.4 Bcast:192.168.4.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe82:9e9/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:177666 errors:0 dropped:0 overruns:0 frame:0
TX packets:101720 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:18454015 (17.5 MiB) TX bytes:13467792 (12.8 MiB)
採用正則表達式匹配“00:0C:29:82:09:E9”形式的MAC地址,可以寫成:
[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}
或者:
[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}
其中,[0-9a-fA-F]{2} 表示一段十六進制數值,第二種方式的{5}表示連續出現5組前置 : 的十六進制。
因此,若要從ifconfig eth0的輸出結果中過濾出包含MAC地址值的行,可以執行以下操作:
[root@svr5 ~]# ifconfig eth0 | egrep '[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}'
eth0 Link encap:Ethernet HWaddr 00:0C:29:82:09:E9
或者:
[root@svr5 ~]# ifconfig eth0 | egrep \
'[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}'
eth0 Link encap:Ethernet HWaddr 00:0C:29:82:09:E9
根據上述操作結果,稍微擴展一下。利用MAC匹配條件,可以檢查一個變量的值是否是合法的MAC地址。參考下列操作:
先定義三個變量:
[root@svr5 ~]# MAC01="00:50:56:C0:00:08"
[root@svr5 ~]# MAC02="20:68:9D:48:C4:98"
[root@svr5 ~]# MAC03="20:69:74:R2:C5:27" //設一個無效地址
利用正則表達式判斷出其中哪個MAC地址是無效的:
[root@svr5 ~]# echo $MAC01 | egrep -q \
'[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}' && echo "有效" || echo "無效"
有效
[root@svr5 ~]# echo $MAC02 | egrep -q \
'[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}' && echo "有效" || echo "無效"
有效
[root@svr5 ~]# echo $MAC03 | egrep -q \
'[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}' && echo "有效" || echo "無效"
無效
3)匹配郵箱地址
電子郵箱地址的特徵是“用戶名@域名”,主要包括:
用戶名與域名之間以 @ 分隔
用戶名不少於3個字符,可能由字母、下劃線、句點 . 、數字組成
域名應至少有一個 . 分隔,分隔的各部分至少2個字符,可能由字母、減號、數字組成
根據上述特點,編寫的正則表達式參考如下:其中域名分隔以“\.”表示,不能表示爲 . ,否則會匹配任意單個字符。
[0-9a-zA-Z_.]{3,}@[0-9a-zA-Z.-]{2,}(\.[0-9a-zA-Z-]{2,})+
創建一個測試文件,添加若干行主機名、Email、域名地址:
[root@svr5 ~]# vim mailadd.txt
www.tarena.com.cn
mail.163.com
[email protected]
qq.com
www.sina.com.cn
baidu.com
[email protected]
bill@microsoft //無效的郵箱地址,用作測試
[email protected]
過濾出上述文件中包含有效Email地址的行:
[root@svr5 ~]# egrep '[0-9a-zA-Z_.]{3,}@\
[0-9a-zA-Z.-]{2,}(\.[0-9a-zA-Z-]{2,})+' mailadd.txt
[email protected]
[email protected]
[email protected]
4)匹配主機名
以FQDN(完整主機名)爲例,描述其特點:
由 . 分隔,至少包括3組字符串
每組字符串不少於2個字符,可能由字母、減號、數字、下劃線組成
主機名後必須是單詞邊界,主機名前不能有@符號
編寫正則表達式參考如下:
^[^@][0-9a-zA-Z_-]{2,}(\.[0-9a-zA-Z_-]{2,}){2,}\>
以前面的mailadd.txt文件爲例,過濾測試如下所示:
[root@svr5 ~]# egrep '^[^@][0-9a-zA-Z_-]{2,}(\.[0-9a-zA-Z_-]{2,}){2,}\>' \
mailadd.txt
www.tarena.com.cn
mail.163.com
www.sina.com.cn
5)匹配IP地址
歸納合法IP地址的特點:
以 . 分隔,一共由四組十進制數構成
每組數值的範圍爲0-255,字符寬度爲1-3位
前後必須是單詞邊界
編寫正則表達式參考如下:
\<[0-9]{1,3}(\.[0-9]{1,3}){3}\>
以過濾出ifconfig命令輸出結果中包含IP地址的行爲例,過濾測試如下所示:
[root@svr5 ~]# ifconfig //確認原始信息
eth0 Link encap:Ethernet HWaddr 00:0C:29:82:09:E9
inet addr:192.168.4.5 Bcast:192.168.4.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe82:9e9/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:182773 errors:0 dropped:0 overruns:0 frame:0
TX packets:104834 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:18913180 (18.0 MiB) TX bytes:13855676 (13.2 MiB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:838 errors:0 dropped:0 overruns:0 frame:0
TX packets:838 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:93855 (91.6 KiB) TX bytes:93855 (91.6 KiB)
[root@svr5 ~]# ifconfig | egrep '\<[0-9]{1,3}(\.[0-9]{1,3}){3}\>'
inet addr:192.168.4.4 Bcast:192.168.4.255 Mask:255.255.255.0
inet addr:127.0.0.1 Mask:255.0.0.0