魏蓝

以梦为马

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

shell脚本进阶常用工具

1.交互式转化批处理工具expect

让交互式的命令变成非交互式

1)expect默认没有装,需要安装

1
yum -y install expect

2)语法:

1
expect [选项] [-c cmds] [[-[flb]] cmdfiles] [args]

3)常见选项:

-c:从命令执行expect脚本,默认expect是交互执行的

-d:可以调试信息

4)expext中相关命令:

  • spawn 启动新的进程
  • expect 从进程接收字符串
  • send 用于向进程发送字符串
  • interact 允许用户交互
  • exp_continue 匹配多个字符在执行动作后加此命令  

例:非交互式复制文件

1
2
3
4
5
6
7
#!/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

 

 

 

 例:远程登录

1
2
3
4
5
6
7
#!/usr/bin/expect
spawn ssh 192.168.93.141
expect {
        "yes/no" { send "yes\n"; exp_continue }
        "password" { send "JoshuaKimmich\n" }
}
expect eof

 

 例:expect变量

1
2
3
4
5
6
7
8
9
10
11
#!/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位置参数

1
2
3
4
5
6
7
8
9
10
#!/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执行多个命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/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版本

1
bash --version
  • bash的数值支持稀松格式(索引不连续)

 

posted on   魏蓝  阅读(264)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示