1首先判断是否安装了expect
ls /usr/bin |grep expect
2没有输出就安装expect
ubuntu
apt-get install expect
centos
yum install expect
3编写脚本login.sh
#!/usr/bin/expect
# 设置超时时间
set timeout 3
# fork一个子进程执行ssh
spawn ssh root@192.168.100.133
# 捕获到密码
expect "*password*"
# 输入密码并回车
send "xxxxx
"
# 捕获#
expect "*#"
# 进入常用目录下
send "cd /opt
"
# 允许用户进行交互
interact
4输入 ./login.sh执行
5优化的脚本login.sh
#!/usr/bin/expect
# 设置超时时间
set timeout 3
# fork一个子进程执行ssh
spawn ssh root@192.168.100.133
#这里出错的话注意下格式,空格等
expect {
"*yes/no*" { send "yes
" ; exp_continue }
"*password*" { send "HzQukan888
" }
}
# 捕获#
expect "*#"
# 进入常用目录下
send "cd /opt
"
# 允许用户进行交互
interact