2

I am creating a bash script which creates a user and sets a password. When the command "passwd user" is run it requires the user to enter a password and stops my script.

Is there any way to fulfill user input without having the user intervene?

#!/bin/bash

yum -y update
adduser test-user
passwd test-user
"Password here?"
HalosGhost
  • 4,732
  • 10
  • 33
  • 41
user3024130
  • 219
  • 2
  • 4
  • 8

2 Answers2

1

This is a really bad idea, but you can pass the password on standard input:

passwd --stdin test-user <<< "Password here?"
l0b0
  • 50,672
  • 41
  • 197
  • 360
0

Method #1 - using passwd

You can do something like this via a script:

echo -n "$passwd" | passwd "$uname" --stdin

Where the password you want to set is $passwd and the user you want to set it for is $uname.

Method #2 - using useradd

You could also provide it to useradd directly:

useradd -n -M -s $shell -g $group -d "/home/$homedir" "$uname" -p "$passwd"

NOTE: Assuming you're on a Red Hat based distro such as CentOS or RHEL in method #2, since you're example shows yum commands. The -n switch, for example, is in older versions of useradd:

-n  A group having the same name as the user being added to the system 
    will be created by default. This option will turn off this
    Red Hat Linux specific behavior. When this option is used, users by 
    default will be placed in whatever group is specified in
    /etc/default/useradd. If no default group is defined, group 1 will be
    used.

newer versions of useradd now have the option this way on Red Hat and non Red Hat distros:

-N, --no-user-group
    Do not create a group with the same name as the user, but add the 
    user to the group specified by the -g option or by the GROUP 
    variable in /etc/default/useradd.

So you could use this command for other distros:

useradd -N -M -s $shell -g $group -d "/home/$homedir" "$uname" -p "$passwd"
slm
  • 363,520
  • 117
  • 767
  • 871
  • I tried method #2 in Ubuntu Server and received the following. useradd -n -M -s /bin/bash -g test135 -d "/home/testing135" "testing135" -p "testing135" useradd: invalid option -- 'n'. Any ideas? – user3024130 Nov 19 '14 at 22:04
  • @user3024130 - How are you doing `yum` commands in your example if this is an Ubuntu system? the method I showed you was for RH based distros only given your example. – slm Nov 19 '14 at 22:33
  • @user3024130 - see updates. – slm Nov 19 '14 at 22:45