使用expect脚本自动下载和同步代码

来源:互联网 发布:win10破解版office软件 编辑:程序博客网 时间:2024/06/05 14:14

     刚换了工作,新公司采用git和repo来共同管理代码,不同的cpu型号对应在服务器上有不同的sdk,一来就需要下载这些东西,repo相当于是对git指令的打包集合指令,本来下载一个sdk只需要三条指令,但是需要输入一些东西,我突然想到,为何不是用shell脚本将这三条指令打包,然后每次只需要执行一个脚本就可以去实现下载和同步的功能了。很快我写了个shell脚本,但是发现在指令执行的过程中,需要输入用户名,密码,是否确认(y/n),以我所学到的很基础的shell脚本肯定是不知道,我到网上搜了下,发现有种expect脚本,是专门用来从事交互工作的,好像属于tcl脚本中的,tcl听说过而已,网上随便看了个ssh自动登录的例子,发现语法和shell脚本基本一样,多了spawn,expect,send几个关键字,用来新建线程,等待条件和发送字符的,于是我写了两个代码,down_code用于初次下载代码,sync_code用来同步代码,加入到特定的路径,就可以平时使用一个指令来同步代码。另外在使用前需要apt-get install expect。

down_code代码:

#!/usr/bin/expect 

if { $argc != 2&&$argc != 3 } {
    send_user "Usage ./down 型号 用户名 \[密码\]\n"
    send_user "\t默认密码是空\n"
    exit
}

set mode [ lindex $argv 0 ]
set user [ lindex $argv 1 ]
if { $argc == 3 } {
    set password [ lindex $argv2 ]
} else {
    set password ""
}

set timeout -1

if { $mode == "mtk6517" } {
    spawn repo init -u git@192.168.8.201:alps/manifest.git -m mtk6517-jb-dev.xml
    } elseif { $mode == "mtk6577" } {
    spawn repo init -u git@192.168.8.201:alps/manifest.git -m wm301-v2.0-dev.xml 
    } elseif { $mode == "mtk6589" } {
    spawn repo init -u git@192.168.8.201:alps/manifest.git -m mtk6589-jb2-import.xml
    } else {
    send_user "您输入的型号有误\n"
    exit
    }
    
expect "*Your Name  *:*"
send "$user\n"
expect "*Your Email *:*"
send "$password\n"
expect "is this correct *y/n*"
send "y\n"
expect eof

spawn repo sync
expect eof

if { $mode == "mtk6517" } {
    spawn repo start mtk6517-jb-dev --all
    } elseif { $mode == "mtk6577" } {
    spawn repo start wm301-v2.0-dev --all
    } elseif { $mode == "mtk6589" } {
    spawn repo start mtk6589-jb2-import --all
    } else {
    send_user "您输入的型号有误\n"
    exit
    }
expect eof

exit


sync_code代码:

#!/usr/bin/expect 

if { $argc != 1 } {
    send_user "Usage ./sync_code 型号\n"
    exit
}

set mode [ lindex $argv 0 ]
spawn repo sync
expect eof

if { $mode == "mtk6517" } {
    spawn repo start mtk6517-jb-dev --all
    } elseif { $mode == "mtk6577" } {
    spawn repo start wm301-v2.0-dev --all
    } elseif { $mode == "mtk6589" } {
    spawn repo start mtk6589-jb2-import --all
    } else {
    send_user "您输入的型号有误\n"
    exit
    }
expect eof

exit