Expect
#!/usr/bin/expect
set timeout 5
spawn sudo dnf install vim
expect "Is this ok"
send "y\n"
expect "\\\$"
- spawn コマンドでプロセス起動
- spawnのコマンドは囲わない
- expect プロセスに対して待機
- send expectがマッチする時入力
- interact 制御をユーザーへ渡す
実行
expect file.tcl
多段の場合
#!/usr/bin/expect -f
set prompt "(%|#|\\$) $"
spawn passwd
expect {
"Current password:" {
send "CURRENT PASSWORD\n"
exp_continue
}
"ew password:" {
send "NEW PASSWORD\n"
exp_continue
}
eof{
exit
}-re $prompt
}
変数
set v "value"
puts ${v}
expectのインストール方法
dnf -y install expect
おまけ
一般ユーザーで、好きなだけパスワードを変更するシェル
#!/usr/bin/env bash
# 変更回数
change_count=40
# 現在のパスワードを設定
current_password=""
# 新しいパスワードをランダムに生成する関数
generate_password() {
local chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
local length=12
local password=""
for (( i = 0; i < length; i++ )); do
password+="${chars:RANDOM%${#chars}:1}"
done
echo "$password"
}
# パスワード変更処理
for (( i = 1; i <= change_count; i++ )); do
# 新しいパスワードを生成
new_password=$(generate_password)
# expectスクリプトでパスワードを変更
expect <<EOF
spawn passwd
expect "Current password:"
send "$current_password\r"
expect "New password:"
send "$new_password\r"
expect "Retype new password:"
send "$new_password\r"
expect eof
EOF
# パスワード変更の結果を表示
if [ $? -eq 0 ]; then
echo "Password change #$i: Success - New password is $new_password"
# 次の変更に備えて現在のパスワードを更新
current_password="$new_password"
else
echo "Password change #$i: Failed"
fi
done