自动登录expect脚本实例图文教程-演道网

简介:

1.expect的讲解

2.实例操作自动登录脚本

expect讲解

expect可以让我们实现自动登录远程机器,并且可以实现自动远程执行命令。当然若是使用不带密码的密钥验证同样可以实现自动登录和自动远程执行命令。但当不能使用密钥验证的时候,我们就没有办法了。所以,这时候只要知道对方机器的账号和密码就可以通过expect脚本实现登录和远程命令。

Expect中最关键的四个命令是send,expect,spawn,interact。

send:用于向进程发送字符串
expect:从进程接收字符串
spawn:启动新的进程
interact:允许用户交互

1. send命令

send命令接收一个字符串参数,并将该参数发送到进程。

expect1.1> send “hello worldn”hello world

2. expect命令

expect命令和send命令正好相反,expect通常是用来等待一个进程的反馈。expect可以接收一个字符串参数,也可以接收正则表达式参数。

expect “hin”send “hello there!n”

这两行代码的意思是:从标准输入中等到hi和换行键后,向标准输出输出hello there

3. spawn命令

上文的所有demo都是和标准输入输出进行交互,但是我们跟希望他可以和某一个进程进行交互。spawm命令就是用来启动新的进程的。

set timeout -1spawn ftp ftp.test.com      //打开新的进程,该进程用户连接远程ftp服务器

expect “Name”            //进程返回Name时

send “userr”        //向进程输入

anonymousrexpect “Password:”        //进程返回Password:时

send “123456r”    //向进程输入don@libes.comr

expect “ftp> ”            //进程返回ftp>时

send “binaryr”          //向进程输入binaryr

expect “ftp> ”            //进程返回ftp>时

send “get test.tar.gzr”  //向进程输入get test.tar.gzr

4.interact

到现在为止,我们已经可以结合spawn、expect、send自动化的完成很多任务了。但是,如何让人在适当的时候干预这个过程了。比如下载完ftp文件时,仍然可以停留在ftp命令行状态,以便手动的执行后续命令。interact可以达到这些目的。下面的demo在自动登录ftp后,允许用户交互。

spawn ftp ftp.test.com

expect “Name”

send “userr”

expect “Password:”

send “123456r”

interact

2台主机

服务端:back :192.168.19.134

客户端:other:192.168.19.135

服务端操作

1.使用expect之前,需要先安装expect:

yum install -y expect

安装ssh

yum install openssh-server -y

yum -y install openssh-clients

2.新建一个自动登录脚本文件

格式:

      spawn ssh -l username 192.168.1.1

expect{

      “(yes/no)?” { send “yes”; exp_continue}

      “password:” {send “AAAA”}

        }

 interact

vim login.expect

#! /usr/bin/expect

#about login

#written by lizheng

set host “192.168.19.135”

set passwd “lizheng123”

spawn ssh  root@$host

expect {

    “yes/no” { send “yesr”; exp_continue}

    “password:” { send “$passwdr” }

  }

interact

spacer.gif

3.更改权限

chmod +x login.expect

4.执行脚本语句

./login.expect

输入客户机的密码即可登录

5.退出

logout

转载自演道,想查看更及时的互联网产品技术热点文章请点击http://go2live.cn