Shell常用技巧

shell去掉兩端的空格(類似python的strip功能)

echo "   abs  ssa " |sed 's/ *$//g'|sed 's/^ *//g'

shell刪除匹配的兩行之間的內容(包含匹配的行)

比如,文檔myfile.txt,內容如下:

*****
****
a ***
**
**
**
b **
****

刪除a,b行之間的內容,最終得到

*****
****
****

使用sed命令匹配刪除

sed -i '/a/,/b/d' myfile.txt

shell調用expect實現自動交互

上傳文件到指定設備

調用方法:

假設腳本名稱爲upload.sh

bash upload.sh 設備IP地址 設備用戶 設備用戶密碼

腳本代碼

#!/bin/bash
if [ $# -lt 3 ]; then
    echo "Usage: $0 ip user password"
    exit 1
else
    ip=$1
    user=$2
    password=$3
fi
src=./test #要拷貝的源目錄
dst=/home/$user/ #遠端目錄
#上傳文件
expect <<-EOF
set timeout 300 #設置超時時間值大些避免拷貝文件過多超時
spawn scp -r $src $user@$ip:$dst
expect {
    "(yes/no)?"
    {
        send "yes\r"
        expect "*assword:" { send "$password\r"}
    }
    "*assword:"
    {
        send "$password\r"
    }
}
expect eof
EOF

執行遠端代碼

調用方法:

假設腳本名稱爲execute.sh

bash execute.sh 設備IP地址 設備用戶 設備用戶密碼

腳本代碼

#!/bin/bash
if [ $# -lt 3 ]; then
    echo "Usage: $0 ip user password"
    exit 1
else
    ip=$1
    user=$2
    password=$3
fi
command="bash /home/$user/test.sh" #要執行的命令腳本
#執行命令
expect <<-EOF
set timeout 300 #設置超時時間值大些避免執行命令時間過長超時
spawn ssh $user@$ip $command
expect {
    "(yes/no)?"
    {
        send "yes\r"
        expect "*assword:" { send "$password\r"}
    }
    "*assword:"
    {
        send "$password\r"
    }
}
expect eof
EOF
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章