Linux expect命令
当shell编程中用到telnet,ftp,ssh需要要人机交互的服务时,这时可以使用expect实现自动交互.
如果你怕写在shell脚本的中密码被别人看到,你可以通过shc对脚本进行加密:shc –r –f 脚本名
下面是一个ssh使用expect把文件存放到远程主机上的例子
#!/bin/bash
file_exist=false;
confirmed=false;
#程序绝对路径
while [ $file_exist = false ]
do
echo -n "请输入程序路径,如:/u/tiptop/azz/4gl/p_zx.4gl:";
read filename;
if [ -z $filename ];
then continue;
else
if [ -f $filename ];
then file_exist=true;
else
echo "$filename 文件不存在";
fi
fi
done
while [ $confirmed = false ]
do
echo -n "确认上传 y or n:"
read c
if [[ $c = y || $c = Y || $c = n || $c = N ]];
then confirmed=true;
else
echo "请确认是否要上传"
fi
done
if [[ $c = y || $c = Y ]];then
target_filename=${filename}.`date +%Y_%m_%d_%H_%M_%S`
#echo $filename
expect <
spawn ssh tiptop@10.134.x.x mv ${filename} ${target_filename}
expect {
#first connect, no public key in ~/.ssh/known_hosts
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
expect "password:"
send "mi_ma\r"
}
#already has public key in ~/.ssh/known_hosts
"password:" {
send "mi_ma\r"
}
}
expect eof
END1
expect <
spawn scp ${filename} tiptop@10.134.x.x:${filename}
expect {
#first connect, no public key in ~/.ssh/known_hosts
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
expect "password:"
send "mi_ma\r"
}
#already has public key in ~/.ssh/known_hosts
"password:" {
send "mi_ma\r"
}
}
expect "*"
send "exit\r"
expect eof
END2
#记录log
u_time=`date +%Y/%m/%d" "%H:%M:%S`
ip=`who am i|cut -c37-80|sed s/")"//g`
username=`whoami`
echo "$username $ip ${u_time} ${filename}" >> /u/out/upload.log
fi
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7419833/viewspace-673700/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/7419833/viewspace-673700/