Shell 脚本

近期在别人的工作基础上完善了几个shell自动安装脚本。

1. 循环远程访问机器并安装

#!/bin/bash

IpPrefix=52.1.123.
User=root
Pwd=11111111
SMNIP=52.1.123.79

for((i=84;i<100;i++))
do
        echo $IpPrefix$i
        ./remote.exp $IpPrefix$i $User $Pwd $SMNIP
done

remote.exp脚本如下:

#!/usr/local/bin/expect -f

set timeout -1

set IpAddr [lindex $argv 0]
set User [lindex $argv 1]
set Pwd [lindex $argv 2]
set SMNIP [lindex $argv 3]

spawn ssh $User@$IpAddr "cd /usr/;mkdir lihuan"
expect  {
        "yes/no" { send "yes
"; expect "*assword:" { send "$Pwd
" } }
        "*assword:*" { send "$Pwd
"; }
}
expect eof

spawn scp -r computingNodeInstall $User@$IpAddr:/usr/lihuan/
expect "*assword:*" { send "$Pwd
"; }
expect eof

spawn scp -r install $User@$IpAddr:/home/
expect "*assword:*" { send "$Pwd
"; }
expect eof

spawn ssh $User@$IpAddr "cd /home/install;./install.sh;"
expect "*assword:*" { send "$Pwd
"; }
expect "*install finished*" { send 003 }
expect eof

spawn ssh $User@$IpAddr "cd /usr/lihuan/computingNodeInstall;./install.sh $SMNIP;"
expect "*assword:*" { send "$Pwd
"; }
expect eof

2. expect 用法

1. [#!/usr/bin/expect]

这一行告诉操作系统脚本里的代码使用那一个shell来执行。这里的expect其实和linux下的bash、windows下的cmd是一类东西。

注意:这一行需要在脚本的第一行。

2. [set timeout 30]

基本上认识英文的都知道这是设置超时时间的,现在你只要记住他的计时单位是:秒   。timeout -1 为永不超时

3. [spawn ssh -l username IP]

spawn是进入expect环境后才可以执行的expect内部命令,如果没有装expect或者直接在默认的SHELL下执行是找不到spawn命令的。所以不要用 “which spawn“之类的命令去找spawn命令。好比windows里的dir就是一个内部命令,这个命令由shell自带,你无法找到一个dir.com 或 dir.exe 的可执行文件。

它主要的功能是给ssh运行进程加个壳,用来传递交互指令。

4. [expect "password:"]

这里的expect也是expect的一个内部命令,有点晕吧,expect的shell命令和内部命令是一样的,但不是一个功能,习惯就好了。这个命令的意思是判断上次输出结果里是否包含“password:”的字符串,如果有则立即返回,否则就等待一段时间后返回,这里等待时长就是前面设置的30秒

5. [send "ispass "]

这里就是执行交互动作,与手工输入密码的动作等效。

温馨提示: 命令字符串结尾别忘记加上“ ”,如果出现异常等待的状态可以核查一下。

6. [interact]

执行完成后保持交互状态,把控制权交给控制台,这个时候就可以手工操作了。如果没有这一句登录完成后会退出,而不是留在远程终端上。如果你只是登录过去执行

7.$argv 参数数组

expect脚本可以接受从bash传递过来的参数.可以使用[index $argv n]获得,n从0开始,分别表示第一个,第二个,第三个....参数

8.命令行参数

expect的命令行参数参考了c语言的,与bash shell有点不一样。其中,$argc为命令行参数的个数,$argv0为脚本名字本身,$argv为命令行参数。[range $argv 0 0]表示第1个参数,[lrange $argv 0 4]为第一个到第五个参数。与c语言不一样的地方在于,$argv不包含脚本名字本身。

9.exp_continue的用法

#!/usr/bin/expect -f
set ipaddr "localhost"
set passwd "iforgot"
spawn ssh root@$ipaddr              #spawn   意思是执行命令,expect内命令,shell中不存在
expect {
"yes/no" { send "yes
"; exp_continue}
"password:" { send "$passwd
" }
}
expect "]# "
send "touch a.txt
"                       #意思为发送命令
send "exit
"
expect eof
exit
exp_continue可以继续执行下面的匹配,简单了许多。

原文地址:https://www.cnblogs.com/dorothychai/p/4375676.html