通过脚本来执行ssh登录

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\r"
# 捕获#
expect "*#"
# 进入常用目录下
send "cd /opt\r"
# 允许用户进行交互
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\r" ; exp_continue }
"*password*" { send "HzQukan888\r" }
}

# 捕获#
expect "*#"
# 进入常用目录下
send "cd /opt\r"
# 允许用户进行交互
interact

 

 

参考:https://www.cnblogs.com/jiqing9006/p/9209178.html

posted @ 2020-10-14 10:22  ENU  阅读(308)  评论(0编辑  收藏  举报