Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 362
Jared Avatar asked Apr 03 '09 17:04

Jared


People also ask

How do I pass a password to passwd command?

passwd -l <username> The -l option is used to lock the password of a specified account, and it is available to root only. The result is that the user cannot use the password to log in to the system but can use other means such as SSH public key authentication.

How do you put a password on a Linux script?

#!/bin/bash echo "Enter Username : " # read username and echo username in terminal read username echo "Enter Password : " # password is read in silent mode i.e. it will # show nothing instead of password. read -s password echo echo "Your password is read in silent mode."

What is $() in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.


2 Answers

The only solution works on Ubuntu 12.04:

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

But the second option only works when I change from:

echo "password:name" | chpasswd 

To:

echo "user:password" | chpasswd 

See explanations in original post: Changing password via a script

like image 42
Fernando Kosh Avatar answered Oct 21 '22 13:10

Fernando Kosh


from "man 1 passwd":

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

So in your case

adduser "$1" echo "$2" | passwd "$1" --stdin 

[Update] a few issues were brought up in the comments:

Your passwd command may not have a --stdin option: use the chpasswd utility instead, as suggested by ashawley.

If you use a shell other than bash, "echo" might not be a builtin command, and the shell will call /bin/echo. This is insecure because the password will show up in the process table and can be seen with tools like ps.

In this case, you should use another scripting language. Here is an example in Perl:

#!/usr/bin/perl -w open my $pipe, '|chpasswd' or die "can't open pipe: $!"; print {$pipe} "$username:$password"; close $pipe 
like image 100
8jean Avatar answered Oct 21 '22 11:10

8jean