0

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!

4 Answers 4

1

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

3
  • So this is theoretically possible but especially not for setting passwords?
    – strauberry
    Sep 28, 2011 at 13:15
  • Yes, you can write a script that prompts for user input and which reads that user input into a variable. You can also write an interactive script that invokes 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
  • @strauberry: Answer updated Sep 28, 2011 at 13:22
2

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.

1

Example:

$ ./input.sh foo bar baz

Source:

#!/bin/bash
# input.sh

echo $0       # input.sh
echo $1       # foo
echo $3       # baz
4
  • So I could do something like this: passwd test echo $2 ?
    – strauberry
    Sep 28, 2011 at 13:12
  • 1
    As answered by the others, no, this script is just to show how you can pass arguments into the script.
    – Jin
    Sep 28, 2011 at 13:18
  • $argv[1] is not valid syntax in bash. $1 is the only proper way. Sep 28, 2011 at 13:24
  • @grawity Thanks, fixed. Silly me, I've been using zsh.
    – Jin
    Sep 28, 2011 at 13:25
0

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" 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .