神奇的expect
想寫自動(dòng)化腳本的時(shí)候,遇到需要交互的,如ssh,scp,就束手無策,直到我知道了expect。
expect 有一系列expect-send對(duì)組成,就像聊天一樣。
expect A send B
expect C send D
先來個(gè)例子
#!/usr/bin/expect
set timeout 5
spawn ssh 192.168.2.38
expect "password" {send "slk\n"}
expect "Last login" {send " ls -l\n"}
expect eof
exit
/usr/bin/expect是指明該腳本要調(diào)用expect
set timeout 5,設(shè)置每個(gè)expect等待的時(shí)間,-1則為永不超時(shí),在expect scp xxx xxx 的時(shí)候很好用,時(shí)間如果設(shè)太短,還沒傳完,expect就返回了。
spawn 創(chuàng)建一個(gè)進(jìn)程,執(zhí)行ssh 192.168.2.38命令,然后下面就是expect 和send的命令對(duì)了。
expect "password" {send "slk\n"}, 當(dāng)出現(xiàn)“expect"的時(shí)候,發(fā)送,"slk\n",必須要加\n,就和我們平時(shí)自己輸秘密最后要加個(gè)\n一樣。
expect可以不止一個(gè),所以下面可以繼續(xù)expect和send。如果要執(zhí)行的命令有很多,可以不寫那么多expect send,直接把命令寫在另一個(gè)腳本里,expect "Last login" {send " ./do.sh\n"} 就好了,expect是為交互而存在的,在不需要交互的地方調(diào)用expect是浪費(fèi)自己的時(shí)間。
?
總結(jié)
- 上一篇: 各主板黑苹果dsdt补丁_台式机微星(M
- 下一篇: 2022年整理LeetCode最新刷题攻