shell脚本进阶常用工具
1.交互式转化批处理工具expect
让交互式的命令变成非交互式
1)expect默认没有装,需要安装
yum -y install expect
2)语法:
expect [选项] [-c cmds] [[-[flb]] cmdfiles] [args]
3)常见选项:
-c:从命令执行expect脚本,默认expect是交互执行的
-d:可以调试信息
4)expext中相关命令:
- spawn 启动新的进程
- expect 从进程接收字符串
- send 用于向进程发送字符串
- interact 允许用户交互
- exp_continue 匹配多个字符在执行动作后加此命令
例:非交互式复制文件
#!/usr/bin/expect spawn scp /etc/redhat-release 192.168.93.141:/data expect{ "yes/no" { send "yes\n"; exp_continue } "password" { send "JoshuaKimmich\n" } } expect eof
例:远程登录
#!/usr/bin/expect spawn ssh 192.168.93.141 expect { "yes/no" { send "yes\n"; exp_continue } "password" { send "JoshuaKimmich\n" } } expect eof
例:expect变量
#!/usr/bin/expect set ip 192.168.93.141 set user root set password WeiLan set timeout 10 spawn ssh $user@$ip expect { "yes/no" { send "yes\n"; exp_continue } "password" { send "$password\n" } } interact
例:expect位置参数
#!/usr/bin/expect set ip [ lindex $argv 0 ] set user [ lindex $argv 1 ] set password [ lindex $argv 2 ] spawn ssh $user@$ip expect { "yes/no" { send "yes\n"; exp_continue } "password" { send "$password\n" } } interact
注意这里的“[lindex $argv 0] 相当于$1以此类推
例:expect执行多个命令
#!/usr/bin/expect set ip [ lindex $argv 0 ] set user [ lindex $argv 1 ] set password [ lindex $argv 2 ] set timeout 10 spawn ssh $user@$ip expect { "yes/no" { send "yes\n"; exp_continue } "password" { send "$password\n" } } expect "]#" { send "useradd haha\n" } expect "]#" { send "echo weilan | passwd --stain haha\n" } send "exit\n" expect eof
例:shell脚本调用用expect
#!/bin/bash ip=$1 user=$2 password=$3 expect << EOF set timeout 20 spawn ssh $user@$$ip expect { "yes/no" { send "yes\n; exp_continue" } "password" { send "$password } } expect "]#" { send "useradd hehe\n" } expect "]#" { send "echo weilan99999999 | passwd hehe\n" } expect "]#" { send "exit\n" } expect eof EOF
2.数组array简单介绍
1)存储多个元素的连续内存空间,多个变量的集合
2) 三种索引
- 索引的编号从0开始,属于数值索引
- 索引可支持使用自定义的格式,而不仅是数值格式,即为关联索引,bash4.0版本之后开始支持
查看bash版本
bash --version
- bash的数值支持稀松格式(索引不连续)