16

I have a specific use case where I would really like to be able to change a user's password with a single command with no interactivity. This is being done in a safe fashion (over SSH, and on a system with only one user able to be logged in), so it's fine to expose the new password (and even the old one, if necessary) on the command line. FWIW, it's a Ubuntu system.

I just want to avoid having to add something Expect-like to this system for just this one task.

Paul Hoffman
  • 2,214
  • 5
  • 19
  • 23

5 Answers5

26

You could use chpasswd.

echo user:pass | /usr/sbin/chpasswd
xofer
  • 3,072
  • 12
  • 19
5

You can use usermod with the -p option to provide a password hash (not the actual password). You can generate the password hash using something like mkpasswd -m sha-256 or mkpasswd -m md5

jscott
  • 24,484
  • 8
  • 79
  • 100
stew
  • 9,388
  • 1
  • 30
  • 43
3

Sure.

  1. Hash the password on your local system.
  2. Connect to the remote machine (where you want to change the password)
  3. Feed the hashed password & the username to a creative sed script that updates your system's password file (/etc/shadow, /etc/master.passwd, whatever it happens to be).
voretaq7
  • 79,879
  • 17
  • 130
  • 214
1

The passwd utility has a --stdin option that states:

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

Syntax:

echo "newpass" | passwd --stdin user1

Even though you mentioned you don't care, you could put the password in a text file and then do cat pass.txt instead of the echo command, that way it doesn't show up in the bash history.

quanta
  • 51,413
  • 19
  • 159
  • 217
Safado
  • 4,786
  • 7
  • 37
  • 54
  • That's the one. `echo VerySecret | passwd --stdin username` – MadHatter Nov 30 '11 at 17:06
  • 5
    My Ubuntu system doesn't have `--stdin` as an option for `passwd`. – Jeff Ferland Nov 30 '11 at 17:19
  • You're right, it doesn't. I checked on both a CentOS system and on a Mac and they have the --stdin option, so the removal of it must be a Ubuntu thing. – Safado Nov 30 '11 at 17:48
  • 1
    @RyanM. FreeBSD (and AFAIK NetBSD and OpenBSD, AIX, HP-UX and Solaris last I checke) don't support `--stdin` either - mainly because it's a big giant security hole waiting to happen :-) – voretaq7 Nov 30 '11 at 20:12
  • 1
    @quanta: Or start the `echo "newpass" | passwd --stdin user1` line with a space; that way it won't go to bash history at all. – Janne Pikkarainen Dec 01 '11 at 07:44
1

If --stdin option is not working we can basically use two options:

  1. Either use another utilty called chpaswd in your script.
  2. OR use echo "current_password\nnew_password\nnew_password" | passwd user_name
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
Sanjay s.
  • 111
  • 3