Noah
Noah

Reputation: 97

Add an answer to a command in shell script

I am wondering how to add an answer to a command in a shell script. I know this isn't very clear, as I don't know how to describe it. For example:

$> su
$> Password: <automatically_fill_in_the_password_here>

How would I automatically fill in the password?

Upvotes: 1

Views: 2195

Answers (1)

acdcjunior
acdcjunior

Reputation: 135862

expect is what you are looking for.

Allow me to quote this page, as it does a very good job in explaining expect:

Expect is a Unix and Linux automation and testing tool. It works with interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, ssh, and many others. It uses Unix pseudo terminals to wrap up subprocesses transparently, allowing the automation of arbitrary applications that are accessed over a terminal.

Below is, a simple expect script to supply OpenSSH root/admin password for remote ssh server and execute the Unix / Linux / BSD commands. (First, you need to 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

In cas one didn't read the script's comments (you really should), here's how to use it:

./sshlogin.exp password 192.168.1.11 who 

Upvotes: 1

Related Questions