目的:咱們機器的的ID密碼都是各不相同的,不是統一ID和密碼增長了腳本的難度,只能把服務器的ID密碼ip相關信息寫到一個文件中,用sed cut awk去取值,用expect調用這些值達到免密碼的功能shell
這個是最終想要的結果,終於成功了,花了我幾天的時間研究,真的不容易。bash
1,開始仍是堅持用的for去寫循環,發現shell參數好像傳不到expect裏面去,一直糾結怎麼傳參,百度了很久,spawn那裏一直報錯,我還查了spawn的語法格式,綜合百度嘗試了不少仍是報錯。服務器
2,我單獨把那個變量寫在其餘腳本里,看是否能echo出來,發現用的for出問題了,果斷換成了while.因而腳本就被改爲了如下形式測試
3,最後仍是用for寫出來了,主要是變量的值須要仔細測試是否成功spa
方法1 while-expectip
[root@R1 shell]# cat ExCopy.sh
#!/bin/bash
while read LINES
do
file=test.txt
ID=`echo $LINES |cut -d : -f2`
host=`echo $LINES |cut -d : -f1`
passwd=`echo $LINES |cut -d : -f3`
expect <<EOF
spawn scp -r $file $ID@$host:/tmp
expect "yes/no" {send "yes\n"}
expect "password" {send "$passwd\n"}
expect eof
EOF
done <listci
運行結果:it
[root@R1 shell]# ./ExCopy.sh
spawn scp -r test.txt lei@192.168.1.105:/tmp
The authenticity of host '192.168.1.105 (192.168.1.105)' can't be established.
RSA key fingerprint is 4d:74:55:fb:1b:5a:f4:d2:a6:fc:33:49:c4:e5:6f:09.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.105' (RSA) to the list of known hosts.
lei@192.168.1.105's password:
test.txt 100% 1702 1.7KB/s 00:00
spawn scp -r test.txt ray@192.168.1.106:/tmp
ray@192.168.1.106's password:
test.txt 100% 1702 1.7KB/s 00:00test
文件已經在客戶機上傳送完畢awk
————————————————————————————
方法2 for-expect
仍是想用for寫出來,
思路:利用sed讀取第一行,第一行能夠設置變量,對第一行進行cut第幾列的數據,作到能夠精確的取出想要的值,接下來就是和expect語句了沒多少變化
[root@R1 shell]# cat for.sh
#!/bin/bash
num=1
for i in `cat list`
do
file=passwd
ID=`sed -n "$num p" list | cut -d : -f2`
host=`sed -n "$num p" list | cut -d : -f1 `
passwd=`sed -n "$num p" list | cut -d : -f3 `
let num+=1
expect <<EOF
spawn scp -r $file $ID@$host:/tmp
expect "password" {send "$passwd\n"}
expect eof
EOF
done