onvno / pokerface

日常技术文章阅读整理
3 stars 0 forks source link

20190611 - Expect及可执行脚本 #39

Open onvno opened 5 years ago

onvno commented 5 years ago

双击可执行脚本

默认脚本会直接打开,可以使用创建command后缀文件,写入脚本,然后

$ chmod +x file.command

即可实现双击执行

By default, *.sh files are opened in a text editor (Xcode or TextEdit). To create a shell script that will execute in Terminal when you open it, name it with the “command” extension, e.g., file.command. By default, these are sent to Terminal, which will execute the file as a shell script.

打开是默认自带的shell,可以通过添加前缀选择使用自己享用的shell

Note that the script does not have to begin with a #! prefix in this specific scenario, because Terminal specifically arranges to execute it with your default shell. (Of course, you can add a #! line if you want to customize which shell is used or if you want to ensure that you can execute it from the command line while using a different shell.)

Also note that Terminal executes the shell script without changing the working directory. You’ll need to begin your script with a cd command if you actually need it to run with a particular working directory.

How do I make this file.sh executable via double click?

expect脚本

#!/usr/bin/expect -f
set user your_name
set host your_host_address
set password your_password
# 用于设置timeout
set timeout -1

spawn ssh $user@$host

# 根据输入内容进行交互
expect "key*"
stty -echo
expect_user -timeout 36000 -re "(.*)\[\r\n]"
stty echo
send "$expect_out(1,string)\r"

expect "*assword*"
send "$password\r"

expect "root"
send "cd /home/user\r"

expect "root"
send "git pull\r"

expect "root"
send "pm2 restart\r"

# interact用于交互,可以支持后续操作
interact
expect eof

expect基本说明

2

表示说进行若干次各自的匹配,所有的匹配被依次满足了之后才算整个语句完成。这一点就和前面说的tcl的命令解析方式有关了,因为第一种格式虽然占用的行数多,但是它是一个单独的expect命令,所以expect可以一次性将所有情况解析出来,然后组成一个大的并行分支;对于第二种,expect看到的只是多条单独的expect匹配,根据每个expect必须又一次匹配的原则,需要有多次匹配。总之简单的说,一个是并行关系,一个串行关系

expect pattern command expect pattern2 command2

3

它的意义同样是完成一次匹配,并且匹配之后不执行任何动作,同样是只要不匹配就继续执行。

expect pattern


* expect字符匹配:
> ?:匹配一个字符,a?d匹配abd但不匹配abcd
[]:匹配它范围内的任意字符
[abcdef0123456789]能匹配任意十六进制数,也可以写成[a-f0-9]。
如果要匹配短横杠-,要将其写在最前或者最后,例如[-a-c]匹配-,a,b,c
因为中括号[]也是特殊的expect的字符,它里面的式子要立刻求值,所以[]样式必须写成下面两种方式:
expect "\[a-f0-9]",推荐使用
expect {[a-f0-9]},会出现预想不到的情况,因为里面所有的值都不会进行运算
也可以括号的第二部分加\,但这不是必须的
斜杠:太复杂,举例:
* spawn命令用于启动一个进程
* interact命令用于脚本执行完简单的命令后人手动介入,只在所属的spawn进程空间有效
* set timeout INTERGER:超时值可以设置,如果为-1表示永久等待,如果为0表示立即返回
* eof:结束。不仅可以从process送往expect,也可以从expect送往process,使process退出,在expect脚本中用close显式结束一个进程,通常情况下,process和expect一个结束了,另一个也会随之结束。
* 屏蔽显示
stty -echo #禁止回显
stty echo #打开回显

#### 一些实例
* [expect - 自动交互脚本](http://xstarcd.github.io/wiki/shell/expect.html):登录SSH,FTP

#### 参考
* [expect(1) - Linux man page](https://linux.die.net/man/1/expect): Linux expect文档
* [expect说明](http://xstarcd.github.io/wiki/shell/expect_description.html):一个中文文档
* [Linux Expect 简介和使用实例](https://www.jianshu.com/p/70556b1ce932)