目的:咱们机器的的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