Expect概述shell
yum install expect -y 安裝expect服務
Expect基本命令
1.send:向進程發送字符串,用於模擬用戶的輸入數組
expect 「password」 {send 「mypassword」;}
多分支語法結構bash
expect { "aaa"{send "AAA\r"} "bbb"{send "BBB\r"} "ccc"{send "CCC\r"} }
示例:
1.利用expect 完成ssh登陸過程
(1)直接執行服務器
#!/usr/bin/expect set timeout 60 #環境設置 log_flie test.log log_user 1 #變量定義 set hostname [lindex $argv 0] set password [lindex $argv 1] #啓動spawn spawn ssh root@$hostname #匹配條件 expect { "(yes/no)" {send "yes\r";exp_continue} "password" {send "$password\r"} } #權限轉交控制檯 interact
(2)嵌入執行運維
#!/bin/bash hostname=$1 password=$2 /usr/bin/expect<<-EOF spwan ssh root@${hostname} expect{ "(yes/no)" {send "yes\r";exp_continue} "*password" {send "password\r"} } expect "*]#" send "exit\r" expect eof EOF
2.建立用戶tom,密碼tom123ssh
#!/bin/bash user=$1 password=$2 useradd=$user expect<<-EOF spawn passwd $user expect { "New password:" send "${password}\r" "Retype new password:" send "${password}\r" } ecpect eof EOF