在shell脚本中添加命令的答案

时间:2013-04-15 02:48:06

标签: shell

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

$> su
$> Password: <automatically_fill_in_the_password_here>

我如何自动填写密码?

1 个答案:

答案 0 :(得分:1)

expect正是您要找的。

请允许我引用this page,因为它在解释expect方面做得非常好:

  

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

下面是一个简单的expect脚本,为远程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 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

在cas中没有读过脚本的评论(你真的应该),以下是如何使用它:

./sshlogin.exp password 192.168.1.11 who