安装expect
yum -y install expect
编写脚本
vim ssh.exp
#!/usr/bin/expect
spawn ssh root@192.168.57.134 -p 22
expect "*Are you sure you want to continue connecting (yes/no)?"
send "yes
"
expect "*password:"
send "123456
"
interact
增加执行权限
chmod +x ssh.exp
执行脚本
expect ./ssh.exp
编写远程执行命令脚本
#!/use/bin/expect
set host "192.168.100.120"
set passwd "123456"
spawn ssh root@$host
expert {
"yes/no" { send "yes
";exp_continue }
"assword:" { send "$passwd
" }
}
expect "]*" //匹配 ]* 的内容,其实就是[root@localhost sum] # 的最后那段
send "touch 1.txt"
expect "]*"
send "touch 2.txt"
expect "]*"
send "exit
"
远程执行脚本示例
#!/usr/bin/expect
spawn ssh root@192.168.57.134 -p 22
#expect "*Are you sure you want to continue connecting (yes/no)?"
#send "yes
"
expect "*password:"
send "123456
"
expect "]*"
send "yum -y install vsftpd
"
send "systemctl start vsftpd
"
send "netstat -nltp| grep 21
"
send "exit
"
interact