分类: LINUX
2010-11-15 10:45:45
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 <<-END1
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 <<-END2
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
附件:
chinaunix网友2010-11-15 16:06:19
很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com