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.

1
  • 3
    For those who want to do this on FreeBSD: echo "newpassword" | pw usermod theusername -h 0 Commented Dec 2, 2011 at 23:21

5 Answers 5

26

You could use chpasswd.

echo user:pass | /usr/sbin/chpasswd
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

1
  • 1
    ...But my AIX system doesn't have usermod :'( -- I'll fix the tags on the question.
    – voretaq7
    Commented Nov 30, 2011 at 17:01
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).
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.

5
  • That's the one. echo VerySecret | passwd --stdin username
    – MadHatter
    Commented Nov 30, 2011 at 17:06
  • 5
    My Ubuntu system doesn't have --stdin as an option for passwd. Commented Nov 30, 2011 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
    Commented Nov 30, 2011 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
    Commented Nov 30, 2011 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. Commented Dec 1, 2011 at 7: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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .