Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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!

share|improve this question

4 Answers 4

up vote 1 down vote accepted

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

share|improve this answer
    
So this is theoretically possible but especially not for setting passwords? –  strauberry Sep 28 '11 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. –  RedGrittyBrick Sep 28 '11 at 13:19
    
@strauberry: Answer updated –  RedGrittyBrick Sep 28 '11 at 13:22

Example:

$ ./input.sh foo bar baz

Source:

#!/bin/bash
# input.sh

echo $0       # input.sh
echo $1       # foo
echo $3       # baz
share|improve this answer
    
So I could do something like this: passwd test echo $2 ? –  strauberry Sep 28 '11 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 '11 at 13:18
    
$argv[1] is not valid syntax in bash. $1 is the only proper way. –  grawity Sep 28 '11 at 13:24
    
@grawity Thanks, fixed. Silly me, I've been using zsh. –  Jin Sep 28 '11 at 13:25

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.

share|improve this answer

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" 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.