shell指令碼進階常用工具
阿新 • • 發佈:2022-03-09
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的數值支援稀鬆格式(索引不連續)