由于工作需要server间实现自动交互,因此特意在网上找了几篇关于expect文章进行学习。
之后尝试实现了几个常用交互功能的程序,写成脚本供大家参考。
expect不是函数也不是命令,是一种编程工具语言,主要功能是实现信息自动交互(例:自动登录server).
usage: expect [-di] [-c cmds] [[-f] cmdfile] [args]
expect嵌套在shell脚本中实现scp:
#!/bin/sh
echo "input your text name for copying:"
read textname //得到要scp的文件名
login="yourlogin" //设置你的login
password="yourpassword" //设置你的password
servername="yourservername" //设置你的server
path=`pwd` //设置scp文件所在的path
objectpath="yourobjectpath" //设置scp文件到哪个path
expect -c "
spawn scp "$path/$textname" "$login@$servername:@objectpath" //执行scp操作,这时系统会询问密码.
expect {
\"*assword:*\" {
set timeout 300//设置超时时间.
send \"$password\r\"//千万别忘掉回车.
}
}
expect eof"
expect嵌套在shell脚本中实现ftp:
#!/bin/ksh
login="yourlogin"
password="yourpassword"
ftpserver="yourserverip" //格式:xxx.xxx.xxx.xxx
path="yourpath" //你要在目标server中存放file的path
echo "input your file that will download to njcgpa"
read line
expect << EOF
set timeout 120
spawn ftp $ftpserver
expect "*Name*"
send "$login\r"
expect "*assword*"
send "$password\r"
expect "*ftp*"
send "cd $path\r"
expect "*250*CWD*"
send "put line\r"
expect "*complete*"
send "bye\r"
expect eof
EOF //EOF必须在行首,行首不能有空格
一个完整的实现自动ftp多个文件的程序。
功能:将多个文件ftp到指定server中的指定path中去。
用法:将程序存放在autoftp文件中。
>./autoftp file1 file2 file3 file4 ...
#!/bin/ksh
login="yourlogin"
password="yourpassword"
ftpserver="yourftpserverIP"
path="yourftppath"
succount=0
allcount=0
while [ $# -gt 0 ]
do
allcount=`expr $allcount + 1`
if [ -f $1 ]
then
succount=`expr $succount + 1`
expect << EOF
set timeout 120
spawn ftp $ftpserver
expect "*Name*"
send "$login\r"
expect "*assword*"
send "$password\r"
expect "*ftp*"
send "cd $path\r"
expect "*250*CWD*"
send "put $1\r"
expect "*complete*"
send "bye\r"
expect eof
EOF
echo "$1 file was ftp completed!" >> resultlog
else
echo "$1 file was not found!" >> resultlog
countine
fi
shift
done
if [ -f resultlog ]
then
cat resultlog
rm resultlog
fi
echo "ftp $allcount files, $succount files were finished to ftp!"
测试:
>touch 1 2 3 4 5 // 新建5个file文件
>./autoftp 1 2 3 4 55 66 77 5 // 55 66 77为三个不存在的文件
1 file was ftp completed!
2 file was ftp completed!
3 file was ftp completed!
4 file was ftp completed!
55 file was not found!
66 file was not found!
77 file was not found!
5 file was ftp completed!
ftp 8 files, 5 files were finished to ftp!
该程序目前只能判定文件是否存在,若不存在则跳过不执行ftp。