Linux下 expect命令【应用】

来源:互联网 发布:网络用语996什么意思 编辑:程序博客网 时间:2024/05/18 00:11

上一篇   Linux下 expect命令【安装】

在安装好expect 和tcl后,我们就可向各个主机中执行相同的命令了,实际上也就是执行的TCL脚本

如下就是一个TCL脚本,相关语法参见 http://www.tcl.tk/man/tcl/tutorial/tcltutorial.html

expect.tcl脚本逻辑:

  1) 先SSH到所要的执行命令的主机 ,spawn ssh $user@$hostname

  2) 然后在执行shell命令,脚本中执行的 是 函数exec_shell_command

  3)脚本中log 为执行日志函数

expect.tcl

#!/usr/local/bin/expect###set log file handleset timeout 5set systemTime [clock seconds]set file "tcl.log"set fileid [open $file a]seek $fileid 0 start###set the argumentsset hostname [lindex $argv 0]    #主机名set user [lindex $argv 1]        #用户名set passwd [lindex $argv 2]      #密码proc exec_shell_command {} {     #执行命令函数    send "rm -f xubc.log\r"    log "commands  completed..."}proc log {msg} {                 #写日志函数   global fileid   set systemTime [clock seconds]   puts $fileid "[clock format $systemTime -format %H:%M:%S] --- $msg"}log "$hostname begin....."if {$argc != 3} {    log $argc    log $argv    log "Usage: error arguments.\n "} else {    spawn ssh $user@$hostname    expect {       "yes/no" { send "yes\r";exp_continue }       "password:" { send "$passwd\r" }    }    log "Login $hostname Successfully..."    exec_shell_command}log "exit $hostname..."send "exit\r"log "$hostname end... "expect eof

主机名:master   用户:hadoop  密码:123456

执行脚本的命令: 

expect  expect.tcl  master  hadoop 123456

再有上面的基础脚本后,对于多台服务器配置,我们可以把服务器信息的写入配置文件

server.lst

master hadoop 123456slave1 hadoop 123456slave2 hadoop 123456slave3 hadoop 123456

最后通过一个shell脚本,读取server.lst来完成每台机器的配置,实例中是 创建一个xubc.log的文件
expect.sh

#!/bin/bashwhile read line  do    echo expect expect.tcl $line;    expect expect.exp $line  done < server.lst

sh expect.sh  将分别在每台服务器当前用户目录下创建 名为xubc.log 的文件,相关日志文件会在tcl.log中


原创粉丝点击