expect 两种用法

yum install expect -y
#先安装expect

1.测试用法

#!/usr/bin/expect
#解释语言,这边运行要以./运行,bash运行会报错
spawn ssh [email protected]
#启动新的进程
expect "*password:"
#进程接收字符串,匹配
send "yxy7714707@\r"
#前面匹配到了就输入 “ ” 里的内容
expect "*#"
send "ifconfig>>123.txt\r"
send "exit\r"
interact

2.在sh脚本里调用

#!/bin/bash 
ip=$1
#传递参数
user=$2
password=$3
expect <<EOF  
    set timeout 10 
    spawn ssh $user@$ip 
    expect { 
        "yes/no" { send "yes\n";exp_continue } 
        "password" { send "$password\n" }
    } 
        #一个交互用一个expect{} 括起来,这个交互就是登陆的
    expect "]#" { send "date>>123.txt\n" } 
    expect "]#" { send "exit\n" } 
        #退出
expect eof 
EOF 

猜你喜欢

转载自blog.51cto.com/13620944/2440856
今日推荐