Search code examples
bashrandom7zip

7z directrories with unique passwords and filenames


I have a bunch of directories that I want to password protect with 7z. I want to generate a 64 character string to use as the password, a 6 character string to use as a prefix to the file. I would ideally like to save both to a file in an array to keep track of the names and passwords.

Currently i do this manually, but I have too many to do now so I would like to use bash to do it.

I generated the passwords and 6 character string using my password manager. Copy and paste into the script and run it. For 1 or 2 files this ok, but now I have 100's.

Password_string=NzNeUGMpA1DkFPGQW3CEfLX1PIQdFNmKwyBrTqjv73ydcPwAJnNHUZFj4r2siBEu

a=1

for i in *;
do 7za a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=off -p$Password_string -mhe=on $i.7z $i
    new=$(printf "636995_archive_%04d.7z" "$a") #04 pad to length of 4
    mv -i -- "$i.7z" "$new" #rename to include numbers
    let a=a+1 #increment counter
done

Solution

  • you can randomly generate the prefix and password in your loop. After you create the archive, you can log the variables to a file before the next iteration of the loop.

    Here's my example. I commented the 7z command, so I could test the script and see the log.

    seq=0
    echo 'dir,prefix,seq,archive,password' > log.csv
    
    for dir in /*; do
        prefix=$(head -c 6 <(tr -dc '0-9' < /dev/urandom))  # generate random 6-digit prefix
        pw64=$(head -c 64 <(tr -dc '[:alnum:]' < /dev/urandom))  # generate random 64-char alphanumeric string
        ((seq+=1))
        archive=$(printf "${prefix}_archive_%04d" "$seq")  # name of archive
        #7za a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=off -p"$pw64" -mhe=on "$archive.7z" "$dir"
        echo "$dir,$prefix,$seq,$archive,$pw64" >> log.csv
    done
    

    Partial view of the log:

    dir,prefix,seq,archive,password
    /bin,614175,1,614175_archive_0001,C7UhfDcfUyjV0JeOBykMn6fDMF4H4hWka7Y4xluzmWGDPqN0vlNzReIwLv7cYSE7
    /boot,605074,2,605074_archive_0002,BsUQ5uEFpMZKZnKpUq7OH3VVMpp4jrsUrtVWBt6h1Q3S3mHAr5cnJk9w10LefzL0
    /dev,676241,3,676241_archive_0003,5zcnV9EO8Z5nOA3VANGdMoVGTIdjT77RUKybd6cgfXLXDXLA9jiPYtJO66ZwTSbq