Change linux password in a script, quietly
Solution 1
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.
Solution 2
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.
Joel G Mathew
Full Stack Developer with skills in Python, Vue, Flutter/Dart, Perl, PHP, C, Javascript, Bash shell cripting. Android enthusiast. Oh.. I'm a Doctor and an ENT specialist in the real world.
Updated on July 16, 2020Comments
-
Joel G Mathew almost 4 years
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?
-
Joel G Mathew about 11 yearsYes, I had tried that. However passwd on my server does not recognize --stdin option, even though I'm user root.
-
GuySoft almost 5 yearsWorked for me only without --stdin flag, just send stdin