经常需要把服务器的某些文件传到 Mac,或者获取 Mac 的一些文件到服务器。尽管有很多命令scp, ftp, rsync都可以,霸特每次都有敲好长的命令,好烦,而且还要输入密码。所以想着 wrap 到 expect 脚本这样密码什么的都不用输入了。
下面这个是放在服务器端的,用于把file/folder 传到 Mac
#!/usr/bin/expect
#file: _getF.expect
# 和 Bash 的变量一样
# 定义时不加$,用的时候加
set host xxxx@00.000.00.00
set fromWhere [lindex $argv 0]
set toWhere [lindex $argv 1]
#服务器端目录变量
if { $toWhere == "desktop" } {
set toWhere "/home/rayleo/Desktop/"
} elseif { $toWhere == "downloads" } {
set toWhere "/home/rayleo/Downloads/"
} elseif { $toWhere == "home" } {
set toWhere "/home/rayleo/"
} else {
set toWhere $toWhere
}
spawn scp -r -p "$host:$fromWhere" "$toWhere"
expect "assword:"
send "wwlcr\r"
interact
本来想服务器端和本地的一些常用变量可以用变量代替,
为了不被 Bash 在命令行解析,需要把$放在单引号或者\
转意
但是传进来的变量无法被再次解析,I haven't figure out why yet
例如
putF $desktop/lensid/conf.mout desktop
把服务器端桌面的 lensid/conf.mout 文件 传到自己的 Mac桌面
传进来的$desktop 就无法解析了
单引号是同样的情况
can you tell me why? mail
不能解析就绕呗,所以就想到用一个 bash wrapper来处理,再传给 expect
用 Bash字符串替换
#!/bin/bash
#file: getF.bash
#获取参数
fromWhere=$1
toWhere=$2
#解析Mac变量
home=/Users/ruili
desktop=/Users/ruili/Desktop
downloads=/Users/ruili/Downloads
desk=/Users/ruili/YunPan/DeskFolder
fromWhere=${fromWhere//\$desktop/$desktop}
fromWhere=${fromWhere//\$desk/$desk}
fromWhere=${fromWhere//\$downloads/$downloads}
fromWhere=${fromWhere//\$home/$home}
# 服务器本地变量
lhome=/home/rayleo
ldesktop=/home/rayleo/Desktop
ldownloads=/home/rayleo/Downloads
toWhere=${toWhere//\$desktop/$ldesktop}
toWhere=${toWhere//\$downloads/$ldownloads}
toWhere=${toWhere//\$home/$lhome}
#传给 expect
/usr/bin/expect $HOME/Bin/bin/_getF "$fromWhere" $toWhere
下面的是 putF (pushF) ;把文件从服务器推到 Mac 端
#!/usr/bin/expect
#_putF.expect
#定义变量
set host xxxxxxx@00.000.00.00
set fromWhere [lindex $argv 0]
set toWhere [lindex $argv 1]
set desktop "/Users/ruili/Desktop/"
set downloads "/Users/ruili/Downloads/"
set home "/Users/ruili/"
#为单特殊目录替换
if { $toWhere == "desktop" } {
set toWhere "/Users/ruili/Desktop/"
} elseif { $toWhere == "downloads" } {
set toWhere "/Users/ruili/Downloads/"
} elseif { $toWhere == "desk" } {
set toWhere "/Users/ruili/YunPan/DeskFolder/"
} else {
set toWhere $toWhere
}
#执行
spawn scp -r -p "$fromWhere" "$host:$toWhere"
expect "assword:"
send "wwlcr\r"
interact
Bash wrapper
#!/bin/bash
#file: putF.bash
fromWhere=$1
toWhere=$2
home=/Users/ruili
desktop=/Users/ruili/Desktop
downloads=/Users/ruili/Downloads
desk=/Users/ruili/YunPan/DeskFolder
toWhere=${toWhere//\$desktop/$desktop}
toWhere=${toWhere//\$desk/$desk}
toWhere=${toWhere//\$downloads/$downloads}
toWhere=${toWhere//\$home/$home}
lhome=/home/rayleo
ldesktop=/home/rayleo/Desktop
ldownloads=/home/rayleo/Downloads
fromWhere=${fromWhere//\$desktop/$ldesktop}
fromWhere=${fromWhere//\$downloads/$ldownloads}
fromWhere=${fromWhere//\$home/$lhome}
/usr/bin/expect $HOME/Bin/bin/_putF $fromWhere $toWhere
现在可以putF \$downloads/google.dmg desktop
把/home/$USER/Downloads 底下的 google.dmg 文件传到 Mac 的桌面getF \$desktop/bt2_bf_PE.fq \$desktop/../QTL
把 Mac 桌面的bt2_bf_PE.fq文件传到服务的和桌面同级的 QTL 文件