If示例
? 根據命令的退出狀態來執行命令
if ping -c1 -W2 station1 &> /dev/null; then ? ? ?ping一次等待2秒
echo ‘Station1 is UP’
elif grep “station1” ~/maintenance.txt &> /dev/null ? ?主機是否維護
then
echo ‘Station1 is undergoing maintenance‘ ? ? ? ? ? ? ?機器down機
else echo ‘Station1 is unexpectedly DOWN!’ exit 1
fi
循環
? 循環執行
將某代碼段重復運行多次
重復運行多少次
循環次數事先已知
循環次數事先未知
有進入條件和退出條件
? for, while, until
for循環
? ?for 變量名 in 列表;do ? ? 列如:for name in wang mage li lele ;do
循環體
done
? ?執行機制:
依次將列表中的元素賦值給“變量名”; 每次賦值后即執行一次循環體; 直
到列表中的元素耗盡,循環結束
for循環
? 列表生成方式:
(1) 直接給出列表
(2) 整數列表:
(a) {start..end}
(b) $(seq [start [step]] end)
(3) 返回列表的命令
$(COMMAND)
(4) 使用glob,如:*.sh
(5) 變量引用;
$@, $* ? ? ? ?$@ 獨立的字符串,$*整體的字符串
[root@CENTOS7 ~]#for num in 1 2 3 4 5 6 ; do echo num=$num ;done ? ?for循環基本用法 ? ?手動輸入列表
num=1
num=2
num=3
num=4
num=5
num=6
[root@CENTOS7 ~]#echo {10..2..3}
10 7 4
[root@CENTOS7 ~]#for num in {1..10..2} ;do echo num=$num ;done ? 大括號形成列表
num=1
num=3
num=5
num=7
num=9
[root@CENTOS7 ~]#seq 1 3 10
1
4
7
10
[root@CENTOS7 ~]#for num in `seq 1 3 10` ;do echo sum=$num ;done 命令形成列表
sum=1
sum=4
sum=7
sum=10
[root@CENTOS7 ~]#for file in `ls /boot`;do echo filename=$file;done
filename=config-3.10.0-693.el7.x86_64
filename=efi
filename=grub
filename=grub2
filename=initramfs-0-rescue-d9b2c489cdf948f8b487e98005c15e1c.img
filename=initramfs-3.10.0-693.el7.x86_64.img
filename=initrd-plymouth.img
filename=symvers-3.10.0-693.el7.x86_64.gz
filename=System.map-3.10.0-693.el7.x86_64
filename=vmlinuz-0-rescue-d9b2c489cdf948f8b487e98005c15e1c
filename=vmlinuz-3.10.0-693.el7.x86_64
[root@CENTOS7 ~]#for num in /data/*.sh ;do echo $num ; done ? ?通配符生成列表
/data/arg.sh
/data/f1.sh
/data/f2.sh
/data/f3.sh
/data/install.sh
/data/link.sh
/data/sumuid.sh
/data/username.sh
[root@CENTOS7 ~]#for num in “/data/*.sh” ;do echo $num ; done ? ?加上”” 當成一個字符串來顯示
/data/arg.sh /data/f1.sh /data/f2.sh /data/f3.sh /data/install.sh /data/link.sh /data/sumuid.sh /data/username.sh
1一直加到100
[root@CENTOS7 ~]#vim sum.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-07
#FileName: ? ? ? ? ? ? sum.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
for i in {1..100} ; do
? ? ? ? let sum=sum+i
done
echo $sum
[root@CENTOS7 ~]#./sum.sh
5050
1遞進3加到100
[root@CENTOS7 ~]#vim sum147.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-07
#FileName: ? ? ? ? ? ? sum147.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
declare -i sum=0
for i in `seq 1 3 100` ; do
? ? ? ? let sum=sum+i
done
echo $sum
unset sum ? ? ? ? ? ? ? ? ?清除sum的賦值
“sum147.sh” [New] 16L, 420C written
[root@CENTOS7 ~]#chmod +x ?sum147.sh
[root@CENTOS7 ~]#./sum147.sh
1717
在for循環中使用多行從定向時,需要在結束符處加-
[root@CENTOS7 ~]#vim f11.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-07
#FileName: ? ? ? ? ? ? f11.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
for i in {1..10} ;do
? ? ? ? cat >> f1 <<-123
? ? ? ? aaa
? ? ? ? bbb
? ? ? ? 123
done
root@CENTOS7 ~]#cat f1
aaa
bbb
aaa
bbb
aaa
bbb
aaa
bbb
aaa
bbb
aaa
bbb
aaa
bbb
aaa
bbb
aaa
bbb
aaa
bbb
創建10個用戶是user{1..10} 判斷用戶是否存在,不存在創建,存在就提示用戶已經存在,并設置口令是magedu。
[root@CENTOS7 ~]#cat createuser.sh
#!/bin/bash
#
#********************************************************************
#Author: wangxiaochun
#QQ: 29308620
#Date: 2018-05-07
#FileName: createuser.sh
#URL: http://www.magedu.com
#Description: The test script
#Copyright (C): 2018 All rights reserved
#********************************************************************
for user in `echo user{1..10}`; do
id $user &> /dev/null
if [ $? -eq 0 ] ; then
echo the user is exist
else useradd $user
echo magedu | passwd –stdin $user
echo user creat succeed
fi
done
掃描地址段
[root@CENTOS7 ~]#vim scanaddress.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-07
#FileName: ? ? ? ? ? ? scanaddress.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
addr=172.20.0.
for i in {1..255} ;do
? ? ? ? if ping -c1 -w1 $addr$i &>/dev/null ; then
? ? ? ? ? ? ? ? echo $addr$i is up
? ? ? ? else
? ? ? ? ? ? ? ? echo $addr$i is down
? ? ? ? fi
done
運行太慢,加速運行。后臺并行運行
[root@CENTOS7 ~]#vim scanaddress.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-07
#FileName: ? ? ? ? ? ? scanaddress.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
addr=172.20.0.
for i in {1..255} ;do
? ? ? ? { if ping -c1 -w1 $addr$i &>/dev/null ; then
? ? ? ? ? ? ? ? echo $addr$i is up
? ? ? ? else
? ? ? ? ? ? ? ? echo $addr$i is down
? ? ? ? fi ; } &
done
wait ? ? ?后臺運行完畢后自動退出 ? ? ? ?當執行下面計數的命令使不能再后臺并行運行
[root@CENTOS7 ~]#vim scanaddress.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-07
#FileName: ? ? ? ? ? ? scanaddress.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
addr=172.20.0.
up=0
down=0
for i in {1..255} ;do
? ? ? ? if ping -c1 -w1 $addr$i &>/dev/null ; then
? ? ? ? ? ? ? ? echo $addr$i is up &>/dev/null
? ? ? ? ? ? ? ? let up=$up+1
? ? ? ? else
? ? ? ? ? ? ? ? echo $addr$i is down &>/dev/null
? ? ? ? ? ? ? ? let down=$down+1
? ? ? ? fi
done
echo up=$up
echo down=$down
“scanaddress.sh” 29L, 597C written
[root@CENTOS7 ~]#./scanaddress.sh
up=2
down=253
addr=172.20.0.
up=0
down=0
for i in {1..255} ;do
? ? ? ? ?ping -c1 -w1 $addr$i &>/dev/null && { echo $addr$i is up; let up++; } || { echo $addr$i is down; let down++; }
done
[root@CENTOS7 ~]#vim addr.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-07
#FileName: ? ? ? ? ? ? addr.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
addr=172.20.0.
up=0
down=0
for i in {1..10} ;do
? ? ? ? ?ping -c1 -w1 $addr$i &>/dev/null && { echo $addr$i is up; let up++; } || { echo $addr$i is down; let down++; }
?done
?echo $up
?echo $down
~
~
~
“addr.sh” 20L, 540C written
[root@CENTOS7 ~]#./addr.sh
172.20.0.1 is up
172.20.0.1 is down
172.20.0.2 is down
172.20.0.3 is down
172.20.0.4 is down
172.20.0.5 is down
172.20.0.6 is down
172.20.0.7 is down
172.20.0.8 is down
172.20.0.9 is down
172.20.0.10 is down
1
10
發現up的機器出現問題,因為up++,當up=0時,執行up++,$?=1
[root@CENTOS7 ~]#up=0
[root@CENTOS7 ~]#let up++
[root@CENTOS7 ~]#echo $?
1
[root@CENTOS7 ~]#n=10;echo {1..$n} ? ? ?{}不支持變量寫法
{1..10}
[root@CENTOS7 ~]#n=10;seq 1 $n
1
2
3
4
5
6
7
8
9
10
[root@CENTOS7 ~]#n=10;eval echo {1..$n} eval掃描替換變量,然后在執行命令
1 2 3 4 5 6 7 8 9 10
循環嵌套:
for i in {1..10};do ? ? ? ? ?執行100次
for j in {1..10};do
cmd
done
done
打印一個矩形:
[root@CENTOS7 ~]#vim rectangle.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-08
#FileName: ? ? ? ? ? ? rectangle.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
high=$1
wide=$2
for i in `seq $high` ; do
? ? ? ? for j in `seq $wide` ; do
? ? ? ? ? ? ? ? echo -e “\033[1;32m*\033[0m\c”
? ? ? ? done
? ? ? ? echo
done
[root@CENTOS7 ~]#./rectangle.sh 5 10
**********
**********
**********
**********
**********
隨機顏色的矩形
[root@CENTOS7 ~]#vim rectangle.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-08
#FileName: ? ? ? ? ? ? rectangle.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
high=$1
wide=$2
for i in `seq $high` ; do
? ? ? ? for j in `seq $wide` ; do
? ? ? ? ? ? ? ? k=$[$RANDOM%7+31]
? ? ? ? ? ? ? ? echo -e “\033[1;${k}m*\033[0m\c”
? ? ? ? done
? ? ? ? echo
done
[root@CENTOS7 ~]#./rectangle.sh 5 10
**********
**********
**********
**********
**********
99乘法表
[root@CENTOS7 ~]#vim 9*9.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-08
#FileName: ? ? ? ? ? ? 9*9.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
for i in {1..9} ; do
? ? ? ? for j in `seq 1 $i` ; do
? ? ? ? ? ? ? ? result=$[$i*$j]
? ? ? ? ? ? ? ? echo -e “${j}x${i}=$result\t\c”
? ? ? ? done
? ? ? ? echo
done
~
~
~
~
~
~
~
~
~
~
~
“9*9.sh” 18L, 457C written
[root@CENTOS7 ~]#./9\*9.sh
1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
1×4=4 2×4=8 3×4=12 4×4=16
1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
取8個隨機字母
[root@CENTOS7 ~]#openssl rand -base64 20 | tr -dc “[:alpha:]” | head -c8
cxHNcKmG[root@CENTOS7 ~]#
國際象棋棋盤
high=$1
wide=$2
? r i in `seq $high` ; do
? ? ? ? a=$[$i%2]
? ? ? ? for j in `seq $wide` ; do
? ? ? ? if [ $a -eq 1 ] ; then
? ? ? ? ? ? ? ? echo -e “\033[1;42m ? ? \033[0m\033[1;41m ? ? \033[0m\c”
? ? ? ? else
? ? ? ? ? ? ? ? ?echo -e “\033[1;41m ? ? \033[0m\033[1;42m ? ? \033[0m\c”
? ? ? ? fi
? ? ? ? done
? ? ? ? echo
大的國際象棋盤
for i in {1..16};do
? ? ? ? for j in {1..4};do
? ? ? ? ? ? ? ? case $[i%4] in
? ? ? ? ? ? ? ? 1|2)
? ? ? ? ? ? ? ? ? ? ? ? echo -e “\033[1;41m ? ?\033[0m\033[1;43m ? ?\033[0m\c”
? ? ? ? ? ? ? ? ? ? ? ? ;;
? ? ? ? ? ? ? ? *)
? ? ? ? ? ? ? ? ? ? ? ? echo -e “\033[1;43m ? ?\033[0m\033[1;41m ? ?\033[0m\c”
? ? ? ? ? ? ? ? ? ? ? ? ;;
? ? ? ? ? ? ? ? esac
? ? ? ? done
? ? ? ? echo
done
while循環
? while CONDITION; do
循環體
done
? CONDITION:循環控制條件;進入循環之前,先做一次判斷;每一次循環之后
會再次做判斷;條件為“true”,則執行一次循環;直到條件測試狀態為
“false”終止循環
? 因此:CONDTION一般應該有循環控制變量;而此變量的值會在循環體不斷地
被修正
? 進入條件:CONDITION為true
? 退出條件:CONDITION為false
[root@CENTOS7 ~]#vim sum100.sh
#!/bin/bash
declare -i sum=0
i=1
while [ $i -le 100 ]; do
? ? ? ? let sum=sum+i
? ? ? ? let i=i+1
done
echo $sum
[root@CENTOS7 ~]#./sum100.sh
5050
用while實現9*9法則
[root@CENTOS7 ~]#vim while9*9.sh
#!/bin/bash
declare -i i=1
while [ $i -le 9 ]; do
? ? ? ? declare -i j=1
? ? ? ? while [ $j -le $i ]; do
? ? ? ? sum=$[${j}*${i}]
? ? ? ? echo -e “${j}x${i}=$sum\t\c”
? ? ? ? let j++
? ? ? ? done
? ? ? ? echo
? ? ? ? let i++
done
~
“while9*9.sh” 22L, 509C written
[root@CENTOS7 ~]#./while9*9.sh
1×1=1
1×2=22×2=4
1×3=32×3=63×3=9
1×4=42×4=83×4=124×4=16
1×5=52×5=103×5=154×5=205×5=25
1×6=62×6=123×6=184×6=245×6=306×6=36
1×7=72×7=143×7=214×7=285×7=356×7=427×7=49
1×8=82×8=163×8=244×8=325×8=406×8=487×8=568×8=64
1×9=92×9=183×9=274×9=365×9=456×9=547×9=638×9=729×9=81
每10秒監控一次httpd服務,如果服務停止則啟動。
[root@CENTOS7 ~]#systemctl start httpd
[root@CENTOS7 ~]#ss -ntl
LISTEN ? ? ?0 ? ? ?128 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? :::80 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?:::*
[root@CENTOS7 ~]#ps -aux | grep httpd
root ? ? ? 6196 ?0.5 ?0.4 226240 ?5132 ? ? ? ? ?Ss ? 13:44 ? 0:00 /usr/sbin/httpd -DFOREGROUND
apache ? ? 6207 ?0.0 ?0.2 228324 ?3152 ? ? ? ? ?S ? ?13:45 ? 0:00 /usr/sbin/httpd -DFOREGROUND
apache ? ? 6208 ?0.0 ?0.2 228324 ?3152 ? ? ? ? ?S ? ?13:45 ? 0:00 /usr/sbin/httpd -DFOREGROUND
apache ? ? 6209 ?0.0 ?0.2 228324 ?3152 ? ? ? ? ?S ? ?13:45 ? 0:00 /usr/sbin/httpd -DFOREGROUND
apache ? ? 6210 ?0.0 ?0.2 228324 ?3152 ? ? ? ? ?S ? ?13:45 ? 0:00 /usr/sbin/httpd -DFOREGROUND
apache ? ? 6211 ?0.0 ?0.2 228324 ?3152 ? ? ? ? ?S ? ?13:45 ? 0:00 /usr/sbin/httpd -DFOREGROUND
root ? ? ? 6244 ?0.0 ?0.0 112660 ? 972 pts/0 ? ?R+ ? 13:45 ? 0:00 grep –color=auto httpd
[root@CENTOS7 ~]#vim start.sh
while true ; do
? ? ? ? if ?pgrep httpd &> /dev/null ;then ? ?這里也可以寫成 if killall -0 httpd &> /dev/null ;then
? ? ? ? ? ? ? ? ? ? ? ? :
? ? ? ? else
? ? ? ? systemctl start httpd
echo at `date +”%F %T”` restart httpd >> /data/httpd.log
? ? ? ? fi
? ? ? ? sleep 10
done
until循環
? until CONDITION; do
循環體
? done
? 進入條件: CONDITION 為false
? 退出條件: CONDITION 為true
判斷用戶wang是否登錄
[root@CENTOS7 ~]#vim wang.sh
until who | grep wang &> /dev/null ; do
? ? ? ? sleep 1
done
? ? ? ? echo userwang is login
循環控制語句continue
? 用于循環體中
? continue [N]:提前結束第N層的本輪循環,而直接進入下一輪判斷;最內層為
第1層
while CONDTIITON1; do
CMD1
…
if CONDITION2; then
continue
fi
CMDn
…
done
循環控制語句break
? 用于循環體中
? break [N]:提前結束第N層循環,最內層為第1層
while CONDTIITON1; do
CMD1
…
if CONDITION2; then
break
fi
CMDn
…
done
[root@CENTOS7 ~]#vim continue.sh
#!/bin/bash
for i in {1..10}; do
? ? ? ? if [ $i -eq 5 ]; then
? ? ? ? ? ? ? ? continue
? ? ? ? fi
? ? ? ? echo i=$i
done
[root@CENTOS7 ~]#./continue.sh
i=1
i=2
i=3
i=4
i=6
i=7
i=8
i=9
i=10
[root@CENTOS7 ~]#vim continue.sh
#!/bin/bash
for i in {1..10}; do
? ? ? ? if [ $i -eq 5 ]; then
? ? ? ? ? ? ? ? break
? ? ? ? fi
? ? ? ? echo i=$i
done
[root@CENTOS7 ~]#./continue.sh
i=1
i=2
i=3
i=4
[root@CENTOS7 ~]#vim continue.sh
#!/bin/bash
for i in {1..10}; do
? ? ? ? for j in {1..10}; do
? ? ? ? if [ $j -eq 5 ]; then
? ? ? ? ? ? ? ? continue
? ? ? ? fi
? ? ? ? echo j=$j
? ? ? ? done
done
~
除了j=5剩下的現實10次
[root@CENTOS7 ~]#vim continue.sh
#!/bin/bash
for i in {1..10}; do
? ? ? ? for j in {1..10}; do
? ? ? ? if [ $j -eq 5 ]; then
? ? ? ? ? ? ? ? continue 2
? ? ? ? fi
? ? ? ? echo j=$j
? ? ? ? done
done
執行結果是j=1-4,現實10次
[root@CENTOS7 ~]#vim continue.sh
#!/bin/bash
for i in {1..10}; do
? ? ? ? for j in {1..10}; do
? ? ? ? if [ $j -eq 5 ]; then
? ? ? ? ? ? ? ? break
? ? ? ? fi
? ? ? ? echo j=$j
? ? ? ? done
done
執行結果是j=1-4,現實10次
[root@CENTOS7 ~]#vim continue.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-08
#FileName: ? ? ? ? ? ? continue.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
for i in {1..10}; do
? ? ? ? for j in {1..10}; do
? ? ? ? if [ $j -eq 5 ]; then
? ? ? ? ? ? ? ? break 2
? ? ? ? fi
? ? ? ? echo j=$j
? ? ? ? done
done
~
~
~
“continue.sh” 20L, 451C written
[root@CENTOS7 ~]#./continue.sh
j=1
j=2
j=3
j=4
循環控制shift命令
? shift [n]
? 用于將參量列表 list 左移指定次數,缺省為左移一次。
? 參量列表 list 一旦被移動,最左端的那個參數就從列表中刪除。while 循環遍
歷位置參量列表時,常用到 shift
? ./doit.sh a b c d e f g h
? ./shfit.sh a b c d e f g h
批量處理賬號
[root@CENTOS7 ~]#vim userad.sh
#!/bin/bash
until [ -z $1 ]; do
? ? ? ? useradd $1
? ? ? ? echo $1 is cteatd
? ? ? ? shift
done
echo done
[root@CENTOS7 ~]#chmod +x userad.sh
[root@CENTOS7 ~]#./userad.sh
done
[root@CENTOS7 ~]#./userad.sh a
a is cteatd
done
示例:doit.sh ? ? ?1 2 3 4 5
#!/bin/bash
# Name: doit.sh
# Purpose: shift through command line arguments
# Usage: doit.sh [args]
while [ $# -gt 0 ] # or (( $# > 0 ))
do
echo $*
shift
done
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
示例:shift.sh
#!/bin/bash
#step through all the positional parameters
until [ -z “$1” ]
do
echo “$1”
shift
done
echo
創建無限循環
? while true; do
循環體
? done
? until false; do
循環體
2、隨機生成10以內的數字,實現猜字游戲,提示比較大或小,相等則退出
[root@CENTOS7 ~]#vim guess.sh
#!/bin/bash
a=`echo $[RANDOM%11]`
while read -p “please input a nummber:” n ; do
? ? ? ? [[ $n =~ ^[0-9]+$ ]] || { echo please input a 0-10 number ; continue ; }
? ? ? ? if [ $n -lt $a ] ; then
? ? ? ? echo the number less then random
? ? ? ? elif [ $n -gt $a ];then
? ? ? ? echo the number bigger then random
? ? ? ? else
? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? fi
done
echo is equality
特殊用法
? while循環的特殊用法(遍歷文件的每一行):
while read line; do
循環體
done < /PATH/FROM/SOMEFILE
? 依次讀取/PATH/FROM/SOMEFILE文件中的每一行,且將行賦值給變量line
? 練習
掃描/etc/passwd文件每一行,如發現GECOS字段為空,則填充用戶名和單位電
話為62985600,并提示該用戶的GECOS信息修改成功
取分區利用率
[root@CENTOS7 ~]#vim df.sh
#!/bin/bash
df | while read i ; do
? ? ? ? if echo $i | grep “^/dev/sd” > /dev/null ; then
? ? ? ? a=`echo $i | sed -r ‘s/.* ([0-9]+)%.*/\1/’`
? ? ? ? b=`echo $i | cut -d ” ” -f1`
? ? ? ? [ $a -gt 7 ] && echo the disk $b will be full userd $a%
? ? ? ? fi
done
~
將/etc/passwd中uid是偶數的行顯示用戶和uid
[root@CENTOS7 ~]#vim uid.sh
#!/bin/bash
while read link ; do
? ? ? ? a=`echo $link | cut -d “:” -f 3`
? ? ? ? b=`echo $link | cut -d “:” -f 1`
? ? ? ? let c=a%2
? ? ? ? if [ $c -eq 0 ];then
? ? ? ? echo $a ?$b
? ? ? ? fi
done < /etc/passwd
[root@CENTOS7 ~]#./uid.sh
0 root
2 daemon
4 lp
特殊用法
? 雙小括號方法,即((…))格式,也可以用于算術運算
? 雙小括號方法也可以使bash Shell實現C語言風格的變量操作
I=10
((I++))
? for循環的特殊格式:
for ((控制變量初始化;條件判斷表達式;控制變量的修正表達式))
do
循環體
done
? 控制變量初始化:僅在運行到循環代碼段時執行一次
? 控制變量的修正表達式:每輪循環結束會先進行控制變量修正運算,而后再做
條件判斷
[root@CENTOS7 ~]#vim sun.sh
#!/bin/bash
for (( sum=0 , i=1;$i<=100;i++ ));do
? ? ? ? let sum=sum+i
done
echo $sum
~
[root@CENTOS7 ~]#./sun.sh
5050
select循環與菜單
? select variable in list
do
循環體命令
done
? select 循環主要用于創建菜單,按數字順序排列的菜單項將顯示在
標準錯誤上,并顯示 PS3 提示符,等待用戶輸入
? 用戶輸入菜單列表中的某個數字,執行相應的命令
? 用戶輸入被保存在內置變量 REPLY 中
[root@CENTOS7 ~]#vim menu.sh
#!/bin/bash
PS3=”what do you wang to eat :”
select menu in baoyu yanwo haishen yuchi jitang ;do
? ? ? ? ? ? ? ? case $meny in
? ? ? ? ? ? ? ? baoyu)
? ? ? ? ? ? ? ? echo the baoyu price is 500
? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? ;;
? ? ? ? ? ? ? ? yanwo)
? ? ? ? ? ? ? ? echo yanwo price is 1000
? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? ;;
? ? ? ? ? ? ? ? haishen)
? ? ? ? ? ? ? ? echo haoshen price is 1500
? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? ;;
? ? ? ? ? ? ? ? yuchi)
? ? ? ? ? ? ? ? echo yuchi price is 2000
? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? ;;
? ? ? ? ? ? ? ? jitang)
? ? ? ? ? ? ? ? echo jitang price is free
? ? ? ? ? ? ? ? break
? ? ? ? ? ? ? ? ;;
? ? ? ? ? ? ? ? esac
done
select與case
? select 是個無限循環,因此要記住用 break 命令退出循環,或用
exit 命令終止腳本。也可以按 ctrl+c 退出循環
? select 經常和 case 聯合使用
? 與 for 循環類似,可以省略 in list,此時使用位置參量
信號捕捉trap
? trap ‘觸發指令’ 信號
自定義進程收到系統發出的指定信號后,將執行觸發指令,而不會執行原操
作
? trap ” 信號
忽略信號的操作
? trap ‘-‘ 信號
恢復原信號的操作
? trap -p
列出自定義信號操作
9信號在trap時不好用
kill -l 和trap -l 都可以查看信號列表
[root@CENTOS7 ~]#vim trap.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-08
#FileName: ? ? ? ? ? ? trap.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
trap ‘echo you press Ctrl + c’ 2
for i in {1..10};do
? ? ? ? echo $i
? ? ? ? sleep 1
done
trap ” 2
for i in {1..10};do
? ? ? ? echo $i
? ? ? ? ?sleep 1
done
~
“trap.sh” 22L, 482C written
[root@CENTOS7 ~]#./trap.sh
1
2
^Cyou press Ctrl + c
3
[root@CENTOS7 ~]#vim trap.sh
#!/bin/bash
trap ‘echo you press Ctrl + c’ 2
trap -p
for i in {1..10};do
? ? ? ? echo $i
? ? ? ? sleep 1
done
trap ” 2
trap -p
for i in {1..10};do
? ? ? ? echo $i
? ? ? ? ?sleep 1
done
[[]]和[]對比
1)從概念上講,二者是不同層次的東西
“[[“,是關鍵字,許多shell(如ash bsh)并不支持這種方式,ksh,bash等支持
“[“是一條命令,與test等價,大多數shell都支持;
2)[[]]結構比bash版本的[]更通用,在[[和]]之間的所有字符都不會被文件擴展或標記分割,但會有參數引用和命令替換;
用[[ … ]]測試結構比用[ … ]更能防止腳本里的許多邏輯錯誤;比如:&&,||,<和>操作符能在一個[[]]測試里通過,但在[]結構
會發生錯誤;
3)(())結構擴展并計算一個算術表達式的值;若表達式值為0,會返回1或假作為退出狀態碼;一個非零值的表達式返回一個0或真作為退出
狀態碼;這個結構跟test命令以及[]結構的討論正好相反
4)[ … ]為shell命令,所以在其中的表達式應該是它的命令行參數,所以字符串比較操作符”>”與”<“必須轉義,否則就變成了IO重定向
操作符;在[[中”<“與”>”不需轉義;
5)”[[“是關鍵字,不會做命令行擴展,相對語法就更嚴格,例如:
在[ … ]中可以用引號括起操作符,因為在做命令行擴展時會去掉這些引號,而在[[ … ]]中則不允許這樣做
6)[[ … ]]進行算術擴展,而[ … ]不做
1)[]和test
? 兩者是一樣的,命令行里test expr和[ expr ]效果相同;test的三個基本作用是判斷文件、判斷字符串、判斷整數;
? 支持使用與或非將表達式連接起來,要注意的有:
? 1]test中可用的比較運算符只有==和!=,兩者都是用于字符串比較的,不可用于整數比較;整數比較只能用-eq,-gt這
? 種形式;無論是字符串比較還是整數比較不要使用大于號小于號;若實在想用,可以使用尖括號的轉義形式,如比較”ab”
? 和”bc”:[ ab \< bc ],結果為真,即返回狀態為0;
2)[[]]
? 這是內置在shell中的一個命令:支持字符串的模式匹配,使用=~操作符支持shell的正則表達式;邏輯組合
? 可以不使用test的-a ,-o而使用&&,||,主要記住:
? 1]字符串比較時,可以把右邊的作為一個模式(這是右邊的字符串不加雙引號的情況下,若右邊字符串加了雙引號,則認為是一個文本字符串)
? 而不僅僅是一個字符串,比如[[ hello == hell? ]],結果為真
3)使用[]和[[]]時每一項兩邊都要有空格,[[ 1 == 2 ]]的結果為’假’,但[[ 1==2 ]]的結果為’真’,顯然后一種時錯誤的;
Linux組成
? Linux: kernel+rootfs
kernel: 進程管理、內存管理、網絡管理、驅動程序、文件系統、安全功能 ? 在內核包rpm -q kernel
rootfs:程序和glibc
庫:函數集合, function, 調用接口(頭文件負責描述)
過程調用:procedure,無返回值
函數調用:function
程序:二進制執行文件
? 內核設計流派:
單內核(monolithic kernel):Linux
把所有功能集成于同一個程序
微內核(micro kernel):Windows, Solaris
每種功能使用一個單獨子系統實現
[root@CENTOS7 ~]#ldd /bin/ls
linux-vdso.so.1 => ?(0x00007ffcccfb8000)
libselinux.so.1 => /lib64/libselinux.so.1 (0x00007f7b92c4f000)
libcap.so.2 => /lib64/libcap.so.2 (0x00007f7b92a4a000)
libacl.so.1 => /lib64/libacl.so.1 (0x00007f7b92840000)
libc.so.6 => /lib64/libc.so.6 (0x00007f7b9247d000)
libpcre.so.1 => /lib64/libpcre.so.1 (0x00007f7b9221b000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007f7b92016000)
/lib64/ld-linux-x86-64.so.2 (0x0000558e22dec000)
libattr.so.1 => /lib64/libattr.so.1 (0x00007f7b91e11000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f7b91bf5000)
內核
? Linux內核特點:
支持模塊化:.ko(內核對象)
如:文件系統,硬件驅動,網絡協議等
支持內核模塊的動態裝載和卸載
? 組成部分:
核心文件:/boot/vmlinuz- VERSION -release
ramdisk:輔助的偽根系統
CentOS 5: /boot/initrd- VERSION -release.img ? ramdisk
CentOS 6,7: /boot/initramfs- VERSION -release.img ? 各種和啟動相關的啟動模塊,ramfilesystem
模塊文件:/lib/modules/ VERSION -release
[root@CENTOS7 ~]#locate ext4.ko
/usr/lib/modules/3.10.0-693.el7.x86_64/kernel/fs/ext4/ext4.ko.xz
[root@CENTOS7 ~]#lsmod | grep ext4 ? ? lsmod查看內存中加載的模塊
[root@CENTOS7 ~]#lsmod | grep xfs
xfs ? ? ? ? ? ? ? ? ? 978100 ?3
libcrc32c ? ? ? ? ? ? ?12644 ?1 xfs
卸載模塊 modprobe -r e1000
重要的輔助文件
[root@CENTOS7 ~]#file /boot/initramfs-3.10.0-693.el7.x86_64.img
/boot/initramfs-3.10.0-693.el7.x86_64.img: ASCII cpio archive (SVR4 with no CRC)
[root@centos6 ~]#file /boot/initramfs-2.6.32-696.el6.x86_64.img
/boot/initramfs-2.6.32-696.el6.x86_64.img: gzip compressed data, from Unix, last modified: Tue Mar 27 17:14:27 2018, max compression
解壓縮
cp /boot/initramfs-2.6.32-696.el6.x86_64.img /data/boot/initramfs-2.6.32-696.el6.x86_64.img.gz
gzip -d /data/boot/initramfs-2.6.32-696.el6.x86_64.img.gz
cpio -tv < 解壓后的文件
CentOS6啟動流程
1.加載BIOS的硬件信息,獲取第一個啟動設備
2.讀取第一個啟動設備MBR的引導加載程序(grub)的啟動信息
3.加載核心操作系統的核心信息,核心開始解壓縮,并嘗試驅動所有的硬件設備
4.核心執行init程序,并獲取默認的運行信息
5.init程序執行/etc/rc.d/rc.sysinit文件
6.啟動核心的外掛模塊
7.init執行運行的各個批處理文件(scripts)
8.init執行/etc/rc.d/rc.local
9.執行/bin/login程序,等待用戶登錄
10.登錄之后開始以Shell控制主機
啟動流程
? POST:Power-On-Self-Test,加電自檢,是BIOS功能的一個主要部分。負責完成對CPU、主
板、內存、硬盤子系統、顯示子系統、串并行接口、鍵盤、CD-ROM光驅等硬件情況的檢測。
ROM:BIOS,Basic Input and Output System,保存著有關計算機系統最重要的基本輸
入輸出程序,系統信息設置、開機加電自檢程序和系統啟動自舉程序等。
RAM:CMOS互補金屬氧化物半導體,保存各項參數的設定
按次序查找引導設備,第一個有引導程序的設備為本次啟動設備
? bootloader: 引導加載器,引導程序
windows: ntloader,僅是啟動OS
Linux:功能豐富,提供菜單,允許用戶選擇要啟動系統或不同的內核版本;把用戶選定的
內核裝載到內存中的特定空間中,解壓、展開,并把系統控制權移交給內核
LILO:LInux LOader
GRUB: GRand Unified Bootloader ?宏偉統一的
GRUB 0.X: GRUB Legacy, GRUB2
啟動流程 ? grup 安裝的文件有一些放在MBR里
? MBR:
446: bootloader, ?64: 分區表, 2: 55AA
? GRUB:
primary boot loader : 1st stage,第一扇區后面的分區存放1.5 stage ?ext4存放在1.5階段
secondary boot loader :2nd stage,分區文件 放在/boot/grub ?想訪問/boot必須有ext4的驅動
? kernel:
自身初始化:
探測可識別到的所有硬件設備
加載硬件驅動程序(借助于ramdisk加載驅動)
以只讀方式掛載根文件系統 ? ?由 cat /boot/grub/grub.conf 告訴根的uuid,想掛載/需要知道/的文件系統,這個放在/boot/initramfs-2.6.32-696.el6.x86_64.img 這個文件中
運行用戶空間的第一個應用程序:/sbin/init
[root@centos6 ~]#ls /boot
config-2.6.32-696.el6.x86_64 ?grub ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? lost+found ? ? ? ? ? ? ? ? ? ? ? ?System.map-2.6.32-696.el6.x86_64
efi ? ? ? ? ? ? ? ? ? ? ? ? ? initramfs-2.6.32-696.el6.x86_64.img輔助文件,這個文件是裝系統的時候生成的 ?symvers-2.6.32-696.el6.x86_64.gz ?vmlinuz-2.6.32-696.el6.x86_64 ?主文件,這個文件是在光盤時直接拷過來的
一但破壞initramfs-2.6.32-696.el6.x86_64.img ?可以用mkinitrd /bootinitarmfs-`uname-r`.img `uname -r`來生成
ramdisk管理
? ?ramdisk文件的制作:
(1) mkinitrd命令
為當前正在使用的內核重新制作ramdisk文件
mkinitrd /boot/initramfs-$(uname -r).img $(uname -r)
(2) dracut命令
為當前正在使用的內核重新制作ramdisk文件
dracut /boot/initramfs-$(uname -r).img $(uname -r)
-r-xr-xr-x. 1 root root 4274992 Mar 29 ?2017 vmlinuz
[root@centos6 isolinux]#ll vmlinuz /boot/vmlinuz-2.6.32-696.el6.x86_64
-rwxr-xr-x. 1 root root 4274992 Mar 22 ?2017 /boot/vmlinuz-2.6.32-696.el6.x86_64
-r-xr-xr-x. 1 root root 4274992 Mar 29 ?2017 vmlinuz
md5sum
[root@centos6 isolinux]#md5sum vmlinuz /boot/vmlinuz-2.6.32-696.el6.x86_64
9c4cec060e29a7aa10350ca40d3f2f83 ?vmlinuz
9c4cec060e29a7aa10350ca40d3f2f83 ?/boot/vmlinuz-2.6.32-696.el6.x86_64
實驗:誤刪除/boot/vmlinuz-3.10.0-693.el7.x86_64 修復
實驗:centos6,7 上/boot/initramfs-2.6.32-696.el6.x86_64.img 損壞的修復
chroot /mnt/sysimage
mkinitrd /boot/initramfs-`uname -r`.img `uname -r`
sync
exit
exit
reboot
實驗:誤刪除/boot/vmlinuz-3.10.0-693.el7.x86_64 修復
進入光盤啟動,進入救援模式
chroot /mnt/sysimage
mkinitrd /boot/initramfs-`uname -r`.img `uname -r`
sync
sync
sync
exit
exit
reboot
誤刪除vmlinuz-3.10.0-693.el7.x86_64 恢復
[root@CENTOS7 boot]#rm -f vmlinuz-3.10.0-693.el7.x86_64
進入救援模式
cp /misc/cd/isolinux/vmlinuz /mnt/sysimage/boot/vmlinuz-`uname -r`
在centos6上進入救援模式后光盤沒有掛載
mount /dev/sr0 /misc
等腰三角形
[root@CENTOS7 ~]#vim triangle.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-08
#FileName: ? ? ? ? ? ? triangle.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
high=$1
for i in `seq $high`;do
? ? ? ? let wide=2*i-1
? ? ? ? let n=$high-$i
? ? ? ? for j in `seq $n`;do
? ? ? ? echo -e ” \c”
? ? ? ? done
? ? ? ? for k in `seq $wide` ;do
? ? ? ? echo -e “*\c”
? ? ? ? done
? ? ? ? echo
done
“triangle.sh” 23L, 512C written
[root@CENTOS7 ~]#./triangle.sh 5
? ? *
? ?***
? *****
?*******
*********
使用函數文件
? 可以將經常使用的函數存入函數文件,然后將函數文件載入shell
? 文件名可任意選取,但最好與相關任務有某種聯系。例如:functions.main
? 一旦函數文件載入shell,就可以在命令行或腳本中調用函數??梢允褂胹et命
令查看所有定義的函數,其輸出列表包括已經載入shell的所有函數
? 若要改動函數,首先用unset命令從shell中刪除函數。改動完畢后,再重新載
入此文件
創建函數文件
? 函數文件示例:
cat functions.main
#!/bin/bash
#functions.main
findit()
{
if [ $# -lt 1 ] ; then
echo “Usage:findit file”
return 1
fi
find / -name $1 –print
}
函數使用
? 函數的定義和使用:
? ?可在交互式環境下定義函數
? ?可將函數放在腳本文件中作為它的一部分
? ?可放在只包含函數的單獨文件中
? 調用:函數只有被調用才會執行
調用:給定函數名
函數名出現的地方,會被自動替換為函數代碼
? 函數的生命周期:被調用時創建,返回時終止
[root@CENTOS7 ~]#function1 () { echo function1 ; }
[root@CENTOS7 ~]#function1
function1
[root@CENTOS7 ~]#declare -f ? 查看系統中定義的所有函數
[root@CENTOS7 ~]#declare -f funcion1 ? ? 查看某個定義的函數
funcion1 ()
{
? ? echo function1
}
[root@CENTOS7 ~]#function func2 () { echo func2; }
[root@CENTOS7 ~]#func2
func2
[root@CENTOS7 ~]#function func3 { echo func3; }
[root@CENTOS7 ~]#func3
func3
[root@CENTOS7 ~]#func4 () {
> echo func4
> }
[root@CENTOS7 ~]#func4
func4
[root@CENTOS7 ~]#unset func4 ? ?刪除變量
[root@CENTOS7 ~]#declare -f func4
[root@CENTOS7 ~]#echo $?
1
[root@CENTOS7 ~]#less /etc/init.d/functions ? 這個文件中定義了很多function
[root@CENTOS7 ~]#declare -f func3
func3 ()
{
? ? echo func3
}
[root@CENTOS7 ~]#echo $?
0
如果cmd1失敗,執行cmd2和cmd3
cmd1 || { cmd1;cmd2; }其實就是一個匿名函數
如果用系統中已有的命令作為函數名,則函數名的優先級最高。高于外部命令,內部命令,別名
起函數名可以func_開頭
[root@CENTOS7 ~]#unset func2 func3 funcion1 ? ?可以一次性刪除多個函數
[root@CENTOS7 ~]#func1 () { name=mage;echo “func1:$name”; } ? 函數的生效范圍是當前shell
[root@CENTOS7 ~]#func1
func1:mage
[root@CENTOS7 ~]#echo $name
mage
[root@CENTOS7 ~]#name=wang
[root@CENTOS7 ~]#func1 () { echo “func1:$name”; } 相當于name=wang ; echo “func1:$name”
[root@CENTOS7 ~]#func1
func1:wang
讓函數的變量只影響自己而不影響shell
[root@CENTOS7 ~]#func1 (){ local name=mage;echo $name; } ? 本地變量
[root@CENTOS7 ~]#func1
mage
[root@CENTOS7 ~]#echo $name
wang
有效范圍:全局變量export> 普通變量(局部變量)>本地變量
聲明一個數字
[root@CENTOS7 ~]#func1 (){ declare -i name=100;echo $name; } ? declare -i 默認就是本地變量想要其生成普通變量declare -ig在centos7上支持,在centos6上不支持
[root@CENTOS7 ~]#func1
100
[root@CENTOS7 ~]#echo $name
wang
[root@CENTOS7 ~]#func1 (){ declare -ig name=100;echo $name; }
[root@CENTOS7 ~]#func1
100
[root@CENTOS7 ~]#echo $name
100
[root@CENTOS7 bin]#vim redyel.sh ? ?這個函數只能打印紅黃用加參數如 -r 來讓函數可以顯示黃紅
#!/bin/bash
redyel(){
? ? ? ? echo -e “\033[1;41m ?\033[1;42m ?\033[0m”
}
redyel
[root@CENTOS7 bin]#chmod +x redyel.sh
[root@CENTOS7 bin]#redyel.sh
函數后面也可以加位置參數用法和腳本的一樣
[root@CENTOS7 bin]#func1 () { echo arg1:$1;echo arg2:$2;echo arg@:$@;echo arg#:$#; }
[root@CENTOS7 bin]#func1
arg1:
arg2:
arg@:
arg#:0
[root@CENTOS7 bin]#func1 a b c d
arg1:a
arg2:b
arg@:a b c d
arg#:4
[root@CENTOS7 bin]#vim redyel.sh ? ? return退出當前函數
#!/bin/bash
redyel(){
? ? ? ? ?if [ “$1” = “-r” ];then
? ? ? ? ? ? ? ? echo -e “\033[1;42m ?\033[1;41m ?\033[0m”
? ? ? ? ? ? ? ? return
? ? ? ? ? ? ? ? fi
? ? ? ? ? ? ? ? echo -e “\033[1;41m ?\033[1;42m ?\033[0m”
}
redyel
redyel -r
[root@CENTOS7 ~]#version () { ver=`cat /etc/centos-release | sed -r ‘s/.* ([0-9]+)\..*/\1/’` ;echo $ver; }[root@CENTOS7 ~]#version
7
if [ `version` -eq 6 ];then
echo version is old
else echo cersion is new
fi
cersion is new
[root@CENTOS7 ~]#add (){ echo $[$1+$2]; }
[root@CENTOS7 ~]#add 1 2
3
[root@CENTOS7 ~]#add 5 6
11
函數返回值
? 函數有兩種返回值:
? 函數的執行結果返回值:
(1) 使用echo等命令進行輸出
(2) 函數體中調用命令的輸出結果
? 函數的退出狀態碼:
(1) 默認取決于函數中執行的最后一條命令的退出狀態碼
(2) 自定義退出狀態碼,其格式為:
return 從函數中返回,用最后狀態命令決定返回值 ? return 只能在函數中使用
return 0 無錯誤返回。
return 1-255 有錯誤返回
[root@CENTOS7 ~]#return
-bash: return: can only `return’ from a function or sourced script
交互式環境下定義和使用函數
? 示例:
dir() {
> ls -l
> }
? 定義該函數后,若在$后面鍵入dir,其顯示結果同ls -l的作用相同
dir
? 該dir函數將一直保留到用戶從系統退出,或執行了如下所示的unset命令
unset dir
在腳本中定義及使用函數
? 函數在使用前必須定義,因此應將函數定義放在腳本開始部分,直至shell首次發現它
后才能使用
? 調用函數僅使用其函數名即可
? 示例:
cat func1
#!/bin/bash
# func1
hello()
{
echo “Hello there today’s date is `date +%F`”
}
echo “now going to the function hello”
hello
echo “back from the function”
使用函數文件
? 可以將經常使用的函數存入函數文件,然后將函數文件載入shell
? 文件名可任意選取,但最好與相關任務有某種聯系。例如:functions.main
? 一旦函數文件載入shell,就可以在命令行或腳本中調用函數??梢允褂胹et命
令查看所有定義的函數,其輸出列表包括已經載入shell的所有函數
? 若要改動函數,首先用unset命令從shell中刪除函數。改動完畢后,再重新載
入此文件
[root@CENTOS7 ~]#vim function ? ?將函數放入一個文本文件中
#!/bin/bash
version () { ver=`cat /etc/centos-release | sed -r ‘s/.* ([0-9]+)\..*/\1/’` ;echo $ver; }
? redyel(){
? ? ? ? if [ “$1” = “-r” ];then
? ? ? ? ? ? ? ? ? ? ? ? ?echo -e “\033[1;42m ?\033[1;41m ?\033[0m”
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?return
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?fi
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?echo -e “\033[1;41m ?\033[1;42m ?\033[0m”
[root@CENTOS7 ~]#vim f3.sh ? ?在腳本中調用寫好的函數
#!/bin/bash
source function
version
redyel
[root@CENTOS7 ~]#bash f3.sh
7
[root@CENTOS7 ~]#ls /etc/init.d ? ? 系統中就是把函數寫在functions中,在腳本中調用些函數。
functions ?netconsole ?network ?README
[root@CENTOS7 ~]#ll /etc/init.d/functions /etc/rc.d/init.d/functions
-rw-r–r–. 1 root root 17500 May ?3 ?2017 /etc/init.d/functions
-rw-r–r–. 1 root root 17500 May ?3 ?2017 /etc/rc.d/init.d/functions
[root@CENTOS7 ~]#ll -d /etc/init.d /etc/rc.d/init.d
lrwxrwxrwx. 1 root root 11 Mar 27 17:54 /etc/init.d -> rc.d/init.d
drwxr-xr-x. 2 root root 70 Mar 27 17:56 /etc/rc.d/init.d
載入函數
? 函數文件已創建好后,要將它載入shell
? 定位函數文件并載入shell的格式
. filename 或 source filename
? 注意:此即<點> <空格> <文件名>
這里的文件名要帶正確路徑
? 示例:
上例中的函數,可使用如下命令:
. functions.main
[root@CENTOS7 ~]#. /etc/init.d/functions ? 調用系統自帶函數
[root@CENTOS7 ~]#action “command successful” ? 系統自帶函數中的action作用
command successful ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [ ?OK ?]
[root@CENTOS7 ~]#action “command successful” /bin/false
command successful ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [FAILED]
[root@CENTOS7 ~]#action “command successful” /bin/true
command successful ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [ ?OK ?]
如果已經調用的函數修改了函數的內容應該再次引用source function
檢查載入函數
? 使用set命令檢查函數是否已載入。set命令將在shell中顯示所有的載入函數
? 示例:
set
findit=( )
{
if [ $# -lt 1 ]; then
echo “usage :findit file”;
return 1
fi
find / -name $1 -print
}
…
執行shell函數
? 要執行函數,簡單地鍵入函數名即可
? 示例:
findit groups
/usr/bin/groups
/usr/local/backups/groups.bak
刪除shell函數
? 現在對函數做一些改動后,需要先刪除函數,使其對shell不可用。使用unset命
令完成刪除函數
? 命令格式為:
unset function_name
? 示例:
unset findit
再鍵入set命令,函數將不再顯示
? 環境函數
使子進程也可使用
聲明:export -f function_name
查看:export -f 或 declare -xf
函數參數
? 函數可以接受參數:
傳遞參數給函數:調用函數時,在函數名后面以空白分隔給定參數列表即可;
例如“testfunc arg1 arg2 …”
在函數體中當中,可使用$1, $2, …調用這些參數;還可以使用$@, $*, $#
等特殊變量
[root@CENTOS7 ~]#export -f func1 ? ? ? 將普通函數定義成全局函數
[root@CENTOS7 ~]#bash
[root@CENTOS7 ~]#func1
func1
[root@CENTOS7 ~]#expotr -f func2 () { echo func2 ; } ? ?不可以直接定義一個正在創建的函數
-bash: syntax error near unexpected token `(‘
函數變量
? 變量作用域:
環境變量:當前shell和子shell有效 ? 全局變量
本地變量:只在當前shell進程有效,為執行腳本會啟動專用子shell進程; ?普通變量
因此,本地變量的作用范圍是當前shell腳本程序文件,包括腳本中的函數
局部變量:函數的生命周期;函數結束時變量被自動銷毀 ? ? 本地變量
? 注意:如果函數中有局部變量,如果其名稱同本地變量,使 ?用局部變量
? 在函數中定義局部變量的方法
local NAME=VALUE
函數遞歸示例
? 函數遞歸:
函數直接或間接調用自身
注意遞歸層數
? 遞歸實例:
階乘是基斯頓·卡曼于 1808 年發明的運算符號,是數學術語
一個正整數的階乘(factorial)是所有小于及等于該數的正整數的積,并且有0的
階乘為1,自然數n的階乘寫作n!
n!=1×2×3×…×n
階乘亦可以遞歸方式定義:0!=1,n!=(n-1)!×n
n!=n(n-1)(n-2)…1
n(n-1)! = n(n-1)(n-2)!
[root@CENTOS7 ~]#func1 () { let i++;echo $i;echo func1;func1; }
這個數會不斷的累加直到機器死機,這些數會加載到內存中,中斷執行后繼續執行,會接著上次的執行結果繼續執行
函數遞歸示例
? 示例:fact.sh ? ? 如果$1是一個負數這無限循環
#!/bin/bash
#
fact() {
if [ $1 -eq 0 -o $1 -eq 1 ]; then
echo 1
else
echo $[$1*$(fact $[$1-1])]
fi
}
fact $1
fork炸彈
? fork炸彈是一種惡意程序,它的內部是一個不斷在fork進程的無限循環,實質是
一個簡單的遞歸程序。由于程序是遞歸的,如果沒有任何限制,這會導致這個
簡單的程序迅速耗盡系統里面的所有資源
? 函數實現
:(){ :|:& };:
bomb() { bomb | bomb & }; bomb
? 腳本實現
cat Bomb.sh
#!/bin/bash
./$0|./$0&
系統啟動流程
? init程序的類型:
? SysV: init, CentOS 5之前
配置文件:/etc/inittab ? ? ? redhat
? Upstart: init,CentOS 6
配置文件:/etc/inittab, /etc/init/*.conf
? Systemd:systemd, CentOS 7 ? ? ?ubantu
配置文件:/usr/lib/systemd/system
? /etc/systemd/system ? ? ? ? ?redhat
啟動流程
? ?/sbin/init CentOS6之前
? ?運行級別:為系統運行或維護等目的而設定;0-6:7個級別
0:關機
1:單用戶模式(root自動登錄), single, 維護模式
2: 多用戶模式,啟動網絡功能,但不會啟動NFS;維護模式
3:多用戶模式,正常模式;文本界面
4:預留級別;可同3級別
5:多用戶模式,正常模式;圖形界面
6:重啟
? ?默認級別: 3, 5
? ?切換級別:init #
? ?查看級別:runlevel ; who -r
init初始化
? init讀取其初始化文件:/etc/inittab
初始運行級別(RUN LEVEL)
系統初始化腳本
對應運行級別的腳本目錄
捕獲某個關鍵字順序
定義UPS電源終端/恢復腳本
在虛擬控制臺生成getty
在運行級別5初始化X
[root@centos6 ~]#cat /etc/inittab
# inittab is only used by upstart for the default runlevel.
#
# ADDING OTHER CONFIGURATION HERE WILL HAVE NO EFFECT ON YOUR SYSTEM.
#
# System initialization is started by /etc/init/rcS.conf
#
# Individual runlevels are started by /etc/init/rc.conf
#
# Ctrl-Alt-Delete is handled by /etc/init/control-alt-delete.conf
#
# Terminal gettys are handled by /etc/init/tty.conf and /etc/init/serial.conf,
# with configuration in /etc/sysconfig/init.
#
# For information on how to write upstart event handlers, or how
# upstart works, see init(5), init(8), and initctl(8).
#
# Default runlevel. The runlevels used are:
# ? 0 – halt (Do NOT set initdefault to this)
# ? 1 – Single user mode
# ? 2 – Multiuser, without NFS (The same as 3, if you do not have networking)
# ? 3 – Full multiuser mode
# ? 4 – unused
# ? 5 – X11
# ? 6 – reboot (Do NOT set initdefault to this)
#
id:5:initdefault: ? ? id表示這個行的名字 5 模式 initdefault默認模式
id:6:initdefault: ? 設置成6的話會無限重啟
解決辦法 在重啟是按任意鍵,在選擇啟動系統的地方按a鍵然后 (1,3,5)進入你想進的模式,在這選擇模式后不會讀取/etc/inittan文件。
1模式可以重新設置口令,進入1模式后身份是root
直接passwd重置口令就可以了
[root@centos6 ~]#cat /etc/rc.d/rc.sysinit ? ? ?初始化的第一個腳本
#!/bin/bash
#
# /etc/rc.d/rc.sysinit – run once at boot time
#
# Taken in part from Miquel van Smoorenburg’s bcheckrc.
#
HOSTNAME=$(/bin/hostname)
set -m
if [ -f /etc/sysconfig/network ]; then
? ? . /etc/sysconfig/network
fi
if [ -z “$HOSTNAME” -o “$HOSTNAME” = “(none)” ]; then
? ? HOSTNAME=localhost
fi
啟動流程
? /etc/rc.d/rc.sysinit: 系統初始化腳本
(1) 設置主機名
(2) 設置歡迎信息
(3) 激活udev和selinux
(4) 掛載/etc/fstab文件中定義的文件系統
(5) 檢測根文件系統,并以讀寫方式重新掛載根文件系統
(6) 設置系統時鐘
(7) 激活swap設備
(8) 根據/etc/sysctl.conf文件設置內核參數
(9) 激活lvm及software raid設備
(10) 加載額外設備的驅動程序
(11) 清理操作
CentOS 5的inittab文件
? ?配置文件:/etc/inittab
? ?每一行定義一種action以及與之對應的process
id:runlevel:action:process
action:
wait: 切換至此級別運行一次
respawn:此process終止,就重新啟動之
initdefault:設定默認運行級別;process省略
sysinit:設定系統初始化方式,此處一般為指定
/etc/rc.d/rc.sysinit
ca::ctrlaltdel:/sbin/shutdown -t3 -r now
id:3:initdefault:
si::sysinit:/etc/rc.d/rc.sysinit
l0:0:wait:/etc/rc.d/rc 0
l1:1:wait:/etc/rc.d/rc 1…
l6:6:wait:/etc/rc.d/rc 6
進入5模式后
for i in /etc/rc$runlevel.d/S* ; do
# Check if the subsystem is already up.
subsys=${i#/etc/rc$runlevel.d/S??}
[ -f /var/lock/subsys/$subsys ] && continue
[ -f /var/lock/subsys/$subsys.init ] && continue
check_runlevel “$i” || continue
# If we’re in confirmation mode, get user confirmation
if [ “$do_confirm” = “yes” ]; then
confirm $subsys
rc=$?
if [ “$rc” = “1” ]; then
continue
elif [ “$rc” = “2” ]; then
do_confirm=”no”
fi
fi
選著進入/etc/rc5.d ? ?先運行K開頭的并stop在運行S開頭的文件并start
[root@centos6 ~]#ls /etc/rc5.d ? ?根據文件名的順序執行
K01smartd ? ? ? ?K60nfs ? ? ? ? ? ? K95firstboot ? ? S22messagebus ? ? ? ?S55sshd
K02oddjobd ? ? ? K61nfs-rdma ? ? ? ?K99rngd ? ? ? ? ?S23NetworkManager ? ?S58ntpd
K05wdaemon ? ? ? K69rpcsvcgssd ? ? ?S01sysstat ? ? ? S24nfslock ? ? ? ? ? S70spice-vdagentd
K10psacct ? ? ? ?K73winbind ? ? ? ? S02lvm2-monitor ?S24openct ? ? ? ? ? ?S80postfix
K10saslauthd ? ? K75ntpdate ? ? ? ? S05rdma ? ? ? ? ?S24rpcgssd ? ? ? ? ? S82abrtd
K15htcacheclean ?K75quota_nld ? ? ? S08ip6tables ? ? S25blk-availability ?S83abrt-ccpp
K15httpd ? ? ? ? K76ypbind ? ? ? ? ?S10network ? ? ? S25cups ? ? ? ? ? ? ?S90crond
K15svnserve ? ? ?K84wpa_supplicant ?S11auditd ? ? ? ?S25netfs ? ? ? ? ? ? S95atd
K35nmb ? ? ? ? ? K87restorecond ? ? S11portreserve ? S26acpid ? ? ? ? ? ? S99certmonger
K35smb ? ? ? ? ? K88sssd ? ? ? ? ? ?S12rsyslog ? ? ? S26haldaemon ? ? ? ? S99local
K36mysqld ? ? ? ?K89netconsole ? ? ?S13cpuspeed ? ? ?S26udev-post
K50dnsmasq ? ? ? K89rdisc ? ? ? ? ? S13irqbalance ? ?S27pcscd
K50kdump ? ? ? ? K92iptables ? ? ? ?S13rpcbind ? ? ? S28autofs
K50vsftpd ? ? ? ?K92pppoe-server ? ?S15mdmonitor ? ? S50bluetooth
[root@centos6 ~]#/etc/rc5.d/K01smartd stop ? ? 可以這樣停止程序
Shutting down smartd: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[FAILED]
相當于
[root@centos6 ~]#service smartd stop
Shutting down smartd: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[FAILED]
這些服務分為:
獨立服務:不依賴于別人的服務
[root@centos6 ~]#ls /etc/init.d ? ? /etc/rc5.d中的服務是這個文件夾下的服務的軟連接
abrt-ccpp ? ? ? ? dnsmasq ? ? ? lvm2-monitor ? ?ntpdate ? ? ? rpcbind ? ? ? ? svnserve
abrtd ? ? ? ? ? ? firstboot ? ? mdmonitor ? ? ? oddjobd ? ? ? rpcgssd ? ? ? ? sysstat
abrt-oops ? ? ? ? functions ? ? messagebus ? ? ?openct ? ? ? ?rpcidmapd ? ? ? udev-post
acpid ? ? ? ? ? ? haldaemon ? ? mysqld ? ? ? ? ?pcscd ? ? ? ? rpcsvcgssd ? ? ?vsftpd
atd ? ? ? ? ? ? ? halt ? ? ? ? ?netconsole ? ? ?portreserve ? rsyslog ? ? ? ? wdaemon
auditd ? ? ? ? ? ?htcacheclean ?netfs ? ? ? ? ? postfix ? ? ? sandbox ? ? ? ? winbind
autofs ? ? ? ? ? ?httpd ? ? ? ? network ? ? ? ? pppoe-server ?saslauthd ? ? ? wpa_supplicant
blk-availability ?ip6tables ? ? NetworkManager ?psacct ? ? ? ?single ? ? ? ? ?ypbind
bluetooth ? ? ? ? iptables ? ? ?nfs ? ? ? ? ? ? quota_nld ? ? smartd
certmonger ? ? ? ?irqbalance ? ?nfslock ? ? ? ? rdisc ? ? ? ? smb
cpuspeed ? ? ? ? ?kdump ? ? ? ? nfs-rdma ? ? ? ?rdma ? ? ? ? ?spice-vdagentd
crond ? ? ? ? ? ? killall ? ? ? nmb ? ? ? ? ? ? restorecond ? sshd
cups ? ? ? ? ? ? ?lvm2-lvmetad ?ntpd ? ? ? ? ? ?rngd ? ? ? ? ?sssd
之前定義的計劃任務cron @reboot root reboot 進入后就會無限重啟
之所以進入1模式可以進行修改是因為在5模式的時候cron默認是開機啟動而在
1模式的時候cron默認開機不啟動
查看5模式下開機啟動項
ntsysv –level=5
在這個命令界面下 去掉點*就是修改/etc/rc5.d中的軟連接文件夾的名字來完成對開機啟動項的默認修改
也可以直接修改/etc/rc5.d/中的軟連接的名字來直接更改啟動開啟項
列如mv /etc/rc5.d/K05atd /etc/rc5.d/S95atd
ntsysv –level=3
去掉 atd *
atd就變成K開頭的
[root@centos6 ~]#ls /etc/rc3.d/
K01smartd ? ? ? ? ?K35nmb ? ? ? ? K76ypbind ? ? ? ? ?S02lvm2-monitor ?S15mdmonitor ? ? ? ? S27pcscd
K02oddjobd ? ? ? ? K35smb ? ? ? ? K87restorecond ? ? S05rdma ? ? ? ? ?S19rpcgssd ? ? ? ? ? S28autofs
K05atd ? ? ? ? ? ? K36mysqld ? ? ?K88sssd ? ? ? ? ? ?S08ip6tables ? ? S22messagebus ? ? ? ?S50bluetooth
K05wdaemon ? ? ? ? K50dnsmasq ? ? K88wpa_supplicant ?S10network ? ? ? S23NetworkManager ? ?S55sshd
K100kdump ? ? ? ? ?K50vsftpd ? ? ?K89netconsole ? ? ?S11auditd ? ? ? ?S24openct ? ? ? ? ? ?S58ntpd
K10psacct ? ? ? ? ?K60nfs ? ? ? ? K89rdisc ? ? ? ? ? S11portreserve ? S25blk-availability ?S80postfix
K10saslauthd ? ? ? K61nfs-rdma ? ?K92iptables ? ? ? ?S12rsyslog ? ? ? S25cups ? ? ? ? ? ? ?S82abrt-ccpp
K15htcacheclean ? ?K69rpcsvcgssd ?K92pppoe-server ? ?S13cpuspeed ? ? ?S25netfs ? ? ? ? ? ? S82abrtd
K15httpd ? ? ? ? ? K73winbind ? ? K95firstboot ? ? ? S13irqbalance ? ?S26acpid ? ? ? ? ? ? S90crond
K15svnserve ? ? ? ?K75ntpdate ? ? K99rngd ? ? ? ? ? ?S13rpcbind ? ? ? S26haldaemon ? ? ? ? S99certmonger
K30spice-vdagentd ?K75quota_nld ? S01sysstat ? ? ? ? S14nfslock ? ? ? S26udev-post
[root@centos6 ~]#chkconfig –list atd ? 查看所有模式下atd默認啟動情況
atd ? ? ? ? ? ? 0:off 1:off 2:off 3:on 4:on 5:on 6:off
[root@centos6 ~]#chkconfig –level=35 atd off ? ? 將3,5模式的默認設置改變
[root@centos6 ~]#chkconfig –list atd
atd ? ? ? ? ? ? 0:off 1:off 2:off 3:off 4:on 5:off 6:off
[root@centos6 ~]#chkconfig atd off
[root@centos6 ~]#chkconfig atd on
[root@centos6 ~]#chkconfig –list atd ? ?默認開啟或者關閉的是2,3,4,5模式
atd ? ? ? ? ? ? 0:off 1:off 2:on 3:on 4:on 5:on 6:off
禁止防火墻啟動
chkconfig iptables off
K開頭的文件在系統啟動的時候是根本不啟動的,如何判斷這個程序起沒啟動
[ -f/var/lock/subsys ]
但是如果是init3來切換模式則有可能這個文件是已經啟動的,因此還要執行后續命令 ?stop
[root@centos6 ~]#ll /var/lock/subsys ? 這里就是放個文件名,文件根本沒有內容
total 0
-rw-r–r–. 1 root root 0 May 10 08:59 abrt-ccpp
-rw-r–r–. 1 root root 0 May 10 08:59 abrtd
-rw-r–r–. 1 root root 0 May 10 08:59 acpid
-rw-r–r–. 1 root root 0 May 10 08:59 atd
-rw-r–r–. 1 root root 0 May 10 08:59 auditd
-rw-r–r–. 1 root root 0 May 10 08:59 autofs
-rw-r–r–. 1 root root 0 May 10 08:59 blk-availability
-rw-r–r–. 1 root root 0 May 10 08:59 certmonger
-rw-r–r–. 1 root root 0 May 10 08:59 crond
-rw-r–r–. 1 root root 0 May 10 08:59 cups
-rw-r–r–. 1 root root 0 May 10 08:59 haldaemon
-rw-r–r–. 1 root root 0 May 10 08:58 ip6tables
-rw-r–r–. 1 root root 0 May 10 08:59 local
-rw-r–r–. 1 root root 0 May 10 08:58 lvm2-monitor
-rw-r–r–. 1 root root 0 May 10 08:59 messagebus
-rw-r–r–. 1 root root 0 May 10 08:59 netfs
-rw-r–r–. 1 root root 0 May 10 08:58 network
-rw-r–r–. 1 root root 0 May 10 08:59 NetworkManager
-rw-r–r–. 1 root root 0 May 10 08:59 ntpd
-rw-r–r–. 1 root root 0 May 10 08:59 openct
-rw——-. 1 root root 0 May 10 08:59 pcscd
-rw-r–r–. 1 root root 0 May 10 08:59 postfix
-rw-r–r–. 1 root root 0 May 10 08:58 rdma
-rw-r–r–. 1 root root 0 May 10 08:59 rpcbind
-rw-r–r–. 1 root root 0 May 10 08:59 rpc.statd
-rw——-. 1 root root 0 May 10 08:59 rsyslog
-rw-r–r–. 1 root root 0 May 10 08:59 sshd
[root@centos6 ~]#ls /etc/rc5.d ?服務的前后順序很重要,因為后面的服務有可能依賴前面的服務,因此當自己寫了一個服務的時候應盡量往后放,不是按數字排序而是按字符次序排序。
K01smartd ? ? ? ?K60nfs ? ? ? ? ? ? K95firstboot ? ? S22messagebus ? ? ? ?S55sshd
K02oddjobd ? ? ? K61nfs-rdma ? ? ? ?K99rngd ? ? ? ? ?S23NetworkManager ? ?S58ntpd
K05wdaemon ? ? ? K69rpcsvcgssd ? ? ?S01sysstat ? ? ? S24nfslock ? ? ? ? ? S70spice-vdagentd
K10psacct ? ? ? ?K73winbind ? ? ? ? S02lvm2-monitor ?S24openct ? ? ? ? ? ?S80postfix
K10saslauthd ? ? K75ntpdate ? ? ? ? S05rdma ? ? ? ? ?S24rpcgssd ? ? ? ? ? S82abrtd
K15htcacheclean ?K75quota_nld ? ? ? S08ip6tables ? ? S25blk-availability ?S83abrt-ccpp
K15httpd ? ? ? ? K76ypbind ? ? ? ? ?S10network ? ? ? S25cups ? ? ? ? ? ? ?S90crond
K15svnserve ? ? ?K84wpa_supplicant ?S11auditd ? ? ? ?S25netfs ? ? ? ? ? ? S95atd
K35nmb ? ? ? ? ? K87restorecond ? ? S11portreserve ? S26acpid ? ? ? ? ? ? S99certmonger
K35smb ? ? ? ? ? K88sssd ? ? ? ? ? ?S12rsyslog ? ? ? S26haldaemon ? ? ? ? S99local
K36mysqld ? ? ? ?K89netconsole ? ? ?S13cpuspeed ? ? ?S26udev-post
K50dnsmasq ? ? ? K89rdisc ? ? ? ? ? S13irqbalance ? ?S27pcscd
K50kdump ? ? ? ? K92iptables ? ? ? ?S13rpcbind ? ? ? S28autofs
K50vsftpd ? ? ? ?K92pppoe-server ? ?S15mdmonitor ? ? S50bluetooth
S開頭的文件順序越靠前則在K開頭的文件里順序就越靠后,反之依然。
.
CentOS 6 /etc/inittab和相關文件
? /etc/inittab
設置系統默認的運行級別
id:3:initdefault:
? ?示例:
破解CentOS5和6的root口令
? /etc/init/control-alt-delete.conf
? /etc/init/tty.conf
? /etc/init/start-ttys.conf
? ?/etc/init/rc.conf
? /etc/init/prefdm.conf
啟動流程
? 說明:rc N –> 意味著讀取/etc/rc.d/rcN.d/
K*: K##*:##運行次序;數字越小,越先運行;數字越小的服務,通常為
依賴到別的服務
S*: S##*:##運行次序;數字越小,越先運行;數字越小的服務,通常為
被依賴到的服務
for srv in /etc/rc.d/rcN.d/K*; do
$srv stop
done
for srv in /etc/rc.d/rcN.d/S*; do
$srv start
done
chkconfig命令
? ?chkconfig命令
? ?查看服務在所有級別的啟動或關閉設定情形:
chkconfig [–list] [name]
? ?添加:
SysV的服務腳本放置于/etc/rc.d/init.d (/etc/init.d)
chkconfig –add name
#!/bin/bash
#LLLL 表示初始在哪個級別下啟動,-表示都不啟動
# chkconfig: LLLL nn nn
? ?刪除:
chkconfig –del name
? ?修改指定的鏈接類型
chkconfig [–level levels] name <on|off|reset>
–level LLLL: 指定要設置的級別;省略時表示2345
? ntsysv命令
xinetd管理的服務
? service 命令:手動管理服務
service 服務 start|stop|restart
service –status-all
? 瞬態(Transient)服務被xinetd進程所管理
進入的請求首先被xinetd代理
配置文件:/etc/xinetd.conf、/etc/xinetd.d/<service>
與libwrap.so文件鏈接
用chkconfig控制的服務:
chkconfig tftp on
啟動流程
? 注意:正常級別下,最后啟動一個服務S99local沒有鏈接至/etc/rc.d/init.d一個
服務腳本,而是指向了/etc/rc.d/rc.local腳本
? 不便或不需寫為服務腳本放置于/etc/rc.d/init.d/目錄,且又想開機時自動運行
的命令,可直接放置于/etc/rc.d/rc.local文件中
? /etc/rc.d/rc.local在指定運行級別腳本后運行
? 可以根據情況,進行自定義修改
啟動流程
? 1:2345:respawn:/usr/sbin/mingetty tty1
? 2:2345:respawn:/usr/sbin/mingetty tty2
? ?…
? 6:2345:respawn:/usr/sbin/mingetty tty6
mingetty會自動調用login程序
? x:5:respawn:/etc/X11/prefdm -nodaemon
啟動過程
? 總結:/sbin/init –> (/etc/inittab) –> 設置默認運行級別 –> 運行系統初始
腳本、完成系統初始化 –> (關閉對應下需要關閉的服務)啟動需要啟動服務 —
> 設置登錄終端
? ?CentOS 6 init程序為: upstart, 其配置文件:
/etc/inittab, /etc/init/*.conf,配置文件的語法 遵循 upstart配置文件語
法格式,和CentOS5不同
自定義一個開機開啟或者關閉的服務
在文件夾/etc/init.d中加入一個腳本,腳本格式是
[root@centos6 init.d]#cat atd
#!/bin/sh
# chkconfig: ? 345 95 5 ? ?345 代表在上面模式下開機啟動 95是S文件的開啟次序,5是K的關閉次序
#chkconfig : – 96 4 代表所有模式都是開啟的
在/etc/init.d/文件夾下
vim testsev ? ? 模擬一個服務,
#!/bin/bash
#chkconfig: 35 ?96 3
#description: test service
. /etc/init.d/functions
case $1 in
start)
? ? ? ? action ” testservice is starting”
? ? ? ? touch /var/lock/subsys/testservice
? ? ? ? ;;
stop) ? rm -f /var/lock/subsys/testservice
? ? ? ? action “testservice is stopped”
? ? ? ? ;;
status)
? ? ? ? [ -f /var/lock/subsys/testservice ] && echo testservice is running || echo testservice is stopped
? ? ? ? ;;
*)
? ? ? ? echo “usage: service testservice start|stop|status”
? ? ? ? ;;
esac
雖然開啟了服務,但是這個服務并沒有加入到3 和 5 模式中 所以chkconfig –list ?看不到這個服務
[root@centos6 init.d]#./testservice start
?testservice is starting ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [ ?OK ?]
[root@centos6 init.d]#chkconfig –list
[root@centos6 init.d]#chkconfig –add testservice ? 將這個服務添加進相應的模式中
[root@centos6 init.d]#chkconfig –add testservice
[root@centos6 init.d]#chkconfig –list testservice
testservice ? ? 0:off 1:off 2:off 3:on 4:off 5:on 6:off
[root@centos6 init.d]#ls /etc/rc5.d
K01smartd ? ? ? ?K60nfs ? ? ? ? ? ? K95firstboot ? ? S22messagebus ? ? ? ?S55sshd
K02oddjobd ? ? ? K61nfs-rdma ? ? ? ?K99rngd ? ? ? ? ?S23NetworkManager ? ?S58ntpd
K05wdaemon ? ? ? K69rpcsvcgssd ? ? ?S01sysstat ? ? ? S24nfslock ? ? ? ? ? S70spice-vdagentd
K10psacct ? ? ? ?K73winbind ? ? ? ? S02lvm2-monitor ?S24openct ? ? ? ? ? ?S80postfix
K10saslauthd ? ? K75ntpdate ? ? ? ? S05rdma ? ? ? ? ?S24rpcgssd ? ? ? ? ? S82abrtd
K15htcacheclean ?K75quota_nld ? ? ? S08ip6tables ? ? S25blk-availability ?S83abrt-ccpp
K15httpd ? ? ? ? K76ypbind ? ? ? ? ?S10network ? ? ? S25cups ? ? ? ? ? ? ?S90crond
K15svnserve ? ? ?K84wpa_supplicant ?S11auditd ? ? ? ?S25netfs ? ? ? ? ? ? S95atd
K35nmb ? ? ? ? ? K87restorecond ? ? S11portreserve ? S26acpid ? ? ? ? ? ? S96testservice
K35smb ? ? ? ? ? K88sssd ? ? ? ? ? ?S12rsyslog ? ? ? S26haldaemon ? ? ? ? S99certmonger
K36mysqld ? ? ? ?K89netconsole ? ? ?S13cpuspeed ? ? ?S26udev-post ? ? ? ? S99local
K50dnsmasq ? ? ? K89rdisc ? ? ? ? ? S13irqbalance ? ?S27pcscd
K50kdump ? ? ? ? K92iptables ? ? ? ?S13rpcbind ? ? ? S28autofs
K50vsftpd ? ? ? ?K92pppoe-server ? ?S15mdmonitor ? ? S50bluetooth
[root@centos6 init.d]#chkconfig –level 5 testservice off
[root@centos6 init.d]#ls /etc/rc5.d
K01smartd ? ? ? ?K50vsftpd ? ? ? ? ?K92pppoe-server ?S15mdmonitor ? ? ? ? S50bluetooth
K02oddjobd ? ? ? K60nfs ? ? ? ? ? ? K95firstboot ? ? S22messagebus ? ? ? ?S55sshd
K03testservice ? K61nfs-rdma ? ? ? ?K99rngd ? ? ? ? ?S23NetworkManager ? ?S58ntpd
K05wdaemon ? ? ? K69rpcsvcgssd ? ? ?S01sysstat ? ? ? S24nfslock ? ? ? ? ? S70spice-vdagentd
K10psacct ? ? ? ?K73winbind ? ? ? ? S02lvm2-monitor ?S24openct ? ? ? ? ? ?S80postfix
K10saslauthd ? ? K75ntpdate ? ? ? ? S05rdma ? ? ? ? ?S24rpcgssd ? ? ? ? ? S82abrtd
K15htcacheclean ?K75quota_nld ? ? ? S08ip6tables ? ? S25blk-availability ?S83abrt-ccpp
K15httpd ? ? ? ? K76ypbind ? ? ? ? ?S10network ? ? ? S25cups ? ? ? ? ? ? ?S90crond
K15svnserve ? ? ?K84wpa_supplicant ?S11auditd ? ? ? ?S25netfs ? ? ? ? ? ? S95atd
K35nmb ? ? ? ? ? K87restorecond ? ? S11portreserve ? S26acpid ? ? ? ? ? ? S99certmonger
K35smb ? ? ? ? ? K88sssd ? ? ? ? ? ?S12rsyslog ? ? ? S26haldaemon ? ? ? ? S99local
K36mysqld ? ? ? ?K89netconsole ? ? ?S13cpuspeed ? ? ?S26udev-post
K50dnsmasq ? ? ? K89rdisc ? ? ? ? ? S13irqbalance ? ?S27pcscd
K50kdump ? ? ? ? K92iptables ? ? ? ?S13rpcbind ? ? ? S28autofs
刪除這個服務腳本
chkconfig –del
[root@centos6 init.d]#chkconfig –list
NetworkManager 0:off 1:off 2:on 3:on 4:on 5:on 6:off
sysstat ? ? ? ? 0:off 1:on 2:on 3:on 4:on 5:on 6:off
testservice ? ? 0:off 1:off 2:off 3:on 4:off 5:on 6:off
udev-post ? ? ? 0:off 1:on 2:on 3:on 4:on 5:on 6:off
[root@centos6 init.d]#chkconfig –del testservice ? 從服務中刪除這個腳本,這個刪除只是刪除了/etc/rc5.d/中的K和S開頭的文件,
但是在/etc/init.d中的testservice并沒有刪除
[root@centos6 init.d]#chkconfig –list
sysstat ? ? ? ? 0:off 1:on 2:on 3:on 4:on 5:on 6:off
udev-post ? ? ? 0:off 1:on 2:on 3:on 4:on 5:on 6:off
vsftpd ? ? ? ? 0:off 1:off 2:off 3:off 4:off 5:off 6:off
在centos6及之前的版本,在/etc/rc(2-5).d中都有S99lacal,這個文件是最后執行,如果想開機啟動也可將命令或者腳本放到這個文件中
在centos7上這個文件沒有執行權限,如果想用要先加執行權限。
[root@centos6 init.d]#service –status-all ? 查看看所有的服務狀態
abrt-ccpp hook is installed
abrtd (pid ?2861) is running…
abrt-dump-oops is stopped
acpid (pid ?2589) is running…
非獨立服務:
xinetd管理的服務
? service 命令:手動管理服務
service 服務 start|stop|restart
service –status-all
? 瞬態(Transient)服務被xinetd進程所管理
進入的請求首先被xinetd代理
配置文件:/etc/xinetd.conf、/etc/xinetd.d/<service>
與libwrap.so文件鏈接
用chkconfig控制的服務:
chkconfig tftp on
在centos6及之前的版本:
安裝telnet service服務會自動安裝xinetd服務
xinetd服務是獨立服務但是telnet不是,telnet由xinetd來監聽
如果有人用telnet服務則喚醒telnet,否則telnet服務處于sleep狀態,
[root@centos6 ~]#service xinetd start
Starting xinetd: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [ ?OK ?]
[root@centos6 ~]#chkconfig –list
xinetd based services:
chargen-dgram: off
chargen-stream:off
daytime-dgram: off
daytime-stream:off
discard-dgram: off
discard-stream:off
echo-dgram: ? ?off
echo-stream: ? off
rsync: ? ? ? ? off
tcpmux-server: off
telnet: ? ? ? ?off
time-dgram: ? ?off
time-stream: ? off
[root@centos6 ~]#chkconfig –level 5 telnet on
[root@centos6 ~]#chkconfig –list
xinetd based services:
chargen-dgram: off
chargen-stream:off
daytime-dgram: off
daytime-stream:off
discard-dgram: off
discard-stream:off
echo-dgram: ? ?off
echo-stream: ? off
rsync: ? ? ? ? off
tcpmux-server: off
telnet: ? ? ? ?on
time-dgram: ? ?off
time-stream: ? off
[root@centos6 ~]#ss -ntlpe ? ? ? 無人訪問時由xinetd來監聽,一但有人訪問則喚醒telnet由telnet來建立連接
LISTEN ? ? ?0 ? ? ?64 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?:::23 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? :::* ? ? ?users:((“xinetd”,5874,5)) ino:28132 sk:ffff88007c2a5040
users:((“xinetd”,5874,5)) ino:28132 sk:ffff88007c2a5040
在centos7很多的服務都是非獨立服務,因為systemd來監聽所有服務。
[root@centos6 ~]#vim /etc/init/control-alt-delete.conf ? ? 注釋掉#exec /sbin/shutdown -r now “Control-Alt-Delete pressed”
防止誤操作重啟
# control-alt-delete – emergency keypress handling
#
# This task is run whenever the Control-Alt-Delete key combination is
# pressed. ?Usually used to shut down the machine.
#
# Do not edit this file directly. If you want to change the behaviour,
# please create a file control-alt-delete.override and put your changes there.
start on control-alt-delete
#exec /sbin/shutdown -r now “Control-Alt-Delete pressed”
啟動過程:
bois自檢,MBR grub 內核 通過grub讀取內核文件加載/分區,/sbin/init –> (/etc/inittab) –> 設置默認運行級別 –> 運行系統初始
腳本、完成系統初始化 –> (關閉對應下需要關閉的服務)啟動需要啟動服務 –,>設置終端登錄
? CentOS 6啟動流程:
POST –> Boot Sequence(BIOS) –> Boot Loader –> Kernel(ramdisk) –>
rootfs –> switchroot –> /sbin/init –>(/etc/inittab, /etc/init/*.conf) –> 設定默認
運行級別 –> 系統初始化腳本 rc.sysinit –> 關閉或啟動對應級別的服務 –> 啟動終端
grub legacy :
grub: GRand Unified Bootloader
grub 0.97: grub legacy
grub 2.x: grub2
grub legacy:
stage1: mbr
stage1_5: mbr之后的扇區,讓stage1中的bootloader能識別stage2所
在的分區上的文件系統
stage2:磁盤分區(/boot/grub/)
禁用selinux
centos7
[root@centos6 ~]#vim /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# ? ? enforcing – SELinux security policy is enforced.
# ? ? permissive – SELinux prints warnings instead of enforcing.
# ? ? disabled – No SELinux policy is loaded.
SELINUX=enforcing ? ? ? ? ? ? ? ? ?將enforcing ?改成disabled
# SELINUXTYPE= can take one of these two values:
# ? ? targeted – Targeted processes are protected,
# ? ? mls – Multi Level Security protection.
SELINUXTYPE=targeted
[root@centos6 ~]#hexdump -C /dev/sda -n 512 -v
00000000 ?eb 48 90 10 8e d0 bc 00 ?b0 b8 00 00 8e d8 8e c0 ?|.H…………..|
00000010 ?fb be 00 7c bf 00 06 b9 ?00 02 f3 a4 ea 21 06 00 ?|…|………!..|
如果dd if=/dev/sda of=/data/dd bs=1 count=512
sz /data/dd
刪除/dev/sda 第一扇區的446個字節
dd if=/dev/zero of=/dev/sda bs=1 count=446
reboot
發現直接進入光盤模式,因為系統發現硬盤無法引導
進入救援模式
chroot /mnt/sysimage
dd if=/data/dd of=/dev/sda bs=1 count=446
sync
sync
sync
reboot
grub安裝
? 安裝grub:
(1) grub-install
安裝grub stage1和stage1_5到/dev/DISK磁盤上,并復制GRUB相關文件
到 DIR/boot目錄下
grub-install –root-directory=DIR /dev/DISK
(2) grub
grub> root (hd#,#)
grub> setup (hd#)
用grub-install命令修復
dd if=/dev/zero of=/dev/sda bs=1 count=446
reboot
發現直接進入光盤模式,因為系統發現硬盤無法引導
進入救援模式
chroot /mnt/sysimage
grub-install
sync
sync
sync
exit
exit
reboot
用grub>root (hd0,0) 修復
dd if=/dev/zero of=/dev/sda bs=1 count=446
[root@centos6 ~]#dd if=/dev/zero of=/dev/sda bs=1 count=446
446+0 records in
446+0 records out
446 bytes (446 B) copied, 0.000583095 s, 765 kB/s
[root@centos6 ~]#hexdump -C /dev/sda -n 512 -v
00000000 ?00 00 00 00 00 00 00 00 ?00 00 00 00 00 00 00 00 ?|…………….|
00000010 ?00 00 00 00 00 00 00 00 ?00 00 00 00 00 00 00 00 ?|…………….|
00000020 ?00 00 00 00 00 00 00 00 ?00 00 00 00 00 00 00 00 ?|…………….|
00000030 ?00 00 00 00 00 00 00 00 ?00 00 00 00 00 00 00 00 ?|…………….|
00000040 ?00 00 00 00 00 00 00 00 ?00 00 00 00 00 00 00 00 ?|…………….|
00000050 ?00 00 00 00 00 00 00 00 ?00 00 00 00 00 00 00 00 ?|…………….|
[root@centos6 ~]#grub
Probing devices to guess BIOS drives. This may take a long time.
? ? GNU GRUB ?version 0.97 ?(640K lower / 3072K upper memory)
?[ Minimal BASH-like line editing is supported. ?For the first word, TAB
? ?lists possible command completions. ?Anywhere else TAB lists the possible
? ?completions of a device/filename.]
grub> root (hd0,0)
root (hd0,0)
?Filesystem type is ext2fs, partition type 0x83
grub> setup (hd0)
setup (hd0)
?Checking if “/boot/grub/stage1” exists… no
?Checking if “/grub/stage1” exists… yes
?Checking if “/grub/stage2” exists… yes
?Checking if “/grub/e2fs_stage1_5” exists… yes
?Running “embed /grub/e2fs_stage1_5 (hd0)”… ?27 sectors are embedded. ? ?grub1.5階段放在了mbr后面的27個扇區
succeeded
?Running “install /grub/stage1 (hd0) (hd0)1+27 p (hd0,0)/grub/stage2 /grub/grub.conf”… succeeded
Done.
grup 修復的時候依賴于/boot/grub/中的文件如果移走除了splash.xpm.gz和grub.conf ?的其他文件,不影響啟動但是無法再使用grub交互式的方式修復受損的啟動引導磁盤
grub-install命令不依賴上面的文件及時移走一樣能夠修復而且可以生成文件夾中移走的文件
破壞grub1.5階段也就是破壞mbr后面的27個扇區。
dd if=/dev/zero of=/dev/sda bs=1 count=10000 skip=512 seek=512
出現的故障是進入不了菜單,不是直接光盤引導,因為沒有破壞硬盤的512個字節
系統默認硬盤可以引導。
進入救援模式
chroot /mnt/sysimage
grub-install
sync
…
破壞了1.5階段后,用grub命令交互式修復后,如果再移走/boot/grub中的文件,則導致電腦無法啟動
修復方法
進入救援模式
chroot /mnt/sysimage
將移走的文件在拷回/boot/grub中
[root@centos6 ~]#cat /boot/grub/grub.conf ?grub.conf是grub在第二階段重要的配置文件
# grub.conf generated by anaconda
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE: ?You have a /boot partition. ?This means that
# ? ? ? ? ?all kernel and initrd paths are relative to /boot/, eg.
# ? ? ? ? ?root (hd0,0)
# ? ? ? ? ?kernel /vmlinuz-version ro root=/dev/sda2
# ? ? ? ? ?initrd /initrd-[generic-]version.img
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title CentOS 6 (2.6.32-696.el6.x86_64) ? ? ?引導系統的菜單項
root (hd0,0)
kernel /vmlinuz-2.6.32-696.el6.x86_64 ro root=UUID=408b65d7-7551-480b-8916-5eff4cca1b00 rd_NO_LUKS rd_NO_LVM LANG=en_US.UTF-8 rd_NO_MD SYSFONT=latarcyrheb-sun16 crashkernel=auto ?KEYBOARDTYPE=pc KEYTABLE=us rd_NO_DM rhgb quiet max_loop=100
initrd /initramfs-2.6.32-696.el6.x86_64.img
[root@centos6 ~]#vim /boot/grub/grub.conf
# grub.conf generated by anaconda
# i
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE: ?You have a /boot partition. ?This means that
# ? ? ? ? ?all kernel and initrd paths are relative to /boot/, eg.
# ? ? ? ? ?root (hd0,0)
# ? ? ? ? ?kernel /vmlinuz-version ro root=/dev/sda2
# ? ? ? ? ?initrd /initrd-[generic-]version.img
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title CentOS 6 (2.6.32-696.el6.x86_64)
? ? ? ? root (hd0,0)
? ? ? ? kernel /vmlinuz-2.6.32-696.el6.x86_64 ro root=UUID=408b65d7-7551-480b-8916-5eff4cca1b00 rd_NO_LUKS rd_NO_LVM LANG=en_US.UTF-8 rd_NO_MD SYSFONT=latarcyrheb-sun16 crashkernel=auto ?KEYBOARDTYPE=pc KEYTABLE=us rd_NO_DM rhgb quiet max_loop=100
? ? ? ? initrd /initramfs-2.6.32-696.el6.x86_64.img
title CentOS 100 (linux wang) ?復制上面的文件然后修改可以看到兩個啟動可選菜單
? ? ? ? kernel (hd0,0)/vmlinuz-2.6.32-696.el6.x86_64 找到主啟動文件后,找/然后以制度方式掛載ro root=UUID=408b65d7-7551-480b-8916-5eff4cca1b00其后會二次掛載二次掛載時就是rw模式掛載。
?rd_NO_LUKS rd_NO_LVM LANG=en_US.UTF-8 rd_NO_MD SYSFONT=latarcyrheb-sun16 crashkernel=auto ?KEYBOARDTYPE=pc KEYTABLE=us rd_NO_DM rhgb quiet max_loop=100
? ? ? ? initrd (hd0,0)/initramfs-2.6.32-696.el6.x86_64.img
[root@centos6 ~]#vim /boot/grub/grub.conf
# grub.conf generated by anaconda
# i
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE: ?You have a /boot partition. ?This means that
# ? ? ? ? ?all kernel and initrd paths are relative to /boot/, eg.
# ? ? ? ? ?root (hd0,0)
# ? ? ? ? ?kernel /vmlinuz-version ro root=/dev/sda2
# ? ? ? ? ?initrd /initrd-[generic-]version.img
#boot=/dev/sda
default=0 ? ?默認啟動centos6,0代表第一個title
timeout=5 ? ? 停滯5秒以供選擇
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu ? 默認隱藏,所以需要敲任意鍵才能顯示菜單。
title ? ? root (hd0,0)
? ? ? ? kernel /vmlinuz-2.6.32-696.el6.x86_64 ro root=UUID=408b65d7-7551-480b-8916-5eff4cca1b00 rd_NO_LUKS rd_NO_LVM LANG=en_US.UTF-8 rd_NO_MD SYSFONT=latarcyrheb-sun16 crashkernel=auto ?KEYBOARDTYPE=pc KEYTABLE=us rd_NO_DM rhgb quiet max_loop=100
? ? ? ? initrd /initramfs-2.6.32-696.el6.x86_64.img
? ? ? ? title CentOS 100 (linux wang)
? ? ? ? kernel (hd0,0)/vmlinuz-2.6.32-696.el6.x86_64 root=/dev/sda2 ? ? ? 這兩行的順序不能顛倒 ?必須 ? ? kernel在前initd在后。
? ? ? ? initrd (hd0,0)/initramfs-2.6.32-696.el6.x86_64.img
quiet 是否顯示內核啟動過程 ?rhgb啟動時是否是圖形界面
如果這kernel (hd0,0)/vmlinuz-2.6.32-696.el6.x86_64 root=/dev/sda2
? ? ? initrd (hd0,0)/initramfs-2.6.32-696.el6.x86_64.img
寫反了,那么重啟將失敗,修復方法e編輯d刪除o開啟新航e編輯:添加initrd/initramfs-2.6.32-696.el6.x86_64.img支持TAB鍵補全。然后按b重新啟動
這是臨時修改,等機器啟動起來后再去配置文件中將兩行的次序調整好。
[root@centos6 ~]#cp /boot/grub/splash.xpm.gz /data ?將splash.xpm.gz這個文件拷貝到/data下
[root@centos6 data]#ls
beifen ?f1 ?f3 ? ? ? ? ?loop8 ? ? ? mbr_bak ?raid ?sdb2 ?splash.xpm.gz ?TRANS.TBL
dd ? ? ?f2 ?install.sh ?mbr_backup ?mm ? ? ? sdb1 ?sdb3 ?src
[root@centos6 data]#gunzip splash.xpm.gz ? ?解壓
[root@centos6 data]#ls
beifen ?f1 ?f3 ? ? ? ? ?loop8 ? ? ? mbr_bak ?raid ?sdb2 ?splash.xpm ?TRANS.TBL
dd ? ? ?f2 ?install.sh ?mbr_backup ?mm ? ? ? sdb1 ?sdb3 ?src
這個文件就是一張黑色的圖片,就是選擇菜單的黑色背景。
畫圖打開一個圖片
重新設置圖片像素為640×480保存到桌面
然后將這個圖片傳到centos6中
yum install ImageMgick 在ImageMgick中有一個convert
convert -resize 640×480 -colors 14 793-160324161216.jpg win.xpm
gzip win.xpm
mv win.xpm.gz /boot/grub
? [root@centos6 ~]#vim /boot/grub/grub.conf
# grub.conf generated by anaconda
# i
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE: ?You have a /boot partition. ?This means that
# ? ? ? ? ?all kernel and initrd paths are relative to /boot/, eg.
# ? ? ? ? ?root (hd0,0)
# ? ? ? ? ?kernel /vmlinuz-version ro root=/dev/sda2
# ? ? ? ? ?initrd /initrd-[generic-]version.img
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/grub/win.xpm.gz
reboot
圖片更換完成
使破解口令難度加大:
在/boot/grub/grub.conf中加入新的hang
password wang
password –md5 $1$qgyKr/$DclcUQW7FKY1bq6uvDMA01
password –encrypted $6$Iq55.nVdKlhiv4J/$Ou5CTonH3wrPaTJoA4SPrBiip5LOjShgytg05sdDMOYQy1wHasVuWw9kdmaS.1kBOCtyD6Ng7LlIKxh7f3Y0I1
生成加密口令的命令:grub-md5-crypt
[root@centos6 ~]#grub-md5-crypt
Password:
Retype password:
$1$qgyKr/$DclcUQW7FKY1bq6uvDMA01
生成加密口令的命令:grub-crypt
[root@centos6 ~]#grub-crypt
Password:
Retype password:
$6$Iq55.nVdKlhiv4J/$Ou5CTonH3wrPaTJoA4SPrBiip5LOjShgytg05sdDMOYQy1wHasVuWw9kdmaS.1kBOCtyD6Ng7LlIKxh7f3Y0I1
數組
? 變量:存儲單個元素的內存空間
? 數組:存儲多個元素的連續的內存空間,相當于多個變量的集合
? 數組名和索引
索引:編號從0開始,屬于數值索引
注意:索引可支持使用自定義的格式,而不僅是數值格式,即為關聯索引,
bash4.0版本之后開始支持
bash的數組支持稀疏格式(索引不連續)連續數組中缺少了某些元數就是稀疏格式
? 聲明數組:
declare -a ARRAY_NAME
declare -A ARRAY_NAME: 關聯數組 ? ?關聯數組必須先聲明后使用。
注意:兩者不可相互轉換
[root@centos6 ~]#bash –version ? ?查看bash的版本
GNU bash, version 4.1.2(2)-release (x86_64-redhat-linux-gnu)
數組賦值
? 數組元素的賦值
(1) 一次只賦值一個元素
ARRAY_NAME[INDEX]=VALUE
weekdays[0]=”Sunday”
weekdays[4]=”Thursday”
(2) 一次賦值全部元素
ARRAY_NAME=(“VAL1” “VAL2” “VAL3” …)
(3) 只賦值特定元素
ARRAY_NAME=([0]=”VAL1″ [3]=”VAL2″ …)
(4) 交互式數組值對賦值
read -a ARRAY
? ?顯示所有數組:declare -a
[root@centos6 ~]#title[0]=ceo
[root@centos6 ~]#title[1]=cto
[root@centos6 ~]#title[2]=cfo
引用數組
? 引用數組元素:
${ARRAY_NAME[INDEX]}
注意:省略[INDEX]表示引用下標為0的元素
? 引用數組所有元素:
${ARRAY_NAME[*]}
${ARRAY_NAME[@]}
? 數組的長度(數組中元素的個數):
${#ARRAY_NAME[*]}
${#ARRAY_NAME[@]}
? 刪除數組中的某元素:導致稀疏格式
unset ARRAY[INDEX]
? 刪除整個數組:
unset ARRAY
[root@centos6 ~]#name=(wang lele liu) ? ? 一次賦多個數組值
[root@centos6 ~]#echo ${name[0]} ? ? ? ? ?引用數組
wang
[root@centos6 ~]#echo ${name[*]} ? ? ? ?顯示所有元數
wang lele liu
[root@centos6 ~]#echo $name ? 只能顯示第一個數組
wang
[root@centos6 ~]#echo ${name} 默認省略[0]
wang
[root@centos6 ~]#echo $name[1] ?顯示錯誤
wang[1]
[root@centos6 ~]#num=(`echo {1..10}`)
[root@centos6 ~]#echo ${num[*]}
1 2 3 4 5 6 7 8 9 10
[root@centos6 ~]#filename=(`ls /root/*.sh`)
[root@centos6 ~]#echo ${filename[0]}
/root/df.sh
[root@centos6 ~]#echo ${filename[1]}
/root/morejobs.sh
[root@centos6 ~]#echo ${filename[*]}
/root/df.sh /root/morejobs.sh /root/wang.sh
[root@centos6 ~]#num=(`seq 10`)
[root@centos6 ~]#echo ${num[*]}
1 2 3 4 5 6 7 8 9 10
[root@centos6 ~]#filename=(/boot/*)
[root@centos6 ~]#echo ${filename[0]}
/boot/config-2.6.32-696.el6.x86_64
[root@centos6 ~]#echo ${filename[1]}
/boot/efi
[root@centos6 ~]#echo ${filename[*]}
/boot/config-2.6.32-696.el6.x86_64 /boot/efi /boot/grub /boot/initramfs-2.6.32-696.el6.x86_64.img /boot/lost+found /boot/symvers-2.6.32-696.el6.x86_64.gz /boot/System.map-2.6.32-696.el6.x86_64 /boot/vmlinuz-2.6.32-696.el6.x86_64
[root@centos6 ~]#filename=(f{1,2,3}.{log,txt})
[root@centos6 ~]#echo ${filename[*]}
f1.log f1.txt f2.log f2.txt f3.log f3.txt
[root@centos6 ~]#name=([0]=wang [2]=zhang) ? ?稀疏格式
[root@centos6 ~]#echo ${name[1]}
[root@centos6 ~]#echo ${name[0]}
wang
[root@centos6 ~]#echo ${name[2]}
zhang
[root@centos6 ~]#echo ${name[*]}
wang zhang
[root@centos6 ~]#read -a title ? ? ? ?交互式為數組賦值
boss ceo cto beiguoxia
[root@centos6 ~]#echo ${title[0]}
boss
[root@centos6 ~]#echo ${title[1]}
ceo
[root@centos6 ~]#echo ${title[2]}
cto
[root@centos6 ~]#echo ${title[3]}
beiguoxia
[root@centos6 ~]#echo ${title[*]}
boss ceo cto beiguoxia
關聯數組必須先聲明要不然會出現下列錯誤
[root@centos6 ~]#title[ceo]=mage
[root@centos6 ~]#title[coo]=zhang
[root@centos6 ~]#echo ${title[ceo]}
zhang
[root@centos6 ~]#echo ${title[coo]}
zhang
[root@centos6 ~]#declare -A title
[root@centos6 ~]#title[ceo]=mage
[root@centos6 ~]#title[coo]=zhang
[root@centos6 ~]#echo ${title[ceo]}
mage
[root@centos6 ~]#echo ${title[coo]}
zhang
查看數組中有多少個元數
[root@centos6 ~]#echo ${#title[*]}
2
[root@centos6 ~]#echo ${#name[*]}
2
[root@centos6 ~]#echo ${#num[*]}
10
如果數組是連續的那么這個數組的最后一個下標是這個數組的個數減一
如果要加入一個新的元數那么這個元數的下標就是這個數組之前的個數
[root@centos6 ~]#echo ${name[*]}
a b c
[root@centos6 ~]#echo ${#name[*]}
3
[root@centos6 ~]#name[${#name[*]}]=x
[root@centos6 ~]#echo ${#name[*]}
4
[root@centos6 ~]#echo ${name[*]}
a b c x
[root@CENTOS7 ~]#vim max-min.sh ? ?比較10個隨機生成數的大小
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-11
#FileName: ? ? ? ? ? ? max-min.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
declare -a rand
for ((i=0;i<10;i++));do
? ? ? ? rand[$i]=$RANDOM
? ? ? ? if [ “$i” -eq 0 ];then
? ? ? ? ? ? ? ? max=${rand[$i]}
? ? ? ? ? ? ? ? min=$max
? ? ? ? else
? ? ? ? ? ? ? ? [ $max -lt ${rand[$i]} ] && { max=${rand[$i]} ;continue; }
? ? ? ? ? ? ? ? [ $min -gt ${rand[$i]} ]&& min=${rand[$i]}
? ? ? ? fi
done
echo $max
echo $min
echo ${rand[*]}
“max-min.sh” 25L, 614C written
[root@CENTOS7 ~]#./max-min.sh
28419
8710
24405 22016 16541 8710 28419 21459 24498 17134 17641 20700
? 生成10個隨機數保存于數組中,并找出其最大值和最小值
#!/bin/bash
declare -i min max
declare -a nums
for ((i=0;i<10;i++));do
nums[$i]=$RANDOM
[ $i -eq 0 ] && min=${nums[$i]} && max=${nums[$i]}&& continue
[ ${nums[$i]} -gt $max ] && max=${nums[$i]}
[ ${nums[$i]} -lt $min ] && min=${nums[$i]}
done
echo “All numbers are ${nums[*]}”
echo Max is $max
echo Min is $min
數組數據處理
? 引用數組中的元素:
數組切片:${ARRAY[@]:offset:number}
offset: 要跳過的元素個數
number: 要取出的元素個數
取偏移量之后的所有元素
${ARRAY[@]:offset}
? 向數組中追加元素:
ARRAY[${#ARRAY[*]}]=value
? 關聯數組:
declare -A ARRAY_NAME
ARRAY_NAME=([idx_name1]=’val1′ [idx_name2]=’val2‘…)
注意:關聯數組必須先聲明再調用
取分區利用率
[root@CENTOS7 ~]#vim fenqu.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-11
#FileName: ? ? ? ? ? ? fenqu.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
declare -A fenqu
df | grep “/dev/sd” > f1
while read i ; do
? ? ? ? a=`echo $i | cut -d ” ” -f 1`
? ? ? ? b=`echo $i | sed -r ‘s/.* ([0-9]+)%.*/\1/’`
? ? ? ? fenqu[$a]=$b
done < f1
echo ${fenqu[*]}
~
~
~
“fenqu.sh” 19L, 521C written
[root@CENTOS7 ~]#./fenqu.sh
16 1 8
示例
? 編寫腳本,定義一個數組,數組中的元素是/var/log目錄下所有以.log結尾的文件;統
計出其下標為偶數的文件中的行數之和
#!/bin/bash
#
declare -a files
files=(/var/log/*.log)
declare -i lines=0
for i in $(seq 0 $[${#files[*]}-1]); do
if [ $[$i%2] -eq 0 ];then
let lines+=$(wc -l ${files[$i]} | cut -d’ ‘ -f1)
fi
done
echo “Lines: $lines.”
[root@CENTOS7 ~]#vim shuzu.sh
#!/bin/bash
#
#********************************************************************
#Author: ? ? ? ? ? ? ? ?wangxiaochun
#QQ: ? ? ? ? ? ? ? ? ? ?29308620
#Date: ? ? ? ? ? ? ? ? ?2018-05-12
#FileName: ? ? ? ? ? ? shuzu.sh
#URL: ? ? ? ? ? ? ? ? ? http://www.magedu.com
#Description: ? ? ? ? ?The test script
#Copyright (C): ? ? ? ? 2018 All rights reserved
#********************************************************************
declare -a num
sum=0
num=(/var/log/*.log)
for i in `seq 0 $[${#num[*]}-1]`;do
? ? ? ? if [ $[$i%2] -eq 0 ];then
? ? ? ? let sum=sum+`wc -l ${num[$i]} | cut -d ” ” -f1`
? ? ? ? fi
done
echo $sum
~
~
“shuzu.sh” 20L, 517C written
[root@CENTOS7 ~]#bash shuzu.sh
1566
冒泡算法:a b c d e 比較大小
轉置矩陣: ? ? ? ? ? ? ? ? 123 ? ? ? ?147
num[00]=1
num[01]=2 ? ? ? ? ? ? ? ? ?456 ? ? ? ?258
num[02]=3 ? ? ? ? ? ? ? ? ?789 ? ? ? ?369
字符串切片
? ?${#var}:返回字符串變量var的長度
? ?${var:offset}:返回字符串變量var中從第offset個字符后(不包括第offset個字符)的字
符開始,到最后的部分,offset的取值在0 到 ${#var}-1 之間(bash4.2后,允許為負值)
? ?${var:offset:number}:返回字符串變量var中從第offset個字符后(不包括第offset個
字符)的字符開始,長度為number的部分
? ?${var: -length}:取字符串的最右側幾個字符
注意:冒號后必須有一空白字符
? ?${var:offset:-length}:從最左側跳過offset字符,一直向右取到距離最右側lengh個字
符之前的內容
? ?${var: -length:-offset}:先從最右側向左取到length個字符開始,再向右取到距離最
右側offset個字符之間的內容
注意:-length前空格
[root@CENTOS7 ~]#a=`echo {a..z} | tr -d ” “`
[root@CENTOS7 ~]#echo $a
abcdefghijklmnopqrstuvwxyz
[root@CENTOS7 ~]#echo ${#a}
26
[root@CENTOS7 ~]#echo ${a:4} ? ? ?:10跳過10個不包括第10個字符,
efghijklmnopqrstuvwxyz
[root@CENTOS7 ~]#echo ${a:4:2}
ef
[root@CENTOS7 ~]#echo ${a: -4} ? ?在:和-10之間有空格
wxyz
[root@CENTOS7 ~]#echo ${a:4: -4}
efghijklmnopqrstuv
[root@CENTOS7 ~]#echo ${a: -4:1}
w
[root@CENTOS7 ~]#echo ${a: -4:2}
wx
[root@CENTOS7 ~]#echo ${a: -4:-1} ? 在centos6上不支持
wxy
字符串處理
? 基于模式取子串
${var#*word}:其中word可以是指定的任意字符
功能:自左而右,查找var變量所存儲的字符串中,第一次出現的word, 刪
除字符串開頭至第一次出現word字符之間的所有字符
${var##*word}:同上,貪婪模式,不同的是,刪除的是字符串開頭至最后
一次由word指定的字符之間的所有內容
? 示例:
file=“var/log/messages”
${file#*/}: log/messages
${file##*/}: messages
[root@CENTOS7 ~]#line=`head -n1 /etc/passwd`
[root@CENTOS7 ~]#echo $line
root:x:0:0:root:/root:/bin/bash
[root@CENTOS7 ~]#echo ${line#*:}
x:0:0:root:/root:/bin/bash
[root@CENTOS7 ~]#echo ${line##*:}
/bin/bash
字符串處理
? ${var%word*}:其中word可以是指定的任意字符
功能:自右而左,查找var變量所存儲的字符串中,第一次出現的word, 刪
除字符串最后一個字符向左至第一次出現word字符之間的所有字符
file=”/var/log/messages”
${file%/*}: /var/log
? ${var%%word*}:同上,只不過刪除字符串最右側的字符向左至最后一次出現
word字符之間的所有字符;
? 示例:
url=http://www.magedu.com:80
${url##*:} ?80
${url%%:*} http
[root@CENTOS7 ~]#echo ${line%:*}
root:x:0:0:root:/root
[root@CENTOS7 ~]#echo ${line%%:*}
root
[root@CENTOS7 ~]#disk=”/dev/sda2 ? ? ? 52403200 4088408 ?48314792 ? 8% /”
[root@CENTOS7 ~]#echo $disk
/dev/sda2 52403200 4088408 48314792 8% /
[root@CENTOS7 ~]#echo ${disk%% *}
/dev/sda2
[root@CENTOS7 ~]#iptables -vnL ? ?查看防火墻是否關閉
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
?pkts bytes target ? ? prot opt in ? ? out ? ? source ? ? ? ? ? ? ? destination
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
?pkts bytes target ? ? prot opt in ? ? out ? ? source ? ? ? ? ? ? ? destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
?pkts bytes target ? ? prot opt in ? ? out ? ? source ? ? ? ? ? ? ? destination
[root@centos6 ~]#curl 172.20.109.255 ? ?訪問centos7上開啟的httpd服務
[root@CENTOS7 ~]#cat /var/log/httpd/access_log > f1
[root@CENTOS7 ~]#while read i ; do echo ${i%% *}; done < f1
172.20.102.175
172.20.68.110
172.20.68.110
字符串處理
? 查找替換
${var/pattern/substr}:查找var所表示的字符串中,第一次被pattern所匹
配到的字符串,以substr替換之
${var//pattern/substr}: 查找var所表示的字符串中,所有能被pattern所匹
配到的字符串,以substr替換之
${var/#pattern/substr}:查找var所表示的字符串中,行首被pattern所匹
配到的字符串,以substr替換之
${var/%pattern/substr}:查找var所表示的字符串中,行尾被pattern所匹
配到的字符串,以substr替換之
[root@CENTOS7 ~]#echo ${line}
root:x:0:0:root:/root:/bin/bash
[root@CENTOS7 ~]#echo ${line/:/;}
root;x:0:0:root:/root:/bin/bash
[root@CENTOS7 ~]#echo ${line//:/;}
root;x;0;0;root;/root;/bin/bash
[root@CENTOS7 ~]#echo ${line/#root/admin} ? ? 以root開頭的
admin:x:0:0:root:/root:/bin/bash
[root@CENTOS7 ~]#echo ${line/%bash/csh} ? ? ? 以bash結尾的
root:x:0:0:root:/root:/bin/csh
字符串處理
? 查找并刪除
${var/pattern}:刪除var所表示的字符串中第一次被pattern所匹配到的字符串
${var//pattern}:刪除var所表示的字符串中所有被pattern所匹配到的字符串
${var/#pattern}:刪除var所表示的字符串中所有以pattern為行首所匹配到的
字符串
${var/%pattern}:刪除var所表示的字符串中所有以pattern為行尾所匹配到的
字符串
? 字符大小寫轉換
${var^^}:把var中的所有小寫字母轉換為大寫
${var,,}:把var中的所有大寫字母轉換為小寫
[root@CENTOS7 ~]#echo ${line/root/}
:x:0:0:root:/root:/bin/bash
[root@CENTOS7 ~]#echo ${line//root/}
:x:0:0::/:/bin/bash
[root@CENTOS7 ~]#echo $a
root:x:0:0:root:/root:/bin/bash/root
[root@CENTOS7 ~]#echo ${a/#root}
:x:0:0:root:/root:/bin/bash/root
[root@CENTOS7 ~]#echo ${a/%root}
root:x:0:0:root:/root:/bin/bash/
[root@CENTOS7 ~]#echo ${a^^}
ROOT:X:0:0:ROOT:/ROOT:/BIN/BASH/ROOT
[root@CENTOS7 ~]#echo $b
ROOT:X:0:0:ROOT:/ROOT:/BIN/BASH/ROOT
[root@CENTOS7 ~]#echo ${b,,}
root:x:0:0:root:/root:/bin/bash/root
高級變量用法-有類型變量
? Shell變量一般是無類型的,但是bash Shell提供了declare和typeset兩個命令
用于指定變量的類型,兩個命令是等價的
? declare [選項] 變量名
-r 聲明或顯示只讀變量
-i 將變量定義為整型數
-a 將變量定義為數組
-A 將變量定義為關聯數組
-f 顯示已定義的所有函數名及其內容
-F 僅顯示已定義的所有函數名
-x 聲明或顯示環境變量和函數
-l 聲明變量為小寫字母 declare –l var=UPPER
-u 聲明變量為大寫字母 declare –u var=lower
[root@CENTOS7 ~]#declare -xf ? ?查看全局函數
[root@CENTOS7 ~]#a(){ echo wang; }
[root@CENTOS7 ~]#a
wang
[root@CENTOS7 ~]#export -f a
[root@CENTOS7 ~]#declare -f -x
a ()
{
? ? echo wang
}
declare -fx a
eval命令
? ?eval命令將會首先掃描命令行進行所有的置換,然后再執行該命令。該命令適用于
那些一次掃描無法實現其功能的變量.該命令對變量進行兩次掃描
? ?示例:
[root@server ~]# CMD=whoami
[root@server ~]# echo $CMD
whoami
[root@server ~]# eval $CMD
root
[root@server ~]# n=10
[root@server ~]# echo {0..$n}
{0..10}
[root@server ~]# eval echo {0..$n}
0 1 2 3 4 5 6 7 8 9 10
[root@CENTOS7 ~]#n=10
[root@CENTOS7 ~]#echo {1..$n}
{1..10}
[root@CENTOS7 ~]#eval echo {1..$n}
1 2 3 4 5 6 7 8 9 10
間接變量引用
? 如果第一個變量的值是第二個變量的名字,從第一個變量引用第二個變量的值
就稱為間接變量引用
? variable1的值是variable2,而variable2又是變量名,variable2的值為value,
間接變量引用是指通過variable1獲得變量值value的行為
variable1=variable2
variable2=value
[root@CENTOS7 ~]#cmd1=cmd2
[root@CENTOS7 ~]#echo $cmd1
cmd2
[root@CENTOS7 ~]#cmd2=wang
[root@CENTOS7 ~]#echo $cmd2
wang
[root@CENTOS7 ~]#eval echo \$$cmd1
wang
[root@CENTOS7 ~]#echo ${!cmd1}
wang
間接變量引用
? bash Shell提供了兩種格式實現間接變量引用
eval tempvar=\$$variable1
tempvar=${!variable1}
? 示例:
[root@server ~]# N=NAME
[root@server ~]# NAME=wangxiaochun
[root@server ~]# N1=${!N}
[root@server ~]# echo $N1
wangxiaochun
[root@server ~]# eval N2=\$$N
[root@server ~]# echo $N2
wangxiaochun
創建臨時文件
? mktemp命令:創建并顯示臨時文件,可避免沖突
? mktemp [OPTION]… [TEMPLATE]
TEMPLATE: filenameXXX
X至少要出現三個
? OPTION:
-d: 創建臨時目錄
-p DIR或–tmpdir=DIR:指明臨時文件所存放目錄位置
? 示例:
mktemp /tmp/testXXX
tmpdir=`mktemp –d /tmp/testdirXXX`
mktemp –tmpdir=/testdir testXXXXXX
[root@CENTOS7 ~]#mktemp /data/123XXX
/data/123onX
[root@CENTOS7 ~]#mktemp /data/123XXX
/data/1230T1
[root@CENTOS7 ~]#mktemp /data/123XXX
/data/123iS6
[root@CENTOS7 ~]#mktemp -d ?/data/nihaoXXX
/data/nihaozDc
[root@CENTOS7 ~]#a=/data
[root@CENTOS7 ~]#mktemp $a/123XXX
/data/1235J6
安裝復制文件
? install命令:
install [OPTION]… [-T] SOURCE DEST 單文件
install [OPTION]… SOURCE… DIRECTORY
install [OPTION]… -t DIRECTORY SOURCE…
install [OPTION]… -d DIRECTORY…創建空目錄
? 選項:
-m MODE,默認755
-o OWNER
-g GROUP
? 示例:
install -m 700 -o wang -g admins srcfile desfile
install –m 770 –d /testdir/installdir
[root@CENTOS7 ~]#install -m 770 -o wang -g root /etc/shadow /data/password.txt
[root@CENTOS7 ~]#ll /data/password.txt
-rwxrwx— 1 wang root 1932 May 12 11:16 /data/password.txt
[root@CENTOS7 ~]#install -d /data/123 -m 000
[root@CENTOS7 ~]#ll -d /data/123
d——— 2 root root 6 May 12 11:31 /data/123
[root@CENTOS7 ~]#mkdir /data/321 -m 000
[root@CENTOS7 ~]#ll -d /data/321
d——— 2 root root 6 May 12 11:31 /data/321
expect介紹
? expect 是由Don Libes基于Tcl( Tool Command Language )語言開發的,
主要應用于自動化交互式操作的場景,借助Expect處理交互的命令,可以將交互
過程如:ssh登錄,ftp登錄等寫在一個腳本上,使之自動化完成。尤其適用于需
要對多臺服務器執行相同操作的環境中,可以大大提高系統管理人員的工作效率
expect命令
? expect 語法:
expect [選項] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ]
? 選項
? ?-c:從命令行執行expect腳本,默認expect是交互地執行的
示例:expect -c ‘expect “\n” {send “pressed enter\n”}
? ?-d:可以輸出輸出調試信息
示例:expect -d ssh.exp
? ?expect中相關命令
? ?spawn:啟動新的進程
? ?send:用于向進程發送字符串
? ?expect:從進程接收字符串
? ?interact:允許用戶交互
? ?exp_continue 匹配多個字符串在執行動作后加此命令
[root@CENTOS7 ~]#expect
expect1.3> expect “hi” {send “you said hi\n”}
hi
you said hi
expect
? ?expect最常用的語法(tcl語言:模式-動作)
? ?單一分支模式語法:
? ?expect “hi” {send “You said hi\n”}
? ?匹配到hi后,會輸出“you said hi”,并換行
? ?多分支模式語法:
expect “hi” { send “You said hi\n” } \
“hehe” { send “Hehe yourself\n” } \
“bye” { send “Good bye\n” }
? ?匹配hi,hello,bye任意字符串時,執行相應輸出。等同如下:
expect {
“hi” { send “You said hi\n”}
“hehe” { send “Hehe yourself\n”}
“bye” { send “Good bye\n”}
}
[root@CENTOS7 ~]#expect
expect1.1> expect “hi” {send “you said hi\n”}
hi
you said hi
expect1.2> expect “hi” {send “you said hi\n”} \
+> “hehe” {send “hehe yourself\n”} \
+> “bey” {send “good bye\n”}
hey
bey
good bye
[root@CENTOS7 ~]#expect
expect1.1> expect {
+> “hi” {send “you said hi\n”}
+> “hehe” {send “hehe nimei\n”}
+> “bye” {send “good bye\n”}
+> }
hehe
hehe nimei
示例
#!/usr/bin/expect
spawn scp /etc/fstab 192.168.8.100:/app
expect {
“yes/no” { send “yes\n”;exp_continue }
“password” { send “magedu\n” }
}
expect eof
[root@CENTOS7 ~]#vim scp.exp
#!/usr/bin/expect
spawn scp /etc/fstab 192.168.30.102:/data
expect {
“yes/no” { send “yes\n”;exp_continue }
“password” { send “magedu\n” }
}
expect eof
spawn scp /etc/fstab 192.168.30.102:/data
The authenticity of host ‘192.168.30.102 (192.168.30.102)’ can’t be established.
RSA key fingerprint is SHA256:PRXpd893BtvDDcy5yeFh/MVuBjM7LPWwz0JH9Zs+Ia4.
RSA key fingerprint is MD5:08:44:ca:54:1c:a9:20:64:42:40:59:cc:98:be:bd:bc.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘192.168.30.102’ (RSA) to the list of known hosts.
root@192.168.30.102’s password:
fstab ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 100% ?595 ? 795.0KB/s ? 00:00
如果用ssh連接別的主機半天連接不上則可有可能是
[root@CENTOS7 ~]#vim /etc/ssh/sshd_config
SSAPIAuthentication yes ? ?將這項修改成no 79行
#UseDNS no ? 修改成 ? ?UseDNS no 115行
[root@CENTOS7 ~]#systemctl restart sshd ? 從新生效一下
自動ssh連接登錄
[root@CENTOS7 ~]#vim ssh2.exp
#!/usr/bin/expect
spawn ssh 192.168.30.102
expect {
? ? ? ? “yes/no” { send “yes\n” exp_continue }
? ? ? ? “password” { send “magedu\n” }
}
interact ? ? 這個地方一定要寫interact如果寫成expect eof 則無法繼續后續的命令
示例
#!/usr/bin/expect
spawn ssh 192.168.8.100
expect {
“yes/no” { send “yes\n”;exp_continue }
“password” { send “magedu\n” }
}
interact
#expect eof
示例:變量
#!/usr/bin/expect
set ip 192.168.8.100 ? ?在expect中變量賦值需要set
set user root
set password magedu
set timeout 10
spawn ssh $user@$ip
expect {
“yes/no” { send “yes\n”;exp_continue }
“password” { send “$password\n” }
}
interact
示例:位置參數
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh $user@$ip
expect {
“yes/no” { send “yes\n”;exp_continue }
“password” { send “$password\n” }
}
interact
#./ssh3.exp 192.168.8.100 root magedu
示例:執行多個命令
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set timeout 10
spawn ssh $user@$ip
expect {
“yes/no” { send “yes\n”;exp_continue }
“password” { send “$password\n” }
}
expect “]#” { send “useradd haha\n” }
expect “]#” { send “echo magedu |passwd –stdin haha\n” }
send “exit\n”
expect eof
#./ssh4.exp 192.168.8.100 root magedu
示例:shell腳本調用expect
#!/bin/bash
ip=$1
user=$2
password=$3
expect <<EOF
set timeout 10
spawn ssh $user@$ip
expect {
“yes/no” { send “yes\n”;exp_continue }
“password” { send “$password\n” }
}
expect “]#” { send “useradd hehe\n” }
expect “]#” { send “echo magedu |passwd –stdin hehe\n” }
expect “]#” { send “exit\n” }
expect eof
EOF
#./ssh5.sh 192.168.8.100 root magedu
[root@CENTOS7 ~]#vim scp2.exp
#!/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
spawn scp /etc/passwd $user@$ip:/data
expect {
? ? ? ? “yes/no” { send “yes\n”; exp_continue }
? ? ? ? “password” { send “$passwd\n” }
}
expect eof
[root@CENTOS7 ~]#vim scp1.sh
#!/bin/bash
user=root
passwd=magedu
while read ip ;do
? ? ? ? /root/scp2.exp $ip ?$user $passwd
done < f121
centos6 啟動流程
1 post 硬件環境
2 mbr 446 grub stage1
3 grub stage1.5 加載/boot 分區文件系統
4 grub stage2 /boot/grub/grub.conf
5 vmlinuz 加載/ /boot/initramfs.xxx.img
6 /sbin/init ?/etc/inittab id:3:
7 rc.sysinit
8 /etc/rc3.d/S,Kxxx –> /etc/init.d/xxx
chkconfig –level N service on|off
9 /etc/rc.local
10 login
刪除/boot/下的所有文件,恢復過程
第一種方法
1.進入救援模式
2.chroot /mnt/sysimage
3.mount /dev/sr0 /mnt
4.cp /mnt/isolinux/vmlinuz /boot/vmlinuz-`uname -r`
5.mkinitrd initramfs-`uname -r`.x86_64.img `uname -r`
6.grub-install /dev/sda
7.vi grub.conf
default=0
timeout=5
titel wanglinux
root (hd0,0)
kernel /vmlinuz-`uname -r` root=/dev/sda2 rhgb quiet
initrd /initramfs-`uname -r`x86_64
第二種方法
1.進入救援模式
2.mount /mnt/cdroom
3.rpm -ivh /mnt/cdroom/Packages/kernel-2.6.32-696.e16.x86_64.rpm –root=/mnt/sysimage/ –forc
4.chroot /mnt/sysimage
5.grub-install
6.vim /boot/grub/grub.conf
default=0
timeout=5
titel linux wang
kernel /用:r!ls /boot/vmlinuz按Tab補全 ? ? ? ? ? ? ?root=/dev/sda2 可以在此加selinux=0,禁用selinux
initrd /用:r!ls /boot/initramfs按Tab補全
如果/boot不是一個獨立分區
那么
kernel / ? ? ? ? ? ? ? ? ? ? ? ? ?kernel /boot/
initrd /,這兩行不能這么寫,要寫成initrd /boot/
刪除/etc/fstab,同時清空/boot/下的所有文件。如何修復
1.進入救援模式
2.fdisk -l查看分區
3.mkdir /mnt/rootfs
4.mount /dev/sda1 /mnt/rootfs 從/dev/sda1開始嘗試找到/
5.ls
umount /mnt/rootfs
6.mount /dev/sda2 /mnt/rootfs
看一下/分區的文件系統blkid
7.vi /mnt/rootfs/etc/fstab
/dev/sda2 / ext4 defaults 0 0
/dev/sda1 /boot ext4 defualts 0 0
/dev/sda5 swap swap defaults 0 0
/dev/sda3 /data ext4 defaults 0 0
exit
reboot
重新進入救援模式
1.進入救援模式
2.重復上述修復/boot操作
磁盤是邏輯卷如何恢復
如果是邏輯卷進入救援模式后要先啟動邏輯卷
lvchange -ay
就可以掛載了
如果破壞init文件如何修復
1.進入救援模式,開啟網絡服務并配置地址
2.在都是centos6上的機器上遠程拷貝一份
chroot /mnt/sysimage ?切/
3.scp 192.168.30.105(能開啟的centos6的ip地址):/sbin/init /sbin/
exit
reboot
第二種方法
1.進入救援模式
chroot /mnt/sysimage
2.rpm2cpio /misc/cd/Packages/upstart-0.65-el6.x86_64.rpm | cpio -idv ./sbininit
cp ./sbin/init /sbin/
自制一個小linux
自制linux系統
? 分區并創建文件系統
fdisk /dev/sdb
分兩個必要的分區
/dev/sdb1對應/boot /dev/sdb2對應根 /
mkfs.ext4 /dev/sdb1
mkfs.ext4 /dev/sdb2
? 掛載boot
mkdir /mnt/boot 子目錄必須為boot
mount /dev/sdb1 /mnt/boot
? 安裝grub
grub-install –root-directory=/mnt /dev/sdb
自制一個小linux
1.
添加一塊新的硬盤20G(移動硬盤,U盤都可以)dev/sdb
2.
fdisk /dev/sdb分兩個主分區
3.
mkfs.ext4 /dev/sdb1
mkfs.ext4 /dev/sdb2
4.
mkdir /mnt/boot ? ? ?子目錄必須是boot
mkdir /mnt/rootfs
mount /dev/sdb1 /mnt/boot
grub-install –root-directory=/mnt /dev/sdb ?–root-directory=/ ? 這個命令默認是boot的父文件夾
cp /boot/vmlinuz-2.6.32-642.el6.x86_64 /mnt/boot/vmlinuz
cp /boot/initramfs-2.6.32-642.el6.x86_64.img /mnt/boot/initramfs.img
cat > /mnt/boot/grub/grub.conf
default=0
timeout=5
title linux wang
blkid
kernel /vmlinuz root=/dev/sda2(root=UUID=) init=/bin/bash selinux=0,自動擁有IP地址,創建一個軟連接讓/sbin/init→一個bash腳本,腳本中寫著/bin/bash,insmod /lib/e1000.ko ifconfig etho 192.168.30.16/24
initrd /initramfs.img
mount /dev/sdb2 /mnt/rootfs
運行 cmd_copy.sh
ifconfig,insmod,ping,mount,ls,cat,df,lsblk,blkid
mkdir /mnt/rootfs/{dev,etc,proc,sys,usr,bin,sbin,var,lib,boot,mnt,home,root,emp}
cp /lib/modules/3.10.0-693.el7.x86_64/kernel/drivers/net/ethernet/intel/e1000/e1000.ko.xz /mnt/rootfs/lib/
sync
sync
sync
拆掉硬盤(移動硬盤,U盤)
自制linux系統
? 分區并創建文件系統
fdisk /dev/sdb
分兩個必要的分區
/dev/sdb1對應/boot /dev/sdb2對應根 /
mkfs.ext4 /dev/sdb1
mkfs.ext4 /dev/sdb2
? 掛載boot
mkdir /mnt/boot 子目錄必須為boot
mount /dev/sdb1 /mnt/boot
? 安裝grub
grub-install –root-directory=/mnt /dev/sdb
自制linux系統
? ?恢復內核和initramfs文件
cp /boot/vmlinuz-2.6.32-642.el6.x86_64 /mnt/boot/
cp /boot/initramfs-2.6.32-642.el6.x86_64.img /mnt/boot
? ?建立grub.conf
vim /mnt/boot/grub.conf
title wanglinux
root (hd0,0)
kernel /vmlinuz-2.6.32-642.el6.x86_64 root=/dev/sda2 selinux=0
init=/bin/bash
initrd /initramfs-2.6.32-642.el6.x86_64.img
? ?chroot /mnt/sysroot
自制linux系統
? 創建一級目錄
mkdir /mnt/sysroot
mount /dev/sdb2 /mnt/sysroot
mkdir –pv
/mnt/sysroot/{etc,lib,lib64,bin,sbin,tmp,var,usr,sys,proc,opt,home,root,boot,
dev,mnt,media}
? ?復制bash和相關庫文件
? ?復制相關命令及相關庫文件
如:ifconfig,insmod,ping,mount,ls,cat,df,lsblk,blkid等
救援環境
? 在根文件系統無法使用時需要,如/bin/mount刪除
? 對系統沒有特殊要求
? 從光盤引導(boot.iso或者安裝光盤#1)
? 從USB盤(由boot.iso制作)引導
系統配置文件丟失修復
? 系統在引導期間,很重要的一個過程就是init進程讀取其配置文件/etc/inittab,
啟動系統基本服務程序及默認運行級別的服務程序完成系統引導,如果
/etc/inittab誤刪除或修改錯誤,Linux將無法正常啟動。此時,只有通過救援模
式才可以解決此類問題。
? 有備份文件的回復方法
? 沒有備份文件的恢復辦法
系統配置文件丟失修復
? 有備份文件的恢復辦法:
進入救援模式,執行chroot命令后,如果有此文件的備份(強烈建議系統中的重要
數據目錄,如/etc、/boot等要進行備份),直接將備份文件拷貝回去,退出重啟即
可。如果是配置文件修改錯誤,如比較典型的/boot/grub/grub.conf及
/etc/passwd的文件修改錯誤,也可以直接修正恢復。假設有備份文件
/etc/inittab.bak,則在救援模式下執行:
chroot /mnt/sysimage
cp /etc/inittab.bak /etc/inittab
系統配置文件丟失修復
? 沒有備份文件的恢復辦法
如果一些配置文件丟失或軟件誤刪除,且無備份,可以通過重新安裝軟件包來恢復,
首先查找到/etc/inittab屬于哪一個RPM包
chroot /mnt/sysimage
rpm -qf /etc/inittab
initscripts-9.03.49-1.el6.centos.x86_64
exit 退出chroot模式
掛載存放RPM包的安裝光盤(在救援模式下,光盤通常掛載在/mnt/source目錄下)
系統配置文件丟失修復
mount /dev/sr0 /mnt/source
CentOS6系統的RPM包存放在光盤Package目錄下,要修復的硬盤系統的根目
錄在/mnt/sysimage下,需要使用–root選項指定其位置。覆蓋安裝/etc/inittab
文件所在的RPM包:
rpm -ivh –replacepkgs | force /mnt/source/Packages/
initscripts-9.03.49-1.el6.centos.x86_64.rpm
其中的rpm命令選項“–replacepkgs”表示覆蓋安裝,執行完成后,即已經恢復
了此文件
系統配置文件丟失修復
如果想只提取RPM包中的/etc/inittab文件進行恢復,可以在進入救援模式后,執
行命令:
rpm2cpio /mnt/source/Packages/initscripts-9.03.49-
1.el6.centos.x86_64.rpm| cpio -idv ./etc/inittab
cp etc/inittab /mnt/sysimage/etc
注意此命令執行時不能將文件直接恢復至/etc目錄,只能提取到當前目錄下,且恢
復的文件名稱所在路徑要寫完整的路徑。提取文件成功后,將其復制到根分區所在
的/mnt/sysimage目錄下相應位置即可
/proc目錄
? /proc目錄:
內核把自己內部狀態信息及統計信息,以及可配置參數通
過proc偽文件系統加以輸出
? 參數:只讀:輸出信息
可寫:可接受用戶指定“新值”來實現對內核某功
能或特性的配置
? /proc/sys
(1) sysctl命令用于查看或設定此目錄中諸多參數
sysctl -w path.to.parameter=VALUE
sysctl -w kernel.hostname=mail.magedu.com
(2) echo命令通過重定向方式也可以修改大多數參數的值
echo “VALUE” > /proc/sys/path/to/parameter
echo “websrv” > /proc/sys/kernel/hostname
[root@CENTOS7 ~]#cat /proc/sys/net/ipv4/ip_forward
0
[root@CENTOS7 ~]#cat /proc/sys/net/ipv4/ip_default_ttl
64
禁ping
[root@centos6 ~]#cat /proc/sys/net/ipv4/icmp_echo_ignore_all
0
這些文件都可以由/etc/sysctl.conf文件來配置
[root@centos6 ~]#vim /etc/sysctl.conf
# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values, 0 is disabled, 1 is enabled. ?See sysctl(8) and
# sysctl.conf(5) for more details.
#
# Use ‘/sbin/sysctl -a’ to list all possible parameters.
# Controls IP packet forwarding
net.ipv4.ip_forward = 1
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
[root@centos6 ~]#cat /proc/sys/net/ipv4/ip_forward ? 雖然修改了文件的ip_farword 的值,但是文件并沒有生效,
0
讓文件生效的命令是sysctl -p ? 讓系統重讀這個文件
[root@centos6 ~]#sysctl -p
net.ipv4.ip_forward = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
[root@centos6 ~]#cat /proc/sys/net/ipv4/ip_forward
1
[root@centos6 ~]#cat /etc/sysctl.conf
# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values, 0 is disabled, 1 is enabled. ?See sysctl(8) and
# sysctl.conf(5) for more details.
#
# Use ‘/sbin/sysctl -a’ to list all possible parameters.
# Controls IP packet forwarding
net.ipv4.ip_forward = 1 ? ? ? 機器是否能當路由使用
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0
# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0
# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1
# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1
# Controls the default maxmimum size of a mesage queue
kernel.msgmnb = 65536
# Controls the maximum size of a message, in bytes
kernel.msgmax = 65536
# Controls the maximum shared segment size, in bytes ?共享內存的斷大小,60多G
kernel.shmmax = 68719476736 ? ? ? ? ? 將來使用oracle數據庫希望使用更大的內存,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?要將這個數調大
# Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296
查看所有內存參數
sysctl -a
[root@centos6 ~]#sysctl -a
net.ipv4.tcp_syn_retries = 5 ? ? ?嘗試連接5次
net.ipv4.tcp_synack_retries = 5
net.ipv4.tcp_fin_timeout = 60 ? 分手超時時間60秒
net.ipv4.tcp_syncookies = 1 ? ? cookies可以存放一些用戶信息
net.ipv4.tcp_max_tw_buckets = 131072 ? ? timeout能夠保留這個狀態的個數
net.ipv4.tcp_max_syn_backlog = 1024 ? ? ?最多等待隊列
net.ipv4.tcp_max_orphans = 131072 ? ? ? ? 最大孤兒連接數
net.ipv4.ip_local_port_range = 32768 60999 ? 客戶端端口個數(反向代理服務器)
[root@centos6 ~]#sysctl -a | grep icmp
net.netfilter.nf_conntrack_icmpv6_timeout = 30
net.ipv4.icmp_echo_ignore_all = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.icmp_errors_use_inbound_ifaddr = 0
net.ipv4.icmp_ratelimit = 1000
net.ipv4.icmp_ratemask = 6168
net.ipv6.icmp.ratelimit = 1000
[root@centos6 ~]#vim /etc/sysctl.conf
# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values, 0 is disabled, 1 is enabled. ?See sysctl(8) and
# sysctl.conf(5) for more details.
#
# Use ‘/sbin/sysctl -a’ to list all possible parameters.
# Controls IP packet forwarding
net.ipv4.ip_forward = 1
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
net.ipv4.icmp_echo_ignore_all = 1 ? ? ? ?在這加上行禁ping
在文件生效之前可以ping通
sysctl -p
則無法ping通
這是刪除/etc/sysctl.conf這個文件中加入的net.ipv4.icmp_echo_ignore_all = 1還是無法ping通
sysctl -p 之后也無法ping通
因為sysctl -p是重讀次文件,只有文件中與內存中不相符的文件才修改內存,已將刪除了這個文件,那么內存中是什么就是什么不會修改
[root@centos6 ~]#sysctl -w net.ipv4.icmp_echo_ignore_all=0 ?這個也是修改內存,但是存不住。
net.ipv4.icmp_echo_ignore_all = 0
sysctl命令
? ?sysctl命令:
默認配置文件:/etc/sysctl.conf
(1) 設置某參數
sysctl -w parameter=VALUE
(2) 通過讀取配置文件設置參數
sysctl -p [/path/to/conf_file]
(3) 查看所有生效參數
sysctl -a
? ?常用的幾個參數:
net.ipv4.ip_forward
net.ipv4.icmp_echo_ignore_all
vm.drop_caches
[root@centos6 ~]#time ls ? ? 查看命令所用時間
123 ? ? ? ? ? ? ? ? ? anaconda-ks.cfg ?install.log ? ? ? ? p2 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?src
2018 ? ? ? ? ? ? ? ? ?bin ? ? ? ? ? ? ?install.log.syslog ?Pictures ? ? ? ? ? ? ? ? ? ? ? ?Templates
20180417 ? ? ? ? ? ? ?Desktop ? ? ? ? ?morejobs.sh ? ? ? ? Public ? ? ? ? ? ? ? ? ? ? ? ? ?usr
20180417-+09:58:22 ? ?df.sh ? ? ? ? ? ?Music ? ? ? ? ? ? ? [root@centos6 ? ? ? ? ? ? ? ? ? Videos
20180417-09:58:32 ? ? Documents ? ? ? ?nohup.out ? ? ? ? ? samba-3.6.23-41.el6.x86_64.rpm ?vsftpd-3.0.2-22.el7.x86_64.rpm
793-160324161216.jpg ?Downloads ? ? ? ?p1 ? ? ? ? ? ? ? ? ?scp2.ecp ? ? ? ? ? ? ? ? ? ? ? ?wang.sh
real 0m0.002s
user 0m0.001s
sys 0m0.001s
[root@centos6 ~]#sysctl -w vm.drop_caches=1 ? ?清理緩存
/sys目錄
? /sys目錄:
sysfs:為用戶使用的偽文件系統,輸出內核識別出的各硬件設備的相關屬
性信息,也有內核對硬件特性的設定信息;有些參數是可以修改的,用于調整硬件
工作特性
udev通過此路徑下輸出的信息動態為各設備創建所需要設備文件,udev是
運行用戶空間程序
專用工具:udevadmin, hotplug
udev為設備創建設備文件時,會讀取其事先定義好的規則文件,一般在
/etc/udev/rules.d及/usr/lib/udev/rules.d目錄下
內核編譯
? 單內核體系設計、但充分借鑒了微內核設計體系的優點,為內核引入模塊化機
制
? 內核組成部分:
kernel: 內核核心,一般為bzImage,通常在/boot目錄下,名稱為
vmlinuz-VERSION-RELEASE
kernel object: 內核對象,一般放置于
/lib/modules/VERSION-RELEASE/
[ ]: N
[M]: M
[*]: Y
輔助文件:ramdisk
initrd
initramfs
內核版本
? 運行中的內核:
uname命令:
uname – print system information
uname [OPTION]…
-n: 顯示節點名稱
-r: 顯示VERSION-RELEASE
-a:顯示所有信息
[root@centos6 ~]#uname -r ? 內核版本
2.6.32-696.el6.x86_64
內核模塊命令
? lsmod命令:
顯示由核心已經裝載的內核模塊
顯示的內容來自于: /proc/modules文件
? modinfo命令:
顯示模塊的詳細描述信息
modinfo [ -k kernel ] [ modulename|filename… ]
-n: 只顯示模塊文件路徑
-p: 顯示模塊參數
-a: author
-d: description
-l: license
lsmod |grep xfs;modinfo xfs
編譯內核和編譯普通軟件不同的地方就是你要告訴系統那些功能是啟用的,那些功能
是不啟用的,由于太多,因此我們編譯內核的時候可以參照已經編譯好的文件。
[root@centos6 ~]#cd /boot
[root@centos6 boot]#ls
vmlinuz-2.6.32-696.el6.x86_64 ?這個文件中存放著最基本得功能。
一些可用可不用的功能,沒必要放到內核中,因此放到一個獨立的文件中,需要使用就加載到內存中。
比如這個文件[root@CENTOS7 ~]#locate xfs.ko
/usr/lib/modules/3.10.0-693.el7.x86_64/kernel/fs/xfs/xfs.ko.xz
這些功能模塊放在哪在下面這個文件中定義
config-2.6.32-696.el6.x86_64
[root@CENTOS7 ~]#less /boot/config-3.10.0-693.el7.x86_64
#
# Automatically generated file; DO NOT EDIT.
# Linux/x86_64 3.10.0-693.el7.x86_64 Kernel Configuration
#
CONFIG_64BIT=y ? ? ?y代表著打到內核里
CONFIG_X86_64=y
CONFIG_OPROFILE=m ? m表示放到單獨文件中
CONFIG_GCOV_KERNEL is not set ? ? 不啟用
[root@CENTOS7 ~]#wc -l /boot/config-3.10.0-693.el7.x86_64 ? 這個文件的行數
5976 /boot/config-3.10.0-693.el7.x86_64
內核模塊管理
? modprobe命令:
裝載或卸載內核模塊
? modprobe [ -C config-file ] [ modulename ] [ module parame-ters… ]
? 配置文件:/etc/modprobe.conf, /etc/modprobe.d/*.conf
? modprobe [ -r ] modulename…
內核模塊管理
? depmod命令:
內核模塊依賴關系文件及系統信息映射文件的生成工具
? 裝載或卸載內核模塊:
? insmod命令:指定模塊文件,不自動解決依賴模塊
insmod [ filename ] [ module options… ]
insmod `modinfo –n exportfs`
lnsmod `modinfo –n xfs`
? rmmod命令:卸載模塊
rmmod [ modulename ]
rmmod xfs
rmmod exportfs
編譯內核
? 前提:
(1) 準備好開發環境
(2) 獲取目標主機上硬件設備的相關信息
(3) 獲取目標主機系統功能的相關信息
例如:需要啟用相應的文件系統
(4) 獲取內核源代碼包
www.kernel.org
開發環境準備
? 包組(CentOS 6):
Server Platform Development
Development Tools
? 目標主機硬件設備相關信息:
CPU:
cat /proc/cpuinfo
x86info -a
lscpu
硬件設備
? PCI設備:
lspci
-v
-vv
lsusb
-v
-vv
lsblk 塊設備
? 了解全部硬件設備信息
hal-device:CentOS6
內核編譯安裝系統
? 安裝開發包組
? 下載源碼文件
? .config:準備文本配置文件
? make menuconfig:配置內核選項
? make [-j #]
? make modules_install:安裝模塊
? make install :安裝內核相關文件
安裝bzImage為/boot/vmlinuz-VERSION-RELEASE
生成initramfs文件
編輯grub的配置文件
編譯安裝內核示例
? tar xf linux-3.10.67.tar.xz -C /usr/src
? cd /usr/src
? ln -sv linux-3.10.67 linux
? cd /usr/src/linux
? cp /boot/config-$(uname -r) ./.config
? make help
? make menuconfig
? make -j 2
? make modules_install
? make install
? reboot
編譯內核
? (1) 配置內核選項
支持“更新”模式進行配置:make help
(a) make config:基于命令行以遍歷的方式去配置內核中可配置的每個選
項
(b) make menuconfig:基于curses的文本窗口界面
(c) make gconfig:基于GTK (GNOME)環境窗口界面
(d) make xconfig:基于QT(KDE)環境的窗口界面
支持“全新配置”模式進行配置
(a) make defconfig:基于內核為目標平臺提供的“默認”配置進行配置
(b) make allyesconfig: 所有選項均回答為“yes“
(c) make allnoconfig: 所有選項均回答為“no“
編譯內核
? (2) 編譯
? 全編譯:make [-j #]
? 編譯內核的一部分功能:
(a) 只編譯某子目錄中的相關代碼
cd /usr/src/linux
make dir/
(b) 只編譯一個特定的模塊
cd /usr/src/linux
make dir/file.ko
例如:只為e1000編譯驅動:
make drivers/net/ethernet/intel/e1000/e1000.ko
編譯內核
? 如何交叉編譯內核:
編譯的目標平臺與當前平臺不相同
make ARCH=arch_name
? 要獲取特定目標平臺的使用幫助
make ARCH=arch_name help
make ARCH=arm help
內核編譯
? 在已經執行過編譯操作的內核源碼樹做重新編譯
? 需要事先清理操作:
make clean:清理大多數編譯生成的文件,但會保留config文件等
make mrproper: 清理所有編譯生成的文件、config及某些備份文件
make distclean:mrproper、patches以及編輯器備份文件
卸載內核
? 刪除/lib/modules/目錄下不需要的內核庫文件
? 刪除/usr/src/linux/目錄下不需要的內核源碼
? 刪除/boot目錄下啟動的內核和內核映像文件
? 更改grub的配置文件,刪除不需要的內核啟動列表
編譯安裝linux內核文件
1.下載新的內核版本
傳到linux中
sz
2.解壓縮
tar xvf linux-4.16.8.tar.xz
3.cp /boot/config-3.10.0-693-e17.x86_64 .config
yum groupinstall “development tools”
yum install ncurses-decel
make menuconfig ? ?選擇想要啟動的功能
general setup
Local version ? ? ?回車 添加1.0wanglinux
?file system
make -j 4
4.make modules_install:安裝模塊 ? ? 生成模塊文件,將模塊文件拷貝到相應/lib/目錄下.
? make install :安裝內核相關文件
? 安裝bzImage為/boot/vmlinuz-VERSION-RELEASE
生成initramfs文件
編輯grub的配置文件
systemd
? POST –> Boot Sequence –> Bootloader –> kernel + initramfs(initrd) —
> rootfs –> /sbin/init ? ?第一個進程就找init是因為源碼init文件夾中main.c中寫的try_to_run_init_process(“/sbin/init”)
init: ?CentOS 5: SysV init ? ?串行啟動
CentOS 6: Upstart ?部分并行
CentOS 7: Systemd ?全部并行啟動
? Systemd:系統啟動和服務器守護進程管理器,負責在系統啟動或運行時,激
活系統資源,服務器進程和其它進程
? Systemd新特性:
系統引導時實現服務并行啟動
按需啟動守護進程 ? ? ? 代替超級守護(xinetd)管理進程,系統啟動時只啟動必要的進程,其他的只有在需要的時候才喚醒。
自動化的服務依賴關系管理 ? 類似于yum,系統直接幫你啟動有依賴的服務
同時采用socket式與D-Bus總線式激活服務
? 以前的版本httpd服務基于tcp服務而tcp 80想監聽httpd服務就必須 ?socket file,以前是只有啟動httpd服務才能生成socket文件。
? 在centos7上是獨立開的,socket file平時打開監聽80端口,一但有人訪問,激活httpd服務。
系統狀態快照
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/98374