Using Passwords in Scripts

Problem

You need to hardcode a password in a script.

Solution

This is obviously a bad idea and should be avoided whenever possible. Unfortunately, sometimes it isn’t possible to avoid it.

The first way to try to avoid doing this is to see if you can use sudo with the NOPASSWD option to avoid having to hardcode a password anywhere. This obviously has its own risks, but is worth checking out. See Using sudo More Securely for more details.

Another alternative may be to use SSH with public keys and ideally restricted commands. See Using SSH Without a Password.

If there is no other way around it, about the best you can do is put the user ID and password in a separate file that is readable only by the user who needs it, then source that file when necessary (Using Configuration Files in a Script). Leave that file out of revision control, of course.

Discussion

Accessing data on remote machines in a secure manner is relatively easy using SSH (see Using SSH Without a Password and Getting Input from Another Machine). It may even be possible to use that SSH method to access other data on the same host, but it’s probably much more efficient to use sudo for that. But what about accessing data in a remote database, perhaps using some SQL command? There is not much you can do in that case.

Yes, you say, but what about crypt or the other password hashes? The problem is that the secure methods for storing passwords all involve using what’s known as a one-way hash. The password checks ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.