简体   繁体   中英

Using the passwd command from within a shell script

I'm writing a shell script to automatically add a new user and update their password. I don't know how to get passwd to read from the shell script instead of interactively prompting me for the new password. My code is below.

adduser $1
passwd $1
$2
$2

from " man 1 passwd<\/code> ":

   --stdin
          This option is used to indicate that passwd should read the new
          password from standard input, which can be a pipe.

The only solution works on Ubuntu 12.04:

echo -e "new_password\nnew_password" | (passwd user)

现在,您可以使用以下命令:

echo "user:pass" | chpasswd

For those who need to 'run as root' remotely through a script logging into a user account in the sudoers file, I found an evil horrible hack, that is no doubt very insecure:

sshpass -p 'userpass' ssh -T -p port user@server << EOSSH
sudo -S su - << RROOT
userpass
echo ""
echo "*** Got Root ***"
echo ""
#[root commands go here]
useradd -m newuser
echo "newuser:newpass" | chpasswd
RROOT
EOSSH

Here-document<\/em> works if your passwd<\/code> doesn't support --stdin<\/code> and you don't want to (or can't) use chpasswd<\/code> for some reason.

#!/usr/bin/env bash

username="user"
password="pass"

passwd ${username} << EOD
${password}
${password}
EOD

你可以使用 chpasswd

echo $1:$2 | chpasswd<\/code>

"

Tested this on a CentOS VMWare image that I keep around for this sort of thing. Note that you probably want to avoid putting passwords as command-line arguments, because anybody on the entire machine can read them out of 'ps -ef'.

user="$1"
password="$2"
adduser $user
echo $password | passwd --stdin $user

Sometimes it is useful to set a password which nobody knows. This seems to work:

tr -dc A-Za-z0-9 < /dev/urandom | head -c44 | passwd --stdin $user

I stumbled upon the same problem and for some reason the --stdin<\/code> option was not available on the version of passwd<\/code> I was using (shipped in Ubuntu 14.04).

echo "<user>:<password>" | chpasswd

This is the definitive answer for a teradata node admin.

SMP007-1
SMP007-2
SMP007-3

For me on Raspbian it works only this way (old password added):

#!/usr/bin/env bash

username="pi"
password="Szevasz123"
new_ps="Szevasz1234"

passwd ${username} << EOD
${password}
${new_ps}
${new_ps}
EOD

echo 'yourPassword' | sudo -S yourCommand

<\/blockquote>

Have you looked at the -p<\/code> option of adduser<\/code> (which AFAIK is just another name for useradd<\/code> )? You may also want to look at the -P<\/code> option of luseradd<\/code> which takes a plaintext password, but I don't know if luseradd<\/code> is a standard command (it may be part of SE Linux or perhaps just an oddity of Fedora).

"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM