在linux下如何通過expect正確執行自動切換登入,並且執行命令和指令碼

來源:互聯網
上載者:User

最近項目在搞可維護性這塊功能,如:修改網卡IP、機器重啟/關閉,Database Backup與恢複;這些功能點與linux中的shell指令碼執行息息相關,但shell指令碼卻不支援自動化,目前我所知道的支援自動化的指令碼也就expect、perl、python可支援自動化處理的指令碼,雖然linux安裝安後會內建perl命令庫,但還是需要通過安裝expect第三方動態語言。好了,廢話不多說,直接上代碼:
#! /usr/bin/expect 

set command [lindex $argv 0]

set username [lindex $argv 1] 

set passwd [lindex $argv 2]

spawn su - $username -c $command

expect "password:"

send $passwd\r

expect eof

exit

#! /usr/bin/expect   如果各位不知道這句是什麼意思,可以通過執行witch epxect命令查詢expect命令庫地址,我這裡就是/usr/bin/expect

指令碼中首先定義了command、username、passwd三個參數,在調用時可通過./shell.sh  reboot  root  root 來進行傳參,切記不可用sh shell.sh的方式來執行指令碼,因為expect指令碼本身是不能用shell的形式來啟動的,不然會報spawn、expect、send命令不到的錯誤。

如果是想切換使用者後呼叫指令碼,可以這樣寫:

 #! /usr/bin/expect 

set username [lindex $argv 0] 

set passwd [lindex $argv 1]

spawn su - $username

expect "password:"

send $passwd\r

expext {

"su:密碼錯誤" { send "echo 密碼錯誤\r" }

"*#*"  {  send "sh test.sh\r" }

}

expect eof

exit

 

expect安裝包在我的資源中有,大家如有需要也可以下載,語言的思想基本都差不多,只是指令碼語言的寫法都比較嚴謹,所以在編寫過程中需要大夥細心。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.