首页 > 技术文章 > ssh shell expect 远程执行 自动输入密码

ah-firelove 2021-01-22 11:45 原文

下面是在centos7 minial环境下测试通过的一段sh脚本,利用expect命令,对远端设备自动执行命令

首先要安装expect

远程执行 ssh -o

ssh -o 'StrictHostKeyChecking no' 'appdeploy@10.71.2.156' -a "uptime"

 

# yum install expect

#cat test.sh

#!/bin/bash
user=root
pass='远端设备口令'
ip=$1
/usr/bin/expect << FLAGEOF
set timeout 2
spawn ssh $user@$ip   
expect {
        "(yes/no)" {send "yes\r"; exp_continue}
        "password:" {send "$pass\r"}
}
expect "root@*"  {send "df -h\r"}
expect "root@*"  {send "yum -y install wget\r";set timeout -1}
expect "root@*"  {send "exit\r"}
expect eof 
FLAGEOF

执行

#sh test.sh 远端设备ip地址

推荐阅读