Автоматическое рекурсивное шифрование в каталоге с помощью сценария оболочки
Опубликовано: 16 Февраля, 2022
Этот сценарий будет рекурсивно шифровать файл, предоставленный в качестве аргумента, или каталог, а также составляющие его файлы и подкаталоги. Это было бы очень полезно для автоматизации шифрования нескольких файлов в каталоге вместе.
Как это работает?
- Если аргументы не указаны, вывести ошибку и выйти из программы.
- Прочтите пароль, который будет использоваться для шифрования файлов в переменной.
- Найдите путь данного аргумента по realpath.
- Создайте функцию, чтобы проверить, что предоставленный аргумент - это каталог или файл.
- Если указан каталог, рекурсивно получить файлы в этом каталоге, отсортировать и удалить повторяющиеся записи в списке файлов с помощью ls | uniq и сохраните его в массиве.
- Передайте вывод ls | uniq к функции один за другим по индексам созданного массива в цикле, т.е. вызов той же функции рекурсивно.
- Если указан файл a, выполните шаг 8
- Просмотрите каждый файл и зашифруйте файл с помощью встроенной утилиты gpg с заданным паролем.
- Если утилита 'gpg' завершает работу с ненулевым кодом выхода, выдает сообщение об ошибке и завершает программу. В противном случае удалите исходный файл и покажите имя зашифрованного файла, чтобы указать, что он успешно зашифрован.
Source Code: You can use any editor on Linux like nano and save this as s1.sh. You may face some problems with the permission of this file while executing this shell script. Don’t worry, just use the command sudo chmod 774 s1.sh to come over this problem.
#!/bin/bash #In this line we check that an #argument is provided or not if [ -z "$1" ]; then echo "No file provided" >&2 exit 1 fi #reading the password which would #be used for encryption read -p "Enter the password" pass function func() { file_name=$1 #checking if the provided #argument is a directory if [ -d `realpath $file_name` ]; then #going to the location #of the directory cd `realpath $file_name` #saving the output of the #“ls | uniq” in an array array=(` ls | uniq `) #storing the length of the #array in a variable len=${ #array[*]} i=0 #looping through all the #indices of the array while [ $i -lt $len ]; do #displaying the file in #the index right now echo "${array[$i]}" #recursively calling the function func ${array[$i]} #increasing the counter let i++ done fi #checking if the argument is a file if [ -f `realpath $file_name` ]; then #encrypting the file with the given password #and storing the return value of the gpg #in a variable test = echo $pass | gpg -c --batch -- yes --passphrase-fd 0 $file_name #checking if the gpg #executed properly or not if [ "$test" == "1" ]; then #writing to the standard error echo "Bad signature: gpg not executed properly" >&2 exit 1 #checking if the gpg #executed properly or not elif [ "$test" == "2" ]; then #writing to the standard error echo "unexpected error: gpg not executed properly" >&2 exit 1 else #deleting the original file rm $file_name #displaying the gpg created echo " $file_name.gpg " fi fi } func $1 |
Выход: