diff --git a/.env b/.env new file mode 100644 index 0000000..e85c75c --- /dev/null +++ b/.env @@ -0,0 +1,4 @@ +TEST_PASSWORD=Pi9Y8hap63ReAAsH6nxj +TEST_PASSWORD2=4266742@gmail.com +TEST_PASSWORD2r=4266742@gmail.com +TEST_PASSWORD2rr=sU9Dtf6v6qDlVsYaijqu diff --git a/README.md b/README.md index dbd3b82..0b83b02 100644 --- a/README.md +++ b/README.md @@ -7,4 +7,4 @@ curl -H "Authorization: token READ_REPOSITORY_ACCESS_TOKEN" -O https://git.rozen **git** git remote add server-init https://git.rozenlab.com/Leo/server-init.git -git add -A && git commit -m "changes" && git push server-init master \ No newline at end of file +git add -A && git commit -m "changes" && git push server-init master diff --git a/cron-list.sh b/cron-list.sh new file mode 100644 index 0000000..32afd80 --- /dev/null +++ b/cron-list.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +CRON_LIST=/data/$SRV_START_DIR/cron.cfg + +trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT +set -e + +export DEBIAN_FRONTEND=noninteractive + +# Checking for the presence of the cron.list file +if [ ! -f $CRON_LIST ]; then + echo "cron.list file not found!" + exit 1 +fi + +# Reading current crontab jobs into a variable +current_crontab=$(crontab -l 2>/dev/null) + +# Iterate through the lines of the cron.list file +while IFS= read -r line; do + # Skip blank lines and comments + if [[ -z "$line" || "$line" == \#* ]]; then + continue + fi + + # Checking if a job exists in the current crontab + if echo "$current_crontab" | grep -Fq "$line"; then + echo "The task already exists: $line" + else + # Adding a job to crontab + (crontab -l; echo "$line") | crontab - + echo "Task added: $line" + fi +done < "$CRON_LIST" + +trap - EXIT +echo "Cron add ok." \ No newline at end of file diff --git a/env-gen.sh b/env-gen.sh new file mode 100644 index 0000000..51d22a3 --- /dev/null +++ b/env-gen.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +# Проверка наличия первого параметра +if [ -z "$1" ]; then + echo "Использование: $0 <название_переменной> [значение]" + exit 1 +fi + +VARIABLE_NAME=$1 +ENV_FILE="/data/secrets/$SERVER_DOMAIN/$SERVER_DOMAIN.env" + +# Генерация случайного пароля из цифр и маленьких латинских букв длиной 20 символов +generate_random_password() { + #tr -dc 'a-z0-9' > "$ENV_FILE" +fi + +echo "Переменная $VARIABLE_NAME успешно обновлена/добавлена в $ENV_FILE" \ No newline at end of file diff --git a/global-env.sh b/global-env.sh new file mode 100644 index 0000000..0599a3c --- /dev/null +++ b/global-env.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +if [ "$(id -u)" != "0" ]; then + echo -e "\033[31mThis script requires superuser rights.\033[0m" + exit 0 +fi + +if [ -z "$1" ] || [ -z "$2" ]; then + echo "Please provide both the VAR_NAME and VAR_VALUE as arguments." + exit 1 +fi + +trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT +set -e + +export DEBIAN_FRONTEND=noninteractive + +ENV_VAR_NAME=$1 +ENV_VAR_VALUE=$2 + +# Create a file if it does not exist +if [ ! -f /etc/environment ]; then + touch /etc/environment +fi + +# Checking if a variable already exists +if grep -q "^${ENV_VAR_NAME}=" /etc/environment; then + # If the variable exists, update its value + sed -i "s/^${ENV_VAR_NAME}=.*/${ENV_VAR_NAME}=${ENV_VAR_VALUE}/" /etc/environment +else + # If the variable does not exist, add it + echo "${ENV_VAR_NAME}=${ENV_VAR_VALUE}" | tee -a /etc/environment +fi + +export "${ENV_VAR_NAME}=${ENV_VAR_VALUE}" + +trap - EXIT +echo "Environment variable ${ENV_VAR_NAME} set to:" +printenv "${ENV_VAR_NAME}" \ No newline at end of file diff --git a/init-db.sh b/init-db.sh new file mode 100644 index 0000000..d437b0b --- /dev/null +++ b/init-db.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +if [ "$(id -u)" != "0" ]; then + echo -e "\033[31mThis script requires superuser rights\033[0m" + exit 0 +fi + +if [ -z "$1" ] || [ -z "$2" ]; then + echo "Please provide all arguments: CREATE_DB_NAME, CREATE_DB,_PASSWORD" + exit 1 +fi + +trap 'echo -e "\033[31mAn error has occurred\033[0m"; exit 1' EXIT +set -e + +export DEBIAN_FRONTEND=noninteractive + +CREATE_DB_NAME=$1 +CREATE_DB_PASSWORD=$2 + +: "${POSTGRES_USER:?}" +: "${POSTGRES_DB:?}" + +sudo docker exec -i postgres psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" <<-EOSQL + CREATE USER "$CREATE_DB_NAME" WITH ENCRYPTED PASSWORD '$CREATE_DB_PASSWORD'; + CREATE DATABASE "$CREATE_DB_NAME"; + GRANT ALL PRIVILEGES ON DATABASE "$CREATE_DB_NAME" TO "$CREATE_DB_NAME"; + ALTER DATABASE "$CREATE_DB_NAME" OWNER TO "$CREATE_DB_NAME"; +EOSQL + + +trap - EXIT +echo -e "\033[32mDatabase $CREATE_DB_NAME created successfully\033[0m" + + + + + + diff --git a/init.sh b/init-docker.sh similarity index 53% rename from init.sh rename to init-docker.sh index c5e8492..c1cbb1f 100644 --- a/init.sh +++ b/init-docker.sh @@ -1,27 +1,20 @@ -#!/bin/bash - -if [ "$(id -u)" != "0" ]; then - echo "This script requires superuser rights. Running with sudo..." - exec sudo "$0" "$@" -fi - -trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT -set -e - -export DEBIAN_FRONTEND=noninteractive - -apt update -y -apt upgrade -y -apt install -y apt-transport-https ca-certificates curl software-properties-common -curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - -add-apt-repository -y "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable" -apt update -y -apt install -y docker-ce -apt install -y mc vim zip - -mkdir -p /data -chown usradmin:usradmin /data -chmod 770 /data - -trap - EXIT -echo "Init complete" \ No newline at end of file +#!/bin/bash + +if [ "$(id -u)" != "0" ]; then + echo -e "\033[31mThis script requires superuser rights.\033[0m" + exit 0 +fi + +trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT +set -e + +export DEBIAN_FRONTEND=noninteractive + +apt install -y apt-transport-https ca-certificates curl software-properties-common +curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/trusted.gpg.d/docker.gpg +add-apt-repository -y "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable" +apt update -y +apt install -y docker-ce + +trap - EXIT +echo "Docker installed" \ No newline at end of file diff --git a/init-server.sh b/init-server.sh new file mode 100644 index 0000000..3031217 --- /dev/null +++ b/init-server.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +USERNAME=usradmin +SSH_PORT=2525 + +if [ "$(id -u)" != "0" ]; then + echo -e "\033[31mThis script requires superuser rights.\033[0m" + exit 0 +fi + +trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT +set -e + +export DEBIAN_FRONTEND=noninteractive + +apt update -y +apt upgrade -y +apt install -y mc vim zip pwgen + +timedatectl set-timezone Asia/Yekaterinburg +echo "Timezone changed:" +timedatectl + +if id "$USERNAME" &>/dev/null; then + echo "User $USERNAME already exists" +else + useradd -m -s /bin/bash "$USERNAME" + usermod -aG sudo "$USERNAME" +fi + +chown "$USERNAME":"$USERNAME" /data +chmod 770 /data + +mkdir -p /backups +chown "$USERNAME":"$USERNAME" /backups +chmod 770 /backups + +# SSH config: +cd /data/utils +bash ssh-port.sh $SSH_PORT +#bash ssh-pw.sh n + +trap - EXIT +echo "Init complete" \ No newline at end of file diff --git a/loader.sh b/loader.sh new file mode 100644 index 0000000..805c877 --- /dev/null +++ b/loader.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# Путь к файлу с списком ссылок +FILE_LIST="server.list" +# Токен доступа для авторизации +TOKEN="READ_REPOSITORY_ACCESS_TOKEN" + +# Проверка наличия файла со списком ссылок +if [ ! -f "$FILE_LIST" ]; then + echo "Файл $FILE_LIST не найден." + exit 1 +fi + +# Читаем файл строчка за строчкой +while IFS= read -r URL; do + if [ ! -z "$URL" ]; then + # Получаем имя файла из URL + FILE_NAME=$(basename "$URL") + + # Загружаем файл используя curl + curl -H "Authorization: token $TOKEN" -O "$URL" + + # Проверка статуса выполнения curl + if [ $? -ne 0 ]; then + echo "Ошибка при загрузке файла: $FILE_NAME" + else + echo "Успешно загружен: $FILE_NAME" + fi + fi +done < "$FILE_LIST" \ No newline at end of file diff --git a/samba.sh b/samba.sh index 424df4f..443a903 100644 --- a/samba.sh +++ b/samba.sh @@ -1,8 +1,8 @@ #!/bin/bash if [ "$(id -u)" != "0" ]; then - echo "This script requires superuser rights. Running with sudo..." - exec sudo "$0" "$@" + echo -e "\033[31mThis script requires superuser rights.\033[0m" + exit 0 fi if [ -z "$1" ] || [ -z "$2" ]; then @@ -47,6 +47,18 @@ NEW_SECTION=$(cat << EOM directory mask = 0777 force directory mode = 0777 valid users = $USERNAME + +# backups folder access +[backups] + path = /backups + read only = no + browseable = yes + create mask = 0666 + force create mode = 0666 + directory mask = 0777 + force directory mode = 0777 + valid users = $USERNAME + EOM ) diff --git a/secrets-export.sh b/secrets-export.sh new file mode 100644 index 0000000..084d3b1 --- /dev/null +++ b/secrets-export.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +# Переменные +SOURCE_DIR="/data/secrets" +ARCHIVE_NAME="secrets.tar.gz.enc" +REMOTE_USER="remote_user" +REMOTE_HOST="remote_host" +REMOTE_DIR="/secrets" +PASSWORD_FILE="$SOURCE_DIR/secrets.env" + +# Путь к зашифрованному архиву +ARCHIVE_PATH="$SOURCE_DIR/$ARCHIVE_NAME" + +# Чтение пароля из файла +if [ -f "$PASSWORD_FILE" ]; then + PASSWORD=$(cat "$PASSWORD_FILE") +else + echo "Файл с паролем не найден: $PASSWORD_FILE" + exit 1 +fi + +# Создание tar.gz архива и шифрование его +tar -czf - "$SOURCE_DIR" | openssl enc -aes-256-cbc -e -pass pass:"$PASSWORD" -out "$ARCHIVE_PATH" +if [ $? -ne 0 ]; then + echo "Не удалось создать и зашифровать архив" + exit 1 +fi + +# Отправка архива на удаленный сервер +rsync -avz "$ARCHIVE_PATH" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR" +if [ $? -ne 0 ]; then + echo "Не удалось отправить архив на удаленный сервер" + exit 1 +fi + +# Удаление архива после успешной отправки (опционально) +rm -f "$ARCHIVE_PATH" + +echo "Успешно завершено!" + +exit 0 \ No newline at end of file diff --git a/secrets-import.sh b/secrets-import.sh new file mode 100644 index 0000000..4bbe123 --- /dev/null +++ b/secrets-import.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +REMOTE_USER="remote_user" +REMOTE_HOST="remote_host" +REMOTE_DIR="/secrets" +REMOTE_FILE="secrets.env.tar.gz" +LOCAL_SECRETS_DIR="/data/secrets" +ARCHIVE_PATH="$LOCAL_SECRETS_DIR/$REMOTE_FILE" +PASSWORD_FILE="$LOCAL_SECRETS_DIR/secrets.env" + +# Скачиваем файл с удаленного сервера +rsync -avz --progress $REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/$REMOTE_FILE $LOCAL_SECRETS_DIR + +# Проверяем успешность скачивания +if [ $? -ne 0 ]; then + echo "Ошибка: не удалось скачать файл $REMOTE_FILE." + exit 1 +fi + +# Проверяем, существует ли файл $PASSWORD_FILE +if [ ! -f "$PASSWORD_FILE" ]; then + echo "Ошибка: файл с паролем $PASSWORD_FILE не найден." + exit 1 +fi + +# Извлекаем пароль из файла +PASSWORD=$(cat "$PASSWORD_FILE") + +# Проверяем, существует ли папка $LOCAL_SECRETS_DIR +if [ -d "$LOCAL_SECRETS_DIR" ]; then + # Переименовываем старую папку + mv "$LOCAL_SECRETS_DIR" "${LOCAL_SECRETS_DIR}_old" +fi + +# Создаем новую папку +mkdir -p "$LOCAL_SECRETS_DIR" + +# Распаковываем и расшифровываем файл в новую папку +cd "$LOCAL_SECRETS_DIR" +echo "$PASSWORD" | gpg --batch --yes --passphrase-fd 0 -d "$ARCHIVE_PATH" | tar -xz + +# Проверяем успешность распаковки +if [ $? -ne 0 ]; then + echo "Ошибка: не удалось распаковать файл $REMOTE_FILE." + exit 1 +fi + +echo "Файл $REMOTE_FILE успешно скачан, расшифрован и распакован в $LOCAL_SECRETS_DIR." \ No newline at end of file diff --git a/ssh-init.sh b/ssh-init.sh new file mode 100644 index 0000000..016d297 --- /dev/null +++ b/ssh-init.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +ssh-keygen -t ed25519 -C "$ADMIN_EMAIL" + + + +ssh-copy-id user@server_ip \ No newline at end of file diff --git a/ssh-port.sh b/ssh-port.sh index 8333be7..b7d03f6 100644 --- a/ssh-port.sh +++ b/ssh-port.sh @@ -1,8 +1,8 @@ #!/bin/bash if [ "$(id -u)" != "0" ]; then - echo "This script requires superuser rights. Running with sudo..." - exec sudo "$0" "$@" + echo -e "\033[31mThis script requires superuser rights.\033[0m" + exit 0 fi if [ -z "$1" ]; then @@ -10,17 +10,24 @@ if [ -z "$1" ]; then exit 1 fi -trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT -set -e - NEW_PORT="$1" SSH_CONFIG_FILE="/etc/ssh/sshd_config" +# Проверяем, что параметр является числом +if ! [[ "$NEW_PORT" =~ ^[0-9]+$ ]]; then + echo -e "\033[31mPort must be a number\033[0m" + exit 1 +fi + +trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT +set -e + echo "Change SSH port to $NEW_PORT..." cp $SSH_CONFIG_FILE $SSH_CONFIG_FILE.bak -sed -i "s/^#Port 22/Port $NEW_PORT/" $SSH_CONFIG_FILE -sed -i "s/^Port 22/Port $NEW_PORT/" $SSH_CONFIG_FILE -systemctl restart sshd +sed -i "s/^#\?Port [0-9]*/Port $NEW_PORT/" $SSH_CONFIG_FILE + +systemctl daemon-reload +systemctl restart ssh trap - EXIT echo "SSH port successfully changed to $NEW_PORT." \ No newline at end of file diff --git a/ssh-pw.sh b/ssh-pw.sh new file mode 100644 index 0000000..cdb05fa --- /dev/null +++ b/ssh-pw.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +if [ "$(id -u)" != "0" ]; then + echo -e "\033[31mThis script requires superuser rights\033[0m" + exit 0 +fi + +# Проверка наличия одного аргумента +if [ "$#" -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +# Проверка аргумента +if [ "$1" != "y" ] && [ "$1" != "n" ]; then + echo "Invalid argument. Use 'y' to enable password authentication and 'n' to disable it" + exit 1 +fi + +trap 'echo -e "\033[31mSomething went wrong\033[0m"; exit 1' EXIT +set -e + +# Путь к конфигурационному файлу sshd +SSHD_CONFIG="/etc/ssh/sshd_config" + +# Функция включения или отключения доступа по паролю +toggle_password_access() { + local enable=$1 + if [ "$enable" == "y" ]; then + sudo sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication yes/' $SSHD_CONFIG + sudo sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' $SSHD_CONFIG + else + sudo sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication no/' $SSHD_CONFIG + sudo sed -i 's/^PasswordAuthentication yes/PasswordAuthentication no/' $SSHD_CONFIG + fi +} + +# Бэкапим текущий конфигурационный файл +sudo cp $SSHD_CONFIG $SSHD_CONFIG.backup + +# Применение изменений +toggle_password_access "$1" + +# Перезапуск службы sshd для применения изменений +sudo systemctl restart sshd + + +trap - EXIT + +# Уведомление о завершении +if [ "$1" == "y" ]; then + echo "Password authentication has been enabled" +else + echo "Password authentication has been disabled" +fi