expect 自动应答 TCL(Tool Command Language)语言
yum -y install expect
Summary : A program-script interaction and testing utility
Description :
Expect is a tcl application for automating and testing
interactive applications such as telnet, ftp, passwd, fsck,
rlogin, tip, etc. Expect makes it easy for a script to
control another program and interact with it.
This package contains expect and some scripts that use it.
任何有交互性的操作,都可以用expect来做
例1,使用expect修改用户密码
#!/bin/bash expect <<EOF > /dev/null 2>&1 spawn passwd $1 --产生passwd $1这个命令 expect "rd:" --当停在rd:结尾这个标识符时 send "456\r" --我就把456传给它 expect "rd:" --当再次停在rd:结尾这个标识符时 send "456\r" --我就再次把456传给它 expect eof --表示expect结束 EOF
# sh 1.expect test --执行方法,因为脚本里写的是$1,所以后面接你要修改密码的用户名
例2,使用expect下载同步ftp共享的文件
# cat 2.expect #!/bin/bash expect <<EOF &> /dev/null spawn lftp 10.1.1.10 -u notes expect "Password:" send "123\n" expect "10.1.1.10:~>" send "mirror mysql/ /notes/\n" send "mirror program/ /notes/\n" send "quit\n" expect eof EOF # sh 2.expect
例3,使用expect实现ssh传密码
#!/bin/bash sed -i '/^'$1'/d' /root/.ssh/known_hosts expect << EOF > /dev/null 2>&1 spawn ssh $1 expect "no)?" send "yes\r" expect "password:" send "123456\r" expect "# " send "touch /root/Desktop/123\n" send "exit\n" expect eof EOF ------------------ #!/bin/bash LANG=c sed -i '/^'$1'/d' /root/.ssh/known_hosts expect <<EOF > /dev/null 2>&1 spawn ssh $1 expect "(yes/no)?" send "yes\r" expect "rd:" send "redhat\r" expect "# " send "rm -fr /tmp/*\r" send "touch /tmp/file01\r" send "touch /var/tmp/abc\r" send "exit 1\r" EOF
--关于上面跳过yes的问题,可以加下面的参数来做
ssh 192.168.0.1 -o StrictHostKeyChecking=no
[root@i ~]# vim $HOME/.ssh/config
Host 192.168.0.*
StrictHostKeyChecking no
转载于:https://blog.51cto.com/zzclinux/1978243