在实际生产使用中,比如执行批量操作时,我们不想创建ssh认证,需要使用到密码登录或者链接,此时可以使用expect来操作自动添加password:
在centos系统上expect默认是没有安装的,所以首先应先安装expect:
yum install expect -y
创建expect脚本:[[email protected] script]# cat ssh_203.exp
#!/usr/bin/env expect
set timeout 5
set remote_ip "192.168.1.203"
set passwd "hh123456"
spawn ssh [email protected]$remote_ip
expect {
"(yes/no)?" {send "yes\n";exp_continue}
"password:" {send "$passwd\r"}
}
expect "*#"
send "cd /data/script && touch mxd{1..10}\r"
interact
interact的作用是让以上登录后留在远程主机控制台上,这样不会退出远程主机,仅用于ssh登录。
执行脚本:
[[email protected] script]# ./ssh_203.exp (或者/usr/bin/expect ssh_203.exp)
以下为使用scp传输一个文件到远程主机:cat 22.sh
#!/usr/bin/env expect
set timeout 5
set remote_ip "192.168.1.203"
set passwd "hh123456"
spawn scp -rp /data/script/ssh_203.sh [email protected]$remote_ip:/data/script/
expect {
"(yes/no)?" {send "yes\r";exp_continue}
"password:" {send "$passwd\r" }
}
expect eof
expect eof 表示执行完成命令后退出远程主机
timeout则表示连接异常时等待的超时时间
以下为将文件传输带远程主机并执行:cat 33.sh
#!/usr/bin/env expect
set timeout 5
set remote_ip "192.168.1.203"
set passwd "hh123456"
spawn scp -rp /data/script/ssh_203.sh [email protected]$remote_ip:/data/script/
expect "password:"
send $passwd\r
spawn ssh [email protected]$remote_ip "sh /data/script/ssh_203.sh"
expect "password:"
send $passwd\r
expect eof