环境

Mac

安装expect

brew install expect

使用

传参

# 表示获取执行脚本命名空格后第一个参数
set user [lindex $argv 0]

实际应用例子

ssh自动登录

#!/usr/bin/expect
set user root
set ipaddress 120.76.xx.xx
set passwd xxx
set timeout 30spawn ssh $user@$ipaddress
expect {"*password:" { send "$passwd\r" }"yes/no" { send "yes\r";exp_continue }
}
interact

#!/usr/bin/expect -f
spawn ssh -p 22 developer@120.76.103.192
expect "*password:"
send "Sound318\r"
interact #操作完成

scp传输例子

#!/usr/bin/expect
set user root
set user host
set pwd 123pwd
set from_path 120.76.xx.xx
set to_path xxxspawn scp $from_path $user@$host:$to_path
expect {"*password:" { send "$pwd\n" }
}
interact

录制脚本

可以使用提供的脚本进行录制

vim autoexpect.exp

#!/usr/bin/expect --
# Name: autoexpect - generate an Expect script from watching a session
#
# Description:
#
# Given a program name, autoexpect will run that program.  Otherwise
# autoexpect will start a shell.  Interact as desired.  When done, exit
# the program or shell.  Autoexpect will create a script that reproduces
# your interactions.  By default, the script is named script.exp.
# See the man page for more info.
#
# Author: Don Libes, NIST
# Date: June 30 1995
# Version: 1.4bset filename "script.exp"
set verbose 1
set conservative 0
set promptmode 0
set option_keys ""proc check_for_following {type} {if ![llength [uplevel set argv]] {puts "autoexpect: [uplevel set flag] requires following $type"exit 1}
}    while {[llength $argv]>0} {set flag [lindex $argv 0]if 0==[regexp "^-" $flag] breakset argv [lrange $argv 1 end]switch -- $flag \"-c" {set conservative 1} "-C" {check_for_following characterlappend option_keys [lindex $argv 0] ctoggleset argv [lrange $argv 1 end]} "-p" {set promptmode 1} "-P" {check_for_following characterlappend option_keys [lindex $argv 0] ptoggleset argv [lrange $argv 1 end]} "-Q" {check_for_following characterlappend option_keys [lindex $argv 0] quoteset argv [lrange $argv 1 end]} "-f" {check_for_following filenameset filename [lindex $argv 0]set argv [lrange $argv 1 end]} "-quiet" {set verbose 0} default {break}
}#############################################################
# Variables    Descriptions
#############################################################
# userbuf    buffered characters from user
# procbuf    buffered characters from process
# lastkey    last key pressed by user
#        if undefined, last key came from process
# echoing    if the process is echoing
############################################################## Handle a character that came from user input (i.e., the keyboard)
proc input {c} {global userbuf lastkeysend -- $cappend userbuf $lastkeyset lastkey $c
}# Handle a null character from the keyboard
proc input_null {} {global lastkey userbuf procbuf echoingsend -nullif {$lastkey == ""} {if $echoing {sendcmd "$userbuf"}if {$procbuf != ""} {expcmd "$procbuf"}} else {sendcmd "$userbuf"if $echoing {expcmd "$procbuf"sendcmd "$lastkey"}            }cmd "send -null"set userbuf ""set procbuf ""set lastkey ""set echoing 0
}# Handle a character that came from the process
proc output {s} {global lastkey procbuf userbuf echoingsend_user -raw -- $sif {$lastkey == ""} {if !$echoing {append procbuf $s} else {sendcmd "$userbuf"expcmd "$procbuf"set echoing 0set userbuf ""set procbuf $s}return}regexp (.)(.*) $s dummy c tailif {$c == $lastkey} {if $echoing {append userbuf $lastkeyset lastkey ""} else {if {$procbuf != ""} {expcmd "$procbuf"set procbuf ""}set echoing 1}append procbuf $sif [string length $tail] {sendcmd "$userbuf$lastkey"set userbuf ""set lastkey ""set echoing 0}} else {if !$echoing {expcmd "$procbuf"}sendcmd "$userbuf$lastkey"set procbuf $sset userbuf ""set lastkey ""set echoing 0}
}# rewrite raw strings so that can appear as source code but still reproduce
# themselves.
proc expand {s} {regsub -all "\\\\" $s "\\\\\\\\" sregsub -all "\r" $s "\\r"  sregsub -all "\"" $s "\\\"" sregsub -all "\\\[" $s "\\\[" sregsub -all "\\\]" $s "\\\]" sregsub -all "\\\$" $s "\\\$" sreturn $s
}# generate an expect command
proc expcmd {s} {global promptmodeif $promptmode {regexp ".*\[\r\n]+(.*)" $s dummy s}cmd "expect -exact \"[expand $s]\""
}# generate a send command
proc sendcmd {s} {global send_style conservativeif {$conservative} {cmd "sleep .1"}cmd "send$send_style -- \"[expand $s]\""
}# generate any command
proc cmd {s} {global fdputs $fd "$s"
}proc verbose_send_user {s} {global verboseif $verbose {send_user -- $s}
}proc ctoggle {} {global conservative send_styleif $conservative {cmd "# conservative mode off - adding no delays"verbose_send_user "conservative mode off\n"set conservative 0set send_style ""} else {cmd "# prompt mode on - adding delays"verbose_send_user "conservative mode on\n"set conservative 1set send_style " -s"}
}proc ptoggle {} {global promptmodeif $promptmode {cmd "# prompt mode off - now looking for complete output"verbose_send_user "prompt mode off\n"set promptmode 0} else {cmd "# prompt mode on - now looking only for prompts"verbose_send_user "prompt mode on\n"set promptmode 1}
}# quote the next character from the user
proc quote {} {expect_user -re .send -- $expect_out(buffer)
}if [catch {set fd [open $filename w]} msg] {puts $msgexit
}
exec chmod +x $filename
verbose_send_user "autoexpect started, file is $filename\n"# calculate a reasonable #! line
set expectpath /usr/local/bin        ;# prepare default
foreach dir [split $env(PATH) :] {    ;# now look for real locationif [file executable $dir/expect] {set expectpath $dirbreak}
}cmd "#![set expectpath]/expect -f
#
# This Expect script was generated by autoexpect on [timestamp -format %c]
# Expect and autoexpect were both written by Don Libes, NIST."
cmd {#
# Note that autoexpect does not guarantee a working script.  It
# necessarily has to guess about certain things.  Two reasons a script
# might fail are:
#
# 1) timing - A surprising number of programs (rn, ksh, zsh, telnet,
# etc.) and devices discard or ignore keystrokes that arrive "too
# quickly" after prompts.  If you find your new script hanging up at
# one spot, try adding a short sleep just before the previous send.
# Setting "force_conservative" to 1 (see below) makes Expect do this
# automatically - pausing briefly before sending each character.  This
# pacifies every program I know of.  The -c flag makes the script do
# this in the first place.  The -C flag allows you to define a
# character to toggle this mode off and on.set force_conservative 0  ;# set to 1 to force conservative mode even if;# script wasn't run conservatively originally
if {$force_conservative} {set send_slow {1 .1}proc send {ignore arg} {sleep .1exp_send -s -- $arg}
}#
# 2) differing output - Some programs produce different output each time
# they run.  The "date" command is an obvious example.  Another is
# ftp, if it produces throughput statistics at the end of a file
# transfer.  If this causes a problem, delete these patterns or replace
# them with wildcards.  An alternative is to use the -p flag (for
# "prompt") which makes Expect only look for the last line of output
# (i.e., the prompt).  The -P flag allows you to define a character to
# toggle this mode off and on.
#
# Read the man page for more info.
#
# -Don}cmd "set timeout -1"
if $conservative {set send_style " -s"cmd "set send_slow {1 .1}"
} else {set send_style ""
}if [llength $argv]>0 {eval spawn -noecho $argvcmd "spawn $argv"
} else {spawn -noecho $env(SHELL)cmd "spawn \$env(SHELL)"
}cmd "match_max 100000"set lastkey ""
set procbuf ""
set userbuf ""
set echoing 0remove_nulls 0eval interact $option_keys {-re . {input $interact_out(0,string)} null {input_null} \-o \-re .+ {output $interact_out(0,string)} eof {cmd "expect eof"return} null {}
}close $fd
verbose_send_user "autoexpect done, file is $filename\n"

执行

# exit退出,会在当前目录生成一个script.exp文件
expect autoexpect.exp -p

自己使用例子

打包、上传dev、备份、重启

#!/usr/local/bin/expect -f
#
# Auto pack, scp, restart app by expect.
#
# Use example:
#   ./pack_dev.sh developer 192.140.12.2 pwd /java/workspace-idea-soundbus/bet-game-service /java/workspace-idea-soundbus/bet-game-service/bet-game/target/bet-game.jar /home/developer/sunbar/bet-game-service/bet-game-$(date +'%Y%m%d').jar bet-game /home/developer/sunbar/bet-game-service
#
# Init env(mac os):
#   brew install expect
#
# Created by suzhida on 2017-08-06 14:47:11set service_user [lindex $argv 0]
set service_ip [lindex $argv 1]
set service_pwd [lindex $argv 2]set pack_path [lindex $argv 3]
set scp_source_path [lindex $argv 4]
set scp_to_path [lindex $argv 5]
set app_name [lindex $argv 6]
set service_app_path [lindex $argv 7]set timeout -1
# bash shell
spawn $env(SHELL)
match_max 100000
expect -exact ""# pack
send -- "cd $pack_path\r"
expect -exact "cd $pack_path"
send -- "mvn clean install -Dskip.unit.tests=true\r"
expect -exact "mvn clean install -Dskip.unit.tests=true"# scp
send -- "scp $scp_source_path $service_user@$service_ip:$scp_to_path\r"
expect -exact "$service_user@$service_ip's password: "
send -- "$service_pwd\r"
expect -exact ""# restart app
send -- "ssh -p 22 $service_user@$service_ip\r"
expect -exact "$service_user@$service_ip's password: "
send -- "$service_pwd\r"
expect -exact ""
send -- "cd $service_app_path\r"
expect -exact ""
send -- "ln -sf $service_app_path-\$(date +'%Y%m%d').jar $service_app_path-current.jar\r"
expect -exact ""
send -- "./boot.sh\r"
expect -exact ""
send -- "tailf log/spring.log\r"
expect -exact ""# done
interact

1) 维基百科介绍
2) 官网
3) 使用expect工具ssh登录远程服务器并执行命令操作
4) expect用法
5) linux expect详解

Mac 自动化执行脚本 Expect相关推荐

  1. Linux开机自动化执行脚本的四种方法(真实案例分享)

    Linux开机自动化执行脚本的四种方法(真实案例分享) 最近眼睛有点疼,可能是长时间面对电脑屏幕的原因罢.百度后安装了Redshift这款护眼工具,只要事先写好配置文件它会根据你的地理位置自动调节屏幕 ...

  2. mac安静执行脚本_让Mac OS X系统启动时执行脚本的方法

    公司购买了Zoho公司的资产管理软件AssetExplorer,该资产管理软件可以通过在客户机电脑上安装Agent客户端软件收集客户机的硬件及软件信息.公司有若干台iMac电脑,运行的是Mac OS ...

  3. mac安静执行脚本_Desktop Goose for Mac在屏幕上到处乱跑的抖音网红桌面宠物鹅

    原标题:Desktop Goose for Mac在屏幕上到处乱跑的抖音网红桌面宠物鹅 最近抖音上火起来的桌面宠物鹅如何获取?这只抖音桌宠鹅可是吸引了大批抖友的眼球,那么今天小编就为大家分享一下Des ...

  4. Mac下使用可执行脚本记录远程服务器账号和密码

    安装工具 brew install expect brew install spawn-fcgi 编写可执行脚本 例如~/.wiwide_dev.sh #!/usr/bin/expect set us ...

  5. 小型自动化运维--expect脚本之自动同步

    小型自动化运维--expect脚本之自动同步 expect脚本可以运用于自动化运维多个方面,例如:可以自动到远程机器执行命令,也可以传输文件到远程机器上. 脚本如下: #!/usr/bin/expec ...

  6. expect自动化交互脚本(一)

    最近在弄ansible的时候,每次使用的时候都要输入密码感觉非常的麻烦,起初是一台一台做无密码验证,但是效率太低.了解到linux是可以批量做部署的,但是需要使用expect脚本来完成. expect ...

  7. linux非交互式脚本,Linux expect非交互式执行脚本

    expect简介 expect是一款自动化的脚本解释型的工具. expect基于tcl脚本,expect脚本的运行需要tcl的支持. expect对一些需要交互输入的命令很有帮助,比如ssh ftp ...

  8. linux ssh非交互脚本,Linux expect非交互式执行脚本

    expect简介 expect是一款自动化的脚本解释型的工具. expect基于tcl脚本,expect脚本的运行需要tcl的支持. expect对一些需要交互输入的命令很有帮助,比如ssh ftp ...

  9. 小型自动化运维--expect脚本之传递函数

    小型自动化运维--expect脚本之传递函数 [root@shiyanji ~]# vim 3.expect #!/usr/bin/expect set user [lindex $argv 0] s ...

最新文章

  1. 从零开始小说 html,从零开始的HTML生活
  2. 关于python类的继承正确的说法是_2017美团点评的运维岗校招笔试题,测测你会几题?...
  3. 3d打印主要的切片参数类型_3D打印机切片参数详情说明
  4. linux awk菜鸟教程,Linux awk 命令
  5. matplotlib 添加偏移量
  6. CHIL-SQL-INNER JOIN 关键字
  7. 望洋兴叹的意思是什么?望洋兴叹造句
  8. split用法与图像预处理
  9. 公专网集群对讲系统在城市执法过程中的应用
  10. openwrt编译smartdns_ubuntu下交叉编译PandoraBox/潘多拉 k2p/mipsel软件openssl和smartdns
  11. 东芝服务器报错误代码维修,实战维修 东芝复印机故障维修详解
  12. cmyk rgb 数值转换_计算机视觉学习笔记2 图像类型转换
  13. 宝塔面板干什么用的?
  14. 【大厂面试】面试官看了赞不绝口的Redis笔记(三)分布式篇
  15. 三角函数的极限和导数
  16. DAX: 用SWITCH函数替换嵌套IF函数
  17. HTTP协议-get与post请求
  18. Redis 总结 —— 2022/2/4
  19. 计算机维修分为那两种,计算机二级维修中最常见的三种方法是什么?
  20. linux升级补丁包,linux 升级补丁

热门文章

  1. 解决Chrome、360自动填充用户名和密码行为带来的困扰
  2. Linux下 QT中 log4cplus 最基本配置及使用
  3. python按概率生成随机数
  4. JVM-内存区域 堆、方法区,虚拟机栈、程序计数器详解
  5. 2007经典搞笑警句
  6. SQL案例学习-数据透视表
  7. 中秋祝福代码,中秋快乐代码,采用H5制作的中秋动画祝福
  8. 图片前后旋转(头像前后旋转)
  9. python获取excel整行数据如何保存到新的工作簿中_如何使用python将大量数据导出到Excel中的小技巧之一...
  10. python爬虫初试-下载LOL全英雄皮肤