我在想如何在shell腳本中添加對命令的回答。我知道這不是很清楚,因爲我不知道如何描述它。例如:在shell腳本中添加對命令的回答
$> su
$> Password: <automatically_fill_in_the_password_here>
我將如何自動填寫密碼?
我在想如何在shell腳本中添加對命令的回答。我知道這不是很清楚,因爲我不知道如何描述它。例如:在shell腳本中添加對命令的回答
$> su
$> Password: <automatically_fill_in_the_password_here>
我將如何自動填寫密碼?
expect
是你在找什麼。
允許我引用this page,因爲它在解釋expect
做了很好的工作:
期待是Unix和Linux自動化和測試工具。它適用於交互式應用程序,如
telnet
,ftp
,passwd
,fsck
,rlogin
,tip
,ssh
和許多其他。它使用Unix僞終端透明地包裝子過程,允許通過終端訪問任意應用程序的自動化。
下面是一個簡單的期望腳本,用於爲遠程SSH服務器提供OpenSSH root/admin密碼並執行Unix/Linux/BSD命令。 (首先,你需要install expect tool by following these instructions)
#!/usr/bin/expect -f
# Expect script to supply root/admin password for remote ssh server
# and execute command.
# This script needs three argument to(s) connect to remote server:
# password = Password of remote UNIX server, for root user.
# ipaddr = IP Addreess of remote UNIX server, no hostname
# scriptname = Path to remote script which will execute on remote server
# For example:
# ./sshlogin.exp password 192.168.1.11 who
# ------------------------------------------------------------------------
# Copyright (c) 2004 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# ----------------------------------------------------------------------
# set Variables
set password [lrange $argv 0 0]
set ipaddr [lrange $argv 1 1]
set scriptname [lrange $argv 2 2]
set arg1 [lrange $argv 3 3]
set timeout -1
# now connect to remote UNIX box (ipaddr) with given script to execute
spawn ssh [email protected]$ipaddr $scriptname $arg1
match_max 100000
# Look for passwod prompt
expect "*?assword:*"
# Send password aka $password
send -- "$password\r"
# send blank line (\r) to make sure we get back to gui
send -- "\r"
expect eof
在CAS一個沒有看過劇本的意見(你真的應該),這裏是如何使用它:
./sshlogin.exp password 192.168.1.11 who
謝謝!唯一的缺點是,它本身不能在Mac上工作,(我不這麼認爲),但我確信Macports有一個端口。如果我要分發一個項目,我需要在計算機上安裝它,對嗎?謝謝, – Noah
更大的問題是爲什麼你需要?你想做什麼?自動填寫密碼是個不錯的主意。幾乎總是有更好的方法。 –
@JohnKugelman這是一個例子,我想填寫別的東西。 – Noah
'su'是一個特例。它直接從終端設備讀取而不是標準輸入,因此您無法通過管道訪問它。你需要像'expect'這樣的東西。 – FatalError