expect可以帮助脚本完成自动化。今天就用二种实例来介绍2种写法。

 

安装 

yum -y install expect

 

一、直接用/usr/bin/expect 这种就不方便调用linux下的环境变量了。 

#!/usr/bin/expect
set User root       #expect位tcl语言、所以里面的格式或者变量都和tcl语言相关咯 Author:V    
set Host 192.168.0.160
set Passwd 123456
spawn ssh $User@$Host     #spawn 为执行语句块
expect  "*yes/no)?"   { send "yes\r" }        #expect为检测输出 这里可以使用正则         send为检测到右yes/no就发送yes并\r
expect  "*password:"  { send "$Passwd\r" }
expect  "#*"          { send "pwd\r"}
interact                  #交互
        

 执行结果如下

 

二、

#!/bin/bash

User=root
Host=192.168.0.82
Passwd=yingzi
#interact

expect<< SYW
spawn ssh $User@$Host
expect  "*yes/no)?"   { send "yes\r" }
expect  "*password:"  { send "$Passwd\r" }
expect  "#*"          { send "pwd\r"}
interact
SYW

 这个有点问题不能持续性交互。有大神知道的话,请告知