Jolly Llama
Jolly Llama

Reputation: 101

Bash script to read a password once and use it for many files

I'm writing a Bash script to encrypt a lot of files using zip -e, and right now I have to use zip -P "plaintextpassword" to get it to work. I'd like to have my script prompt securely for a password once, then use the same one for a bunch of files. My script looks something like

for f in *; do zip -v -P "plaintextpassword" "$f.zip" "$f"

This results in a whole lot of separate .zip files, which is what I want.

Upvotes: 0

Views: 2494

Answers (3)

kvantour
kvantour

Reputation: 26481

While not really an answer, it is always nice to quote the man-page:

-P password --password password Use password to encrypt zipfile entries (if any). THIS IS INSECURE! Many multi-user operating systems provide ways for any user to see the current command line of any other user; even on stand-alone systems there is always the threat of over-the-shoulder peeking. Storing the plaintext password as part of a command line in an automated script is even worse. Whenever possible, use the non-echoing, interactive prompt to enter pass‐ words. (And where security is truly important, use strong encryption such as Pretty Good Privacy instead of the relatively weak standard encryption provided by zipfile utilities.)

source: man zip

Upvotes: 1

Gordon Davisson
Gordon Davisson

Reputation: 125818

In bash, you'd use something like this to read the password:

IFS= read -sr -p "Enter a password: " password
echo

The IFS= prefix keeps read from trimming spaces and tabs, the -r keeps it from trying to parse backslashes as escapes, -p "Enter a password: " supplies the prompt, -s keeps it from echoing as you type, and then echo at then end goes to the next line (normally handled by echoing the carriage return at the end of input... but -s suppresses that).

Then use the password like this:

for f in *; do zip -v -P "$password" "$f.zip" "$f"

Note that this isn't all that secure, because the arguments passed to commands (including the password argument to zip) are basically public info, easily viewable with the ps command.

Upvotes: 2

Sonny
Sonny

Reputation: 3183

You could read the password and store as a variable and pass to the for loop in bash shell

#!/bin/bash
# Read Password
echo -n Password:
read -s password

for f in *;
do
        zip -v -P "$password" "$f.zip" "$f"
done

Upvotes: 1

Related Questions