Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change linux password in a script, quietly

As part of trying to implement a security measure in my root ssh session, I'm trying to devise a method of starting a script after n seconds of root user login, and change the user password and logout the user automatically.

I'm getting stuck at trying to change the password silently. I have the following code:

echo -e "new\nnew" | passwd -q

This instead of changing the password "quietly" as mentioned in man pages, outputs this:

~/php-pastebin-v3 #echo -e "new\nnew" | passwd -q
Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully

which doesnt help much.

I tried to pipe stdout and stderr, however I think I have misunderstood piping.

~/php-pastebin-v3 #echo -e "new\nnew" | passwd -q > /dev/null
Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully

~/php-pastebin-v3 #echo -e "new\nnew" | passwd -q /dev/null 2>&1
passwd: user '/dev/null' does not exist

What's the correct method to change the password via a script, quietly?

like image 322
Joel G Mathew Avatar asked Feb 22 '13 11:02

Joel G Mathew


2 Answers

If you want to redirect both stdout and sterr:

echo "..." | passwd &> /dev/null

which is the equivalent of

echo "..." | passwd > /dev/null 2>&1

which means "redirect stdout to /dev/null and then redirect (duplicate) stderr to stdout". This way you redirect both stdout and stderr to null ... but it might not be enough (it will be in this case I believe). But theoretically the program might write directly to terminal. For example this script

$ cat test.sh
echo stdout
echo stderr 1 1>&2
echo stderr 2 >/dev/stderr
echo stderr 3 >/dev/fd/2
echo bad luck > /dev/tty

$ ./test.sh &> /dev/null
bad luck

To get rid even of this output you must force the program to run in pseudo terminal, for example http://empty.sourceforge.net/ . But that is just a side note &> /dev/null will work fine.

like image 133
Neuron Avatar answered Sep 25 '22 13:09

Neuron


You can also do it that way:

mkpasswd
# Password:blah
# BVR2Pnr3ro5B2

echo "user:BVR2Pnr3ro5B2" | chpasswd -e

so the password is already encrypted in the script.

like image 42
Florian Fida Avatar answered Sep 22 '22 13:09

Florian Fida