你覺得最實用的linux腳本哪些?

你寫過哪些腳本大大提高了自己的工作效率呢~


有哪些好用的bash 技巧(包括不限於快捷鍵、自用小腳本)? - 呂糰子的回答

2. 便捷的 ssh 管理

將常用的ssh伺服器配置好:

$ cat ~/.ssh/config
# Test host
Host test
HostName 10.1.1.1
User admin

Host *
ServerAliveInterval 60
ControlMaster auto
ControlPath ~/.ssh/%h-%p-%r
ControlPersist yes

將以下內容添加到~/.bash_profile 或者 ~/.bashrc 文件中:

# Auto complete ssh server defined in ~/.ssh/config
#complete -W "$(awk /^Host/{if ($2!="*") print $2} ~/.ssh/config)" ssh

# Define ssh alias for server defined in ~/.ssh/config
for host in $(awk /^Host/{if ($2!="*") print $2} ~/.ssh/config); do
alias $host="ssh $host"
done

然後重新登錄,輸入 test 命令就可以 ssh 到 test 伺服器了 :)


幾個Shell腳本的例子,覺得還不錯。

【例子:001】判斷輸入為數字,字元或其他

#!/bin/bash
read -p "Enter a number or string here:" input
case $input in
[0-9]) echo -e "Good job, Your input is a numberic!
" ;;
[a-zA-Z]) echo -e "Good job, Your input is a character!
" ;;
*) echo -e "Your input is wrong, input again!
" ;;
esac

【例子:002】求平均數

#!/bin/bash
# Calculate the average of a series of numbers.
SCORE="0"
AVERAGE="0"
SUM="0"
NUM="0"
while true; do
echo -n "Enter your score [0-100%] (q for quit): "; read SCORE;
if (("$SCORE" &< "0")) || (("$SCORE" &> "100")); then
echo "Be serious. Common, try again: "
elif [ "$SCORE" == "q" ]; then
echo "Average rating: $AVERAGE%."
break
else
SUM=$[$SUM + $SCORE]
NUM=$[$NUM + 1]
AVERAGE=$[$SUM / $NUM]
fi
done
echo "Exiting."
【例子:003】自減輸出
[scriptname: doit.sh]
while (( $# &> 0 ))
do
echo $*
shift
done
/&> ./doit.sh a b c d e
a b c d e
b c d e
c d e
d e
e

【例子:004】在文件中添加前綴

# 人名列表
# cat namelist
Jame
Bob
Tom
Jerry
Sherry
Alice
John
# 腳本程序
# cat namelist.sh
#!/bin/bash
for name in $(cat namelist)
do
echo "name= " $name
done
echo "The name is out of namelist file"
# 輸出結果
# ./namelist.sh
name= Jame
name= Bob
name= Tom
name= Jerry
name= Sherry
name= Alice
name= John

【例子:005】批量測試文件是否存在

[root@host ~]# cat testfile.sh
#!/bin/bash

for file in test*.sh
do
if [ -f $file ];then
echo "$file existed."
fi
done

[root@host ~]# ./testfile.sh
test.sh existed.
test1.sh existed.
test2.sh existed.
test3.sh existed.
test4.sh existed.
test5.sh existed.
test78.sh existed.
test_dev_null.sh existed.
testfile.sh existed.

【例子:005】用指定大小文件填充硬碟
複製代碼代碼如下:
[root@host ~]# df -ih /tmp
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/vg00-lvol5
1000K 3.8K 997K 1% /tmp
[root@host ~]# cat cover_disk.sh
#!/bin/env bash
counter=0
max=3800
remainder=0
while true
do
((counter=counter+1))
if [ ${#counter} -gt $max ];then
break
fi
((remainder=counter%1000))
if [ $remainder -eq 0 ];then
echo -e "counter=$counter date=" $(date)
fi
mkdir -p /tmp/temp
cat &< testfile &> "/tmp/temp/myfile.$counter"
if [ $? -ne 0 ];then
echo "Failed to write file to Disk."
exit 1
fi
done
echo "Done!"
[root@host ~]# ./cover_disk.sh
counter=1000 date= Wed Sep 10 09:20:39 HKT 2014
counter=2000 date= Wed Sep 10 09:20:48 HKT 2014
counter=3000 date= Wed Sep 10 09:20:56 HKT 2014
cat: write error: No space left on device
Failed to write file to Disk.
dd if=/dev/zero of=testfile bs=1M count=1

【例子:006】通過遍歷的方法讀取配置文件

[root@host ~]# cat hosts.allow
127.0.0.1
127.0.0.2
127.0.0.3
127.0.0.4
127.0.0.5
127.0.0.6
127.0.0.7
127.0.0.8
127.0.0.9
[root@host ~]# cat readlines.sh
#!/bin/env bash
i=0
while read LINE;do
hosts_allow[$i]=$LINE
((i++))
done &< hosts.allow for ((i=1;i&<=${#hosts_allow[@]};i++)); do echo ${hosts_allow[$i]} done echo "Done" [root@host ~]# ./readlines.sh 127.0.0.2 127.0.0.3 127.0.0.4 127.0.0.5 127.0.0.6 127.0.0.7 127.0.0.8 127.0.0.9 Done

【例子:007】簡單正則表達式應用

[root@host ~]# cat regex.sh
#!/bin/env sh
#Filename: regex.sh
regex="[A-Za-z0-9]{6}"
if [[ $1 =~ $regex ]]
then
num=$1
echo $num
else
echo "Invalid entry"
exit 1
fi
[root@host ~]# ./regex.sh 123abc
123abc

#!/bin/env bash
#Filename: validint.sh
validint(){
ret=`echo $1 | awk {start = match($1,/^-?[0-9]+$/);if (start == 0) print "1";else print "0"}`
return $ret
}
validint $1
if [ $? -ne 0 ]; then
echo "Wrong Entry"
exit 1
else
echo "OK! Input number is:" $1
fi

【例子:008】簡單的按日期備份文件

#!/bin/bash
NOW=$(date +"%m-%d-%Y") # 當前日期
FILE="backup.$NOW.tar.gz" # 備份文件
echo "Backing up data to /tmp/backup.$NOW.tar.gz file, please wait..." #列印信息
tar xcvf /tmp/backup.$NOW.tar.gz /home/ /etc/ /var # 同時備份多個文件到指定的tar壓縮文件中
echo "Done..."

你想更深入了解學習Linux知識體系,你可以看一下我們花費了一個多月整理了上百小時的幾百個知識點體系內容:

【超全整理】《Linux雲計算從入門到精通》系列實戰筆記全放送


隨手寫了個helm-fasd.

直接在emacs裡面用fasd的結果, 還多了模糊查找. 算是腳本吧, 畢竟.el文件是解釋執行的, 我沒編譯到elc...


再次安利youtube-dl,比大部分付費youtube下載工具都好用,,唯一缺點就是需要python、而且沒有GUI。


受邀回答,既然提到了工作效率,自動和無人值守的應該是屬於最高效率了吧。

  • SVN/GIT提交代碼時自動檢查語法錯誤,生成代碼文檔,跑unit test case--CI。
  • 自動同步代碼,編譯,發布更新的系統--CD。
  • 自動抓取主機各種指標,一旦異常發送郵件和簡訊通知——shenkin。
  • vi 保存時自動掛鉤語法檢查,舊文件自動備份。
  • 一條命令分析當前的最大流量來源。

先寫這麼多吧。


  1.模擬linnux登錄shell

  #/bin/bash

  echo -n "login:"

  read name

  echo -n "password:"

  read passwd

  if [ $name = "cht" -a $passwd = "abc" ];then

  echo "the host and password is right!"

  else echo "input is error!"

  fi

  2.比較兩個數大小

  #/bin/bash

  echo "please enter two number"

  read a

  read b

  if test $a -eq $b

  then echo "NO.1 = NO.2"

  elif test $a -gt $b

  then echo "NO.1 &> NO.2"

  else echo "NO.1 &< NO.2"

  fi

  3.查找/root/目錄下是否存在該文件

  #/bin/bash

  echo "enter a file name:"

  read a

  if test -e /root/$a

  then echo "the file is exist!"

  else echo "the file is not exist!"

  fi

  4.for循環的使用

  #/bin/bash

  clear

  for num in 1 2 3 4 5 6 7 8 9 10

  do

  echo "$num"

  done

 5.

  #/bin/bash

  echo "Please enter a user:"

  read a

  b=$(whoami)

  if test $a = $b

  then echo "the user is running."

  else echo "the user is not running."

  fi

 6.刪除當前目錄下大小為0的文件

  #/bin/bash

  for filename in `ls`

  do

  if test -d $filename

  then b=0

  else

  a=$(ls -l $filename | awk { print $5 })

  if test $a -eq 0

  then rm $filename

  fi

  fi

  done

 7.如果/export/um_lpp_source下有文件,那麼將其文件系統大小改為3G

  #/bin/bash

  while line=`ls /export/um_lpp_source`

  do

  if test $line=""

  then echo "NULL"

  sleep 1

  else echo $line

  chfs -a size=3G /export/um_lpp_source

  exit 0

  fi

  done

 8.測試IP地址

  #/bin/bash

  for i in 1 2 3 4 5 6 7 8 9

  do

  echo "the number of $i computer is "

  ping -c 1 192.168.0.$i

  done

 9.如果test.log的大小大於0,那麼將/opt目錄下的*.tar.gz文件

  #/bin/sh

  a=2

  while name="test.log"

  do

  sleep 1

  b=$(ls -l $name | awk {print $5})

  if test $b -ge $a

  #then echo "OK"

  then `cp /opt/*.tar.gz .`

  exit 0

  fi

  done

10.列印讀取的內容,為下面的例子做準備

  #/bin/bash

  while read name

  do

  echo $name

  done

 11.從0.sh中讀取內容並列印

  #/bin/bash

  while read line

  do

  echo $line

  done &< 0.sh

 12.讀取a.c中的內容並做加1運算

  #/bin/bash

  test -e a.c

  while read line

  do

  a=$(($line+1))

  done &< a.c

  echo $a

 13.普通無參數函數

  #/bin/bash

  p ()

  {

  echo "hello"

  }

  p

 14.給函數傳遞參數

  #/bin/bash

  p_num ()

  {

  num=$1

  echo $num

  }

  for n in $@

  do

  p_num $n

  done

 15.創建文件夾

  #/bin/bash

  while :

  do

  echo "please input files name:"

  read a

  if test -e /root/$a

  then

  echo "the file is existing Please input new file name:"

  else

  mkdir $a

  echo "you aye sussesful!"

  break

  fi

  done

16.獲取本機IP地址

  #/bin/bash

  ifconfig | grep "inet addr:" | awk { print $2 }| sed s/addr://g

 17.查找最大文件

  #/bin/bash

  a=0

  for name in *.*

  do

  b=$(ls -l $name | awk {print $5})

  if test $b -ge $a

  then a=$b

  namemax=$name

  fi

  done

  echo "the max file is $namemax"

18.查找當前網段內IP用戶,重定向到ip.txt文件中

  #/bin/bash

  a=1

  while :

  do

  a=$(($a+1))

  if test $a -gt 255

  then break

  else

  echo $(ping -c 1 192.168.0.$a | grep "ttl" | awk {print $4}| sed s/://g)

  ip=$(ping -c 1 192.168.0.$a | grep "ttl" | awk {print $4}| sed s/://g)

  echo $ip &>&> ip.txt

  fi

  done

 19.列印當前用戶

  #/bin/bash

  echo "Current User is :"

  echo $(ps | grep "$$" | awk {print $2})

 20.case語句練習

  #!/bin/bash

  clear

  echo "enter a number from 1 to 5:"

  read num

  case $num in

  1) echo "you enter 1"

  ;;

  2) echo "you enter 2"

  ;;

  3) echo "you enter 3"

  ;;

  4) echo "you enter 4"

  ;;

  5) echo "you enter 5"

  ;;

  *) echo "error"

  ;;

  esac

 21.yes/no返回不同的結構

  #!/bin/bash

  clear

  echo "enter [y/n]:"

  read a

  case $a in

  y|Y|Yes|YES) echo "you enter $a"

  ;;

  n|N|NO|no) echo "you enter $a"

  ;;

  *) echo "error"

  ;;

  esac

 22.內置命令的使用

  #/bin/bash

  clear

  echo "Hello, $USER"

  echo

  echo "Today s date id `date`"

  echo

  echo "the user is :"

  who

  echo

  echo "this is `uname -s`"

  echo

  echo "thats all folks! "

 23.列印無密碼用戶

  #/bin/bash

  echo "No Password User are :"

  echo $(cat /etc/shadow | grep "!!" | awk BEGIN { FS=":" }{print $1})

 24.

  #/bin/bash

  clear

  echo "Hello, $USER"

  echo

  echo "Today s date id `date`"

  echo

  echo "the user is :"

  who

  echo

  echo "this is `uname -s`"

  echo

  echo "thats all folks! "

 25.檢查埠號是否已啟動

  #!/bin/bash

  n=1

  echo "檢查xxx服務..."

  while true

  do

  if test $n -gt 20

  then

  echo "xxx服務啟動失敗"

  break

  fi

  sleep 5

  n=$(($n+1))

  port=`netstat -antp | grep "0.0.0.0:8080"`

  if [ ${#port} -gt 3 ]; then

  echo "xxx服務已經啟動"

  break;

  fi

  done


以下命令日常操作,純屬沒事娛樂,基本很通用的命令

1.查看登錄用戶記錄,按次數排序

#!/bin/bash

lastb -a 2&>/dev/null|head -n100|grep -v btmp begins|

awk $1!="" {print $1,$NF}|

sort|uniq -c|sort -nr -k 1|

awk

BEGIN {

printf "%s
%-12s%-18s%s
","Login Failed:","User","IP","Num of login"

}

{

printf "%-12s%-18s%s
",$2,$3,$1

}

END {

print ""

}

2.查看登錄失敗用戶記錄,按次數排序

last -a 2&>/dev/null|head -n100|grep -v btmp begins|

awk $1!="" {print $1,$NF}|

sort|uniq -c|sort -nr -k 1|

awk

BEGIN {

printf "%s
%-12s%-18s%s
","Login Successed:","User","IP","Num of login"

}

{

printf "%-12s%-18s%s
",$2,$3,$1

}

END {

print ""

}

3.CPU佔用前十進程

ps axww -o user,pcpu,pmem,stime,comm |

grep -v PID |

sort -nr -k 2 | head |

awk

{printf "%-3s%-8s%-6s%-6s%-8s%-24s
",NR,$1,$2,$3,$4,$5}

END {

print""}

4.內存佔用前十進程

ps axww -o user,pcpu,pmem,stime,comm |

grep -v PID |

sort -nr -k 3 |

head |

awk

{printf "%-3s%-8s%-6s%-6s%-8s%-24s
",NR,$1,$2,$3,$4,$5}

END {

print""}

5. TCP佔用

ss -atnp |

grep -v "State" |

awk {print $6} |

awk -F " {print $2} |

awk

{++S[$1]}

END {for(a in S) printf "%-20s%-5s
",a, S[a]} |

sort -nr -k2 |

head

6.系統用戶巡檢

#!/bin/bash

all(){

echo System Users:

cat /etc/passwd|

awk -F:

{a[NR]=$1}

END {

for(i=1;i&<=NR;i++) {

printf(i%5 ? " "a[i]" " : " "a[i]"
")}

{print ""}

}

return 0

}

empty(){

echo -e
No Password Users:

cat /etc/shadow|

awk -F: $2=="" {print $1}|

awk

{a[NR]=$1}

END {

for(i=1;i&<=NR;i++) {

printf(i%5 ? " "a[i]" " : " "a[i]"
")}

}

return 0

}

empty_login(){

grep "^PermitEmptyPasswords yes" /etc/ssh/sshd_config echo -e
SSH_Config
PermitEmptyPasswords: YES

return 0

}

all

empty

empty_login

6. SSH快速選擇登錄

#!/bin/bash

hosts=`cat ~/.ssh/config|grep Host|awk {print $2}`

select var in $hosts

do

if [[ -n $var ]];then

break

fi

done

exec ssh $var

7. 工作中遇到 的mysql索引缺失批量自動修復(以模板庫為基準)

#!/bin/bash

declare -A PORTS

N=(

此處為字典,記錄服務埠,比如

[0]="3306"

...

)

mycmd() {

if [ "$1" == "" -o "$2" == "" ];then

printf "${FUNCNAME[0]}:Exit missing argument"

exit 1

else

mysql -uuser -ppassword -hhost -r -N -B -P$1 -e"$2"

fi

}

do_empty() {

printf "檢查基準庫索引
"

if [ ! -s index.empty ];then

emptytbs=$(mycmd ${N[1]} "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA=XXX AND TABLE_TYPE=BASE TABLE;")

for emptytb in $emptytbs

do

mycmd ${N[1]} "show create table XXX.$emptytb"|egrep "^[ ]{1,}KEY.*(.*),{0,1}$"|awk {print "$emptytb:",$0}|sed s/`//g|sed s/(.*:).*KEY.*((.*)),{0,1}/12/g|grep -v 255 1&>&> index.empty

done

fi

}

do_other() {

printf "檢查租戶表
"

index_tbs=$(cat index.empty |awk -F: {print $1}|sort -u)

printf "修復索引
"

for n in ${!N[*]}

do

# database

otherdbs=$(mycmd ${N[$n]} "SHOW DATABASES LIKE XXX;")

for otherdb in $otherdbs

do

# table

for index_tb in $index_tbs

do

isexist=$(mycmd ${N[$n]} "USE $otherdb;SHOW TABLES LIKE $index_tb;"|egrep "^$index_tb$"|wc -l)

if [ $isexist -eq 1 ];then

# columns

local index_cols

index_cols=$(cat index.empty|grep "$index_tb:"|awk -F: {print $2})

for index_col in $index_cols

do

# index

mycmd ${N[$n]} "SHOW CREATE TABLE $otherdb.$index_tb;"|egrep "^[ ]{1,}KEY.*(.*),{0,1}$"|sed s/`//g|grep $index_col &>/dev/null

if [ $? -ne 0 ];then

#printf " $otherdb.$index_tb $index_col already exist.
"

#else

local index_name

index_name=$(echo "$index_col"|sed s/,/_/g)

printf " e[31mALTER TABLE $otherdb.$index_tb ADD INDEX IDX_$index_name ($index_col);e[0m
"

# mycmd ${N[$n]} "ALTER TABLE $otherdb.$index_tb ADD INDEX IDX_$index_name ($index_col);"

fi

done

fi

done

done

done

printf "修復完成"

}

do_empty

do_other

8. shell調用阿里雲API獲取Mysl slow log(shell中JSON的解析)

#!/bin/bash

LOGOUTPUT="XXX.log"

# DBInstance

declare -A RDS

RDS=(

此處為字典,記錄HOST IP

[0]="123.123.123.123"

)

#API Request Params

ENDTIME=`date -d -1day +%FT%H:%MZ`

STARTTIME=`date -d -1day -1min +%FT%H:%MZ`

ACTION=DescribeSlowLogRecords

PAGESIZE=100

#echo $LOGOUTPUT

#echo "$STARTTIME $ENDTIME"

JQ1="jq .PageRecordCount"

JQ2="jq .Items.SQLSlowRecord[]"

JQ3="jq -c ."

for RDS in ${RDS[@]}

do

APIREQUEST=$(aliyuncli rds $ACTION --DBInstanceId $RDS --StartTime $STARTTIME --EndTime $ENDTIME --PageSize $PAGESIZE)

COUNT=$(echo $APIREQUEST|$JQ1)

# echo $COUNT

if [[ $COUNT != "0" ]];then

echo $APIREQUEST|$JQ2|$JQ3 &>&>$LOGOUTPUT

fi

done

exit 0


expect腳本,可以完成需要輸入密碼的場景,例如ssh遠程執行命令


http://github.com/binave/extcmd


勤寫alias。。。


linux目錄跳轉利器 z.sh

可以快速切換目錄。

如:

z apt

可以在任何目錄切換到 /etc/apt/ 目錄

使用方法:

linux目錄跳轉利器 z.sh


我來一個,批量替換某文件夾下面的ip或其它配置信息.腳本中ip是假的.

#!/bin/bash

TARGET_FILE=*.properties

TARGET_KEYS=90.46.78.38:90.0.309.949 90.47.904.956:90.0.300.995 90.46.79.53:90.0.300.996 90.47.904.939:90.0.300.999 90.47.49.330:90.0.309.993

BASE_DIR="/path/to/apps"

ANSWER=$1

for key in $TARGET_KEYS

do

key1=`echo $key|awk -F : {print $1}`

key2=`echo $key|awk -F : {print $2}`

SEARCH="find ${BASE_DIR} -name ${TARGET_FILE}|xargs grep -ri ${key1} -l"

echo $SEARCH

echo `eval $SEARCH`

for file in `eval $SEARCH`;

do

echo $file

echo "############################################################################################################################################"

if [ "$ANSWER" = "Y" ]; then

sed -i "s/$key1/$key2/g" $file

else

sed "s/$key1/$key2/g" $file

fi

echo "############################################################################################################################################"

done

done


這個實用的腳本是要大家工作中提練出來的。

這個問題大概的想法就是把大家寫出的LINUX腳本直接拿來用。但是實際上這種腳本已經是滿多了。缺少的是針對性的。

要具有會寫腳本的能力。比這個拿來主義好。


推薦閱讀:

像蘋果Time Machine 一樣備份Linux伺服器(基於rsync)
你的Ubuntu還可以這麼美
重磅推薦:10個你非常熟悉的Linux終端遊戲
Linux 下的 C++ 開發和 Windows 環境下的開發有什麼區別?
Linux系統各種目錄的作用

TAG:Linux | 運維 | 腳本 | IT運維 | Linux運維 |