Welcome 微信登录

首页 / 操作系统 / Linux / Linux下Expect命令应用

在安装好expect 和tcl后,我们就可向各个主机中执行相同的命令了,实际上也就是执行的TCL脚本,如下就是一个TCL脚本。expect.tcl脚本逻辑:1) 先SSH到所要的执行命令的主机 ,spawn ssh $user@$hostname2) 然后在执行shell命令,脚本中执行的 是 函数exec_shell_command3)脚本中log 为执行日志函数expect.tcl
  1. #!/usr/local/bin/expect 
  2.  
  3. ###set log file handle 
  4. set timeout 5 
  5. set systemTime [clock seconds] 
  6. set file "tcl.log" 
  7. set fileid [open $file a] 
  8. seek $fileid 0 start 
  9.  
  10. ###set the arguments 
  11. set hostname [lindex $argv 0]    #主机名 
  12. set user [lindex $argv 1]        #用户名 
  13. set passwd [lindex $argv 2]      #密码 
  14.  
  15.  
  16. proc exec_shell_command {} {     #执行命令函数 
  17.     send "rm -f xubc.log " 
  18.     log "commands  completed..." 
  19.  
  20. proc log {msg} {                 #写日志函数 
  21.    global fileid 
  22.    set systemTime [clock seconds] 
  23.    puts $fileid "[clock format $systemTime -format %H:%M:%S] --- $msg" 
  24.  
  25. log "$hostname begin....." 
  26.  
  27. if {$argc != 3} { 
  28.     log $argc 
  29.     log $argv 
  30.     log "Usage: error arguments.  " 
  31. } else { 
  32.     spawn ssh $user@$hostname 
  33.     expect { 
  34.        "yes/no" { send "yes ";exp_continue } 
  35.        "password:" { send "$passwd " } 
  36.     } 
  37.     log "Login $hostname Successfully..." 
  38.     exec_shell_command 
  39. log "exit $hostname..." 
  40. send "exit " 
  41. log "$hostname end... " 
  42. expect eof 
主机名:master 用户:Hadoop  密码:123456执行脚本的命令: expect  expect.tcl  master  hadoop 123456 再有上面的基础脚本后,对于多台服务器配置,我们可以把服务器信息的写入配置文件server.lst
  1. master hadoop 123456 
  2. slave1 hadoop 123456 
  3. slave2 hadoop 123456 
  4. slave3 hadoop 123456 
最后通过一个shell脚本,读取server.lst来完成每台机器的配置,实例中是 创建一个xubc.log的文件
expect.sh
  1. #!/bin/bash 
  2.  
  3. while read line 
  4.   do 
  5.     echo expect expect.tcl $line; 
  6.     expect expect.exp $line 
  7.   done < server.lst 
sh expect.sh  将分别在每台服务器当前用户目录下创建 名为xubc.log 的文件,相关日志文件会在tcl.log中。相关阅读:Linux下Expect命令安装 http://www.linuxidc.com/Linux/2012-10/72761.htmLinux下Expect命令安装HP-UNIX的NFS配置相关资讯      Linux  linux常用命令  Expect  Linux Expect  Expect的用法 
  • 常用的Linux命令  (今 08:47)
  • Linux目录结构和常用命令  (08月29日)
  • 一些 Linux 常用命令说明  (06月04日)
  • Linux 文件与目录的基本常用命令  (09月03日)
  • Linux常用命令札记  (08月14日)
  • Linux系统管理员常用命令实例分析  (04月11日)
本文评论 查看全部评论 (0)
表情: 姓名: 字数