How can I create a shell script containing some commands which need user input, for example
#!/bin/sh
useradd test
passwd test
The passwd command needs some input (the password). Can I serve this input via the shell script? Thank you!
The passwd
command is specifically protected against this (I believe in order to reduce it's utility in brute-force password guessing attacks). It reads it's input only from a connected terminal and not from the usual STDIN - this makes it difficult to use it to script password changes.
But see the man page for usermod
passwd
but, in that case, your script doesn't get to see any part of passwd
's user interaction and can't feed password values into passwd
.
Sep 28, 2011 at 13:19
Normally not since most programs which require a password will not read from stdin as regular UNIX processes do. Instead they will try to read in the password from the controlling tty.
If you want to script such applications you will have to use tools like expect.
Example:
$ ./input.sh foo bar baz
Source:
#!/bin/bash
# input.sh
echo $0 # input.sh
echo $1 # foo
echo $3 # baz
$argv[1]
is not valid syntax in bash. $1
is the only proper way.
Sep 28, 2011 at 13:24
Use expect. An example here
#!/usr/bin/expect
set username [lindex $argv 0]
set newpass [lindex $argv 1]
spawn passwd $username
expect {*password:}
send "$newpass\r"
expect {*password:}
send "$newpass\r"