1

我想知道如何在 shell 脚本中为命令添加答案。我知道这不是很清楚,因为我不知道如何描述它。例如:

$> su
$> Password: <automatically_fill_in_the_password_here>

如何自动填写密码?

4

1 回答 1

1

expect就是你要找的。

请允许我引用此页面,因为它在解释方面做得很好expect

Expect是一个 Unix 和 Linux 自动化和测试工具。它适用于交互式应用程序,例如telnet, ftp, passwd, fsck, rlogin, tip, ssh, 和许多其他应用程序。它使用 Unix 伪终端透明地包装子进程,允许通过终端访问的任意应用程序的自动化。

下面是一个简单的期望脚本,用于为远程 ssh 服务器提供 OpenSSH 根/管理员密码并执行 Unix / Linux / BSD 命令。(首先,您需要按照这些说明安装 expect 工具。)

#!/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 root@$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

如果一个人没有阅读脚本的评论(你真的应该),这里是如何使用它:

./sshlogin.exp password 192.168.1.11 who 
于 2013-04-15T04:40:10.220 回答