やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

CLIの入力を自動化する(expect)

 rsyncのパスワード等、これですべて自動化できる。

成果物

概要

 CLIにはしばしば以下のような入力を促す項目がある。

インストールする? (Y/n) > 
パスワードを入力しろ: 

 これに阻まれて自動化できない。今回はこれを自動化すべくexpectを導入する。

手順

 インストールする。

sudo apt install expect -y

 rsyncで使ってみる。

UN=pi
IP=192.168.11.51
PW=raspberry
FROM=/tmp/work/a.txt
TO=/tmp/work
time expect -c "
  spawn rsync -auvzP -e ssh \"$FROM\" $UN@$IP:\"$TO\"
  expect \"Password:\"
  send \"$PW\n\"
  interact
"
spawn rsync -auvzP -e ssh /tmp/work/a.txt pi@192.168.11.51:"/tmp/work"
pi@192.168.11.51's password: 
sending incremental file list

sent 52 bytes  received 12 bytes  6.10 bytes/sec
total size is 12  speedup is 0.19

real  0m9.614s
user  0m0.019s
sys   0m0.000s
pi@raspberrypi:/tmp/work $ 

 成功。10秒くらいかかったが。

失敗

 rustをインストールするとき、以下を手動で入力せねばならない。これを自動化したかった。

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation
>

 だが、以下のようにしてもcurlのエラーに阻まれてしまった。

expect -c "
  spawn curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  expect \">\"
  send \"1\n\"
  interact
"
spawn curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
curl: option --proto: is badly used here
curl: try 'curl --help' or 'curl --manual' for more information
send: spawn id exp4 not open
    while executing
"send "1\n""

man

所感

 自動化が捗る。でもコマンドが難しすぎる。思うように自動化できない。

対象環境

$ uname -a
Linux raspberrypi 4.19.97-v7l+ #1294 SMP Thu Jan 30 13:21:14 GMT 2020 armv7l GNU/Linux