在shell腳本中利用expect實作自己主動應答
測試腳本(已驗證,來自于http://forum.ubuntu.org.cn/ntopic21611.html):
要互動的腳本(talk.sh)例如以下:
#!/bin/bash
echo "Who are you?"
read who
echo "Hello,$who"
echo "Are you happy?"
read answer
echo "why?"
實作自己主動應答的腳本auto.sh例如以下:
expect<<- END
spawn ./talk.sh
expect "who"
send "firefly\n"
expect "happy?"
send "Yes,I am happy.\n"
expect "why?"
send "Because it worked!\n"
expect eof
exit
END
運作auto.sh後能夠看到自己主動互動例如以下:
Who are you?
firefly
Hello,firefly
Are you happy?
Yes,I am happy.
why?
Because it worked!
眼下僅僅用到了expect最主要的使用方法,隻是對用腳本實作自己主動化已經非常實用了
-------------------------------------------------------------------------------------------------
expect 實作su root:
#!/usr/bin/expect
#created by neilzhao of linpus corp.
set passwd 111111
spawn su
expect "Password:"
send "$passwd\n"
interact
自己主動ssh登入的幾種方法
自己主動ssh登入的幾種方法 1. 自己主動ssh/scp方法==
A為本地主機(即用于控制其它主機的機器) ;
B為遠端主機(即被控制的機器Server), 假如ip為192.168.60.110;
A和B的系統都是Linux
在A上執行指令:
# ssh-keygen -t rsa (連續三次回車,即在本地生成了公鑰和私鑰,不設定password)
# ssh "mkdir .ssh" (須要輸入password)
# scp ~/.ssh/id_rsa.pub :.ssh/id_rsa.pub (須要輸入password)
在B上的指令:
# touch /root/.ssh/authorized_keys (假設已經存在這個檔案, 跳過這條)
# cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys (将id_rsa.pub的内容追加到authorized_keys 中)
回到A機器:
# ssh (不須要password, 登入成功)
2. 控制n個機器如上所述自己主動登入
那就須要n對鑰匙(密鑰和公鑰), ssh-keygen 指令能夠任意更改鑰匙對的名字, 比方:
# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa_192.168.60.110
這樣私鑰和公鑰的名字分别就是: id_rsa_192.168.60.110和 id_rsa_192.168.60.110.pub;然後将 id_rsa_192.168.60.110.pub 檔案的内容, 追加到sever的 ~/.ssh/authorized_keys檔案裡,最後, 在本地用ssh指令的 -i 參數指定本地密鑰, 并登入:
# ssh -i /root/.ssh/id_rsa_192.168.60.110
scp也是一樣的
# scp -i /root/.ssh/id_rsa_192.168.60.110 filename :/home/someone
在檔案.bashrc中加下兩行,每次做相同的操作就不用敲入這樣長的指令了:
alias sshcell='ssh -i /root/.ssh/id_rsa_192.168.60.110 '
alias scpcell='scp -i /root/.ssh/id_rsa_192.168.60.110 filename :/home/someone'
這樣,直接鍵入一下指令實作ssh和scp自己主動登入:
# sshcell
# scpcell
3. 自己主動ssh/scp腳本
假設須要從A,到B,然後才可以到C,那麼須要ssh和scp兩次,是比較麻煩的。
ssh自己主動登入:
#!/usr/bin/expect -f
set timeout 30
spawn ssh weiqiong@B
expect "password:"
send "pppppp\r"
expect "]*"
send "ssh weiqiong@C\r"
scp從A複制檔案到C:
set timeout 300
set file [lindex $argv 0]
spawn scp $file weiqiong@B:/home/weiqiong
send "scp $file weiqiong@C:/home/weiqiong\r"
exit
scp從C複制檔案到A:
send "scp weiqiong@C:/home/weiqiong/$file .\r"
send "exit\r"
spawn scp weiqiong@B:/home/weiqiong/$file .
4. 建立ssh/scp通道
比方說我的機器是A,中間server為B,目标server是C<br>
從A能夠ssh到B,從B能夠ssh到C,可是A不能直接ssh到C<br>
如今展示利用ssh通道技術從A直接傳輸檔案到C<br>
1. ssh -L1234:C:22 userid@B<br>
input B's password<br>
(1234是本機A的空暇port,該指令須要A機器上的root使用者權限,實際上是在本機1234port建立了一個通道)<br>