We're an ISO27001:2013 Certified Supplier

From time to time, it’s helpful to be able to generate Linux passwords from a script. In this TechTip, we’ll look at one way that may be done.

Generate The Password

Secure passwords can be generated with the pwgen command. By default, it will print 160 8 character passwords, but for demonstration purposes we’ll limit it to printing four passwords:

$ pwgen -N 4 
Oquaeba1 Aidien5J moh3ooHu Yaez1chi

Human Or Machine Use?

Passwords that are intended for machine use don’t need to be easy to type (or even write down):

$ pwgen -sy 15 1 
kFa\B_~:e=r[*J1

This command line:

  • runs pwgen
  • the -s (“secure”) option generates “completely random, hard-to-memorize passwords”
  • the -y specifies that the password should include at least one symbol
  • the 15 specifies that the passwords should be 15 characters long
  • the 1 specifies that only one password should be generated

A password that needs to be typed by a human normally requires a degree of compromise in its complexity. Perhaps this is appropriate:

$ pwgen -Bcny 10 1 
EiF@ae4jei

Here:

  • -B excludes ambiguous characters (such as zero and the letter “O”)
  • -c includes at least one uppercase character
  • -n includes at least one number
  • -y includes at least one non-alphanumeric character
  • 10 1 produce one ten-character password

Use In Scripts

The danger of generating and using passwords in a bash script revolves around the shell interpreting non-alphanumeric characters. Let’s simulate pwgen generating a password with a dollar sign in it:

#!/bin/bash
pw="abc$def"
echo "Your password is: '$pw'"

When we run the script, we get:

Your password is: 'abc'

That’s because the $def part is being interpreted as a bash variable, and as it doesn’t exist it evaluates to an empty string.

It is hard – very hard – to handle such conditions within bash.

The easy fix is not to have non-alphanumeric characters in the password. Here’s a script that creates a new account and sets the password:

#!/bin/bash

USER=$1
if [ -z "$1" ]; then
    echo "No username given"
    exit 1
fi

PASSWORD=$(pwgen -Bcn 10 1)
useradd -m $USER
echo "$USER:$PASSWORD" | chpasswd

echo "Account created"
echo "Username: $USER"
echo "Password: $PASSWORD"

If you want to write scripts that handle passwords that include non-alphanumeric characters, use something other than bash.

Conclusion

The ideas presented on this page are just that: ideas. The scripts need refinement to include error checking, but hopefully they will provide a starting point.

Was This Linux Tip Helpful?

Let us know in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Secure. Reliable. Scalable.

If that doesn't describe your current Linux systems, check out our FREE Linux Survival Guide to help you get your systems up to scratch today!

  • This field is for validation purposes and should be left unchanged.