reworking content
All checks were successful
learn org at code.softwareshinobi.com/linux.softwareshinobi.com/pipeline/head This commit looks good

This commit is contained in:
2025-06-19 10:03:08 -04:00
parent 611d0816cc
commit 7d9171c854
192 changed files with 2234 additions and 2362 deletions

View File

@@ -0,0 +1,91 @@
# About the book
* **This version was published on Oct 30 2023**
This is an open-source introduction to Bash scripting guide that will help you learn the basics of Bash scripting and start writing awesome Bash scripts that will help you automate your daily SysOps, DevOps, and Dev tasks. No matter if you are a DevOps/SysOps engineer, developer, or just a Linux enthusiast, you can use Bash scripts to combine different Linux commands and automate tedious and repetitive daily tasks so that you can focus on more productive and fun things.
The guide is suitable for anyone working as a developer, system administrator, or a DevOps engineer and wants to learn the basics of Bash scripting.
The first 13 chapters would be purely focused on getting some solid Bash scripting foundations, then the rest of the chapters would give you some real-life examples and scripts.
## About the author
My name is Bobby Iliev, and I have been working as a Linux DevOps Engineer since 2014. I am an avid Linux lover and supporter of the open-source movement philosophy. I am always doing that which I cannot do in order that I may learn how to do it, and I believe in sharing knowledge.
I think it's essential always to keep professional and surround yourself with good people, work hard, and be nice to everyone. You have to perform at a consistently higher level than others. That's the mark of a true professional.
For more information, please visit my blog at [https://bobbyiliev.com](https://bobbyiliev.com), follow me on Twitter [@bobbyiliev_](https://twitter.com/bobbyiliev_) and [YouTube](https://www.youtube.com/channel/UCQWmdHTeAO0UvaNqve9udRw).
## Sponsors
This book is made possible thanks to these fantastic companies!
### Materialize
The Streaming Database for Real-time Analytics.
[Materialize](https://materialize.com/) is a reactive database that delivers incremental view updates. Materialize helps developers easily build with streaming data using standard SQL.
### DigitalOcean
DigitalOcean is a cloud services platform delivering the simplicity developers love and businesses trust to run production applications at scale.
It provides highly available, secure, and scalable compute, storage, and networking solutions that help developers build great software faster.
Founded in 2012 with offices in New York and Cambridge, MA, DigitalOcean offers transparent and affordable pricing, an elegant user interface, and one of the largest libraries of open source resources available.
For more information, please visit [https://www.digitalocean.com](https://www.digitalocean.com) or follow [@digitalocean](https://twitter.com/digitalocean) on Twitter.
If you are new to DigitalOcean, you can get a free $200 credit and spin up your own servers via this referral link here:
[Free $200 Credit For DigitalOcean](https://m.do.co/c/2a9bba940f39)
### DevDojo
The DevDojo is a resource to learn all things web development and web design. Learn on your lunch break or wake up and enjoy a cup of coffee with us to learn something new.
Join this developer community, and we can all learn together, build together, and grow together.
[Join DevDojo](https://devdojo.com?ref=bobbyiliev)
For more information, please visit [https://www.devdojo.com](https://www.devdojo.com?ref=bobbyiliev) or follow [@thedevdojo](https://twitter.com/thedevdojo) on Twitter.
## Ebook PDF Generation Tool
This ebook was generated by [Ibis](https://github.com/themsaid/ibis/) developed by [Mohamed Said](https://github.com/themsaid).
Ibis is a PHP tool that helps you write eBooks in markdown.
## Ebook ePub Generation Tool
The ePub version was generated by [Pandoc](https://pandoc.org/).
## Book Cover
The cover for this ebook was created with [Canva.com](https://www.canva.com/join/determined-cork-learn).
If you ever need to create a graphic, poster, invitation, logo, presentation or anything that looks good — give Canva a go.
## License
MIT License
Copyright (c) 2020 Bobby Iliev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,11 @@
# Introduction to Bash scripting
Welcome to this Bash basics training guide! In this **bash crash course**, you will learn the **Bash basics** so you could start writing your own Bash scripts and automate your daily tasks.
Bash is a Unix shell and command language. It is widely available on various operating systems, and it is also the default command interpreter on most Linux systems.
Bash stands for Bourne-Again SHell. As with other shells, you can use Bash interactively directly in your terminal, and also, you can use Bash like any other programming language to write scripts. This book will help you learn the basics of Bash scripting including Bash Variables, User Input, Comments, Arguments, Arrays, Conditional Expressions, Conditionals, Loops, Functions, Debugging, and testing.
Bash scripts are great for automating repetitive workloads and can help you save time considerably. For example, imagine working with a group of five developers on a project that requires a tedious environment setup. In order for the program to work correctly, each developer has to manually set up the environment. That's the same and very long task (setting up the environment) repeated five times at least. This is where you and Bash scripts come to the rescue! So instead, you create a simple text file containing all the necessary instructions and share it with your teammates. And now, all they have to do is execute the Bash script and everything will be created for them.
In order to write Bash scripts, you just need a UNIX terminal and a text editor like Sublime Text, VS Code, or a terminal-based editor like vim or nano.

View File

@@ -0,0 +1,104 @@
# Working with Cloudflare API with Bash
I host all of my websites on **DigitalOcean** Droplets and I also use Cloudflare as my CDN provider. One of the benefits of using Cloudflare is that it reduces the overall traffic to your user and also hides your actual server IP address behind their CDN.
My personal favorite Cloudflare feature is their free DDoS protection. It has saved my servers multiple times from different DDoS attacks. They have a cool API that you could use to enable and disable their DDoS protection easily.
This chapter is going to be an exercise! I challenge you to go ahead and write a short bash script that would enable and disable the Cloudflare DDoS protection for your server automatically if needed!
## Prerequisites
Before following this guide here, please set up your Cloudflare account and get your website ready. If you are not sure how to do that you can follow these steps here: [Create a Cloudflare account and add a website](https://support.cloudflare.com/hc/en-us/articles/201720164-Step-2-Create-a-Cloudflare-account-and-add-a-website).
Once you have your Cloudflare account, make sure to obtain the following information:
* A Cloudflare account
* Cloudflare API key
* Cloudflare Zone ID
Also, Make sure curl is installed on your server:
```bash
curl --version
```
If curl is not installed you need to run the following:
* For RedHat/CentOs:
```bash
yum install curl
```
* For Debian/Ubuntu
```bash
apt-get install curl
```
## Challenge - Script requirements
The script needs to monitor the CPU usage on your server and if the CPU usage gets high based on the number vCPU it would enable the Cloudflare DDoS protection automatically via the Cloudflare API.
The main features of the script should be:
* Checks the script CPU load on the server
* In case of a CPU spike the script triggers an API call to Cloudflare and enables the DDoS protection feature for the specified zone
* After the CPU load is back to normal the script would disable the "I'm under attack" option and set it back to normal
## Example script
I already have prepared a demo script which you could use as a reference. But I encourage you to try and write the script yourself first and only then take a look at my script!
To download the script just run the following command:
```bash
wget https://raw.githubusercontent.com/bobbyiliev/cloudflare-ddos-protection/main/protection.sh
```
Open the script with your favorite text editor:
```bash
nano protection.sh
```
And update the following details with your Cloudflare details:
```bash
CF_CONE_ID=YOUR_CF_ZONE_ID
CF_EMAIL_ADDRESS=YOUR_CF_EMAIL_ADDRESS
CF_API_KEY=YOUR_CF_API_KEY
```
After that make the script executable:
```bash
chmod +x ~/protection.sh
```
Finally, set up 2 Cron jobs to run every 30 seconds. To edit your crontab run:
```bash
crontab -e
```
And add the following content:
```bash
* * * * * /path-to-the-script/cloudflare/protection.sh
* * * * * ( sleep 30 ; /path-to-the-script/cloudflare/protection.sh )
```
Note that you need to change the path to the script with the actual path where you've stored the script at.
## Conclusion
This is quite straight forward and budget solution, one of the downsides of the script is that if your server gets unresponsive due to an attack, the script might not be triggered at all.
Of course, a better approach would be to use a monitoring system like Nagios and based on the statistics from the monitoring system then you can trigger the script, but this script challenge could be a good learning experience!
Here is another great resource on how to use the Discord API and send notifications to your Discord Channel with a Bash script:
[How To Use Discord Webhooks to Get Notifications for Your Website Status on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-use-discord-webhooks-to-get-notifications-for-your-website-status-on-ubuntu-18-04)
>{notice} This content was initially posted on [DevDojo](https://devdojo.com/bobbyiliev/bash-script-to-automatically-enable-cloudflare-ddos-protection)

View File

@@ -0,0 +1,83 @@
# BASH Script parser to Summarize Your NGINX and Apache Access Logs
One of the first things that I would usually do in case I notice a high CPU usage on some of my Linux servers would be to check the process list with either top or htop and in case that I notice a lot of Apache or Nginx process I would quickly check my access logs to determine what has caused or is causing the CPU spike on my server or to figure out if anything malicious is going on.
Sometimes reading the logs could be quite intimidating as the log might be huge and going though it manually could take a lot of time. Also, the raw log format could be confusing for people with less experience.
Just like the previous chapter, this chapter is going to be a challenge! You need to write a short bash script that would summarize the whole access log for you without the need of installing any additional software.
# Script requirements
This BASH script needs to parse and summarize your access logs and provide you with very useful information like:
* The 20 top pages with the most POST requests
* The 20 top pages with the most GET requests
* Top 20 IP addresses and their geo-location
## Example script
I already have prepared a demo script which you could use as a reference. But I encourage you to try and write the script yourself first and only then take a look at my script!
In order to download the script, you can either clone the repository with the following command:
```bash
git clone https://github.com/bobbyiliev/quick_access_logs_summary.git
```
Or run the following command which would download the script in your current directory:
```bash
wget https://raw.githubusercontent.com/bobbyiliev/quick_access_logs_summary/master/spike_check
```
The script does not make any changes to your system, it only reads the content of your access log and summarizes it for you, however, once you've downloaded the file, make sure to review the content yourself.
## Running the script
All that you have to do once the script has been downloaded is to make it executable and run it.
To do that run the following command to make the script executable:
```bash
chmod +x spike_check
```
Then run the script:
```bash
./spike_check /path/to/your/access_log
```
Make sure to change the path to the file with the actual path to your access log. For example if you are using Apache on an Ubuntu server, the exact command would look like this:
```bash
./spike_check /var/log/apache2/access.log
```
If you are using Nginx the exact command would be almost the same, but with the path to the Nginx access log:
```bash
./spike_check /var/log/nginx/access.log
```
## Understanding the output
Once you run the script, it might take a while depending on the size of the log.
The output that you would see should look like this:
![Summarized access log](https://imgur.com/WWHVMrj.png)
Essentially what we can tell in this case is that we've received 16 POST requests to our xmlrpc.php file which is often used by attackers to try and exploit WordPress websites by using various username and password combinations.
In this specific case, this was not a huge brute force attack, but it gives us an early indication and we can take action to prevent a larger attack in the future.
We can also see that there were a couple of Russian IP addresses accessing our site, so in case that you do not expect any traffic from Russia, you might want to block those IP addresses as well.
## Conclusion
This is an example of a simple BASH script that allows you to quickly summarize your access logs and determine if anything malicious is going on.
Of course, you might want to also manually go through the logs as well but it is a good challenge to try and automate this with Bash!
>{notice} This content was initially posted on [DevDojo](https://devdojo.com/bobbyiliev/bash-script-to-summarize-your-nginx-and-apache-access-logs)

View File

@@ -0,0 +1,95 @@
# Sending emails with Bash and SSMTP
SSMTP is a tool that delivers emails from a computer or a server to a configured mail host.
SSMTP is not an email server itself and does not receive emails or manage a queue.
One of its primary uses is for forwarding automated email (like system alerts) off your machine and to an external email address.
## Prerequisites
You would need the following things in order to be able to complete this tutorial successfully:
* Access to an Ubuntu 18.04 server as a non-root user with sudo privileges and an active firewall installed on your server. To set these up, please refer to our [Initial Server Setup Guide for Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04)
* An SMTP server along with SMTP username and password, this would also work with Gmail's SMTP server, or you could set up your own SMTP server by following the steps from this tutorial on [How to Install and Configure Postfix as a Send-Only SMTP Server on Ubuntu 16.04](https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-postfix-as-a-send-only-smtp-server-on-ubuntu-16-04)
## Installing SSMTP
In order to install SSMTP, youll need to first update your apt cache with:
```bash
sudo apt update
```
Then run the following command to install SSMTP:
```bash
sudo apt install ssmtp
```
Another thing that you would need to install is `mailutils`, to do that run the following command:
```bash
sudo apt install mailutils
```
## Configuring SSMTP
Now that you have `ssmtp` installed, in order to configure it to use your SMTP server when sending emails, you need to edit the SSMTP configuration file.
Using your favourite text editor to open the `/etc/ssmtp/ssmtp.conf` file:
```bash
sudo nano /etc/ssmtp/ssmtp.conf
```
You need to include your SMTP configuration:
```
root=postmaster
mailhub=<^>your_smtp_host.com<^>:587
hostname=<^>your_hostname<^>
AuthUser=<^>your_gmail_username@your_smtp_host.com<^>
AuthPass=<^>your_gmail_password<^>
FromLineOverride=YES
UseSTARTTLS=YES
```
Save the file and exit.
## Sending emails with SSMTP
Once your configuration is done, in order to send an email just run the following command:
```bash
echo "<^>Here add your email body<^>" | mail -s "<^>Here specify your email subject<^>" <^>your_recepient_email@yourdomain.com<^>
```
You can run this directly in your terminal or include it in your bash scripts.
## Sending A File with SSMTP (optional)
If you need to send files as attachments, you can use `mpack`.
To install `mpack` run the following command:
```bash
sudo apt install mpack
```
Next, in order to send an email with a file attached, run the following command.
```bash
mpack -s "<^>Your Subject here<^>" your_file.zip <^>your_recepient_email@yourdomain.com<^>
```
The above command would send an email to `<^>your_recepient_email@yourdomain.com<^>` with the `<^>your_file.zip<^>` attached.
## Conclusion
SSMTP is a great and reliable way to implement SMTP email functionality directly in bash scripts.
For more information about SSMTP I would recommend checking the official documentation [here](https://wiki.archlinux.org/index.php/SSMTP).
>{notice} This content was initially posted on the [DigitalOcean community forum](https://www.digitalocean.com/community/questions/how-to-send-emails-from-a-bash-script-using-ssmtp).

View File

@@ -0,0 +1,126 @@
# Password Generator Bash Script
It's not uncommon situation where you will need to generate a random password that you can use for any software installation or when you sign-up to any website.
There are a lot of options in order to achieve this. You can use a password manager/vault where you often have the option to randomly generate a password or to use a website that can generate the password on your behalf.
You can also use Bash in your terminal (command-line) to generate a password that you can quickly use. There are a lot of ways to achieve that and I will make sure to cover few of them and will leave up to you to choose which option is most suitable with your needs.
## :warning: Security
**This script is intended to practice your bash scripting skills. You can have fun while doing simple projects with BASH, but security is not a joke, so please make sure you do not save your passwords in plain text in a local file or write them down by hand on a piece of paper.**
**I will highly recommend everyone to use secure and trusted providers to generate and save the passwords.**
## Script summary
Let me first do a quick summary of what our script is going to do.:
1. We will have to option to choose the password characters length when the script is executed.
2. The script will then generate 5 random passwords with the length that was specified in step 1
## Prerequisites
You would need a bash terminal and a text editor. You can use any text editor like vi, vim, nano or Visual Studio Code.
I'm running the script locally on my Linux laptop but if you're using Windows PC you can ssh to any server of your choice and execute the script there.
Although the script is pretty simple, having some basic BASH scripting knowledge will help you to better understand the script and how it's working.
## Generate a random password
One of the great benefits of Linux is that you can do a lot of things using different methods. When it comes to generating a random string of characters it's not different as well.
You can use several commands in order to generate a random string of characters. I will cover few of them and will provide some examples.
- Using the ```date``` command.
The date command will output the current date and time. However we also further manipulate the output in order to use it as randomly generated password. We can hash the date using md5, sha or just run it through base64. These are few examples:
```
date | md5sum
94cb1cdecfed0699e2d98acd9a7b8f6d -
```
using sha256sum:
```
date | sha256sum
30a0c6091e194c8c7785f0d7bb6e1eac9b76c0528f02213d1b6a5fbcc76ceff4 -
```
using base64:
```
date | base64
0YHQsSDRj9C90YMgMzAgMTk6NTE6NDggRUVUIDIwMjEK
```
- We can also use openssl in order to generate pseudo-random bytes and run the output through base64. An example output will be:
```
openssl rand -base64 10
9+soM9bt8mhdcw==
```
Keep in mind that openssl might not be installed on your system so it's likely that you will need to install it first in order to use it.
- The most preferred way is to use the pseudorandom number generator - /dev/urandom
since it is intended for most cryptographic purposes. We would also need to manipulate the output using ```tr``` in order to translate it. An example command is:
```
tr -cd '[:alnum:]' < /dev/urandom | fold -w10 | head -n 1
```
With this command we take the output from /dev/urandom and translate it with ```tr``` while using all letters and digits and print the desired number of characters.
## The script
First we begin the script with the shebang. We use it to tell the operating system which interpreter to use to parse the rest of the file.
```
#!/bin/bash
```
We can then continue and ask the user for some input. In this case we would like to know how many characters the password needs to be:
```
# Ask user for password length
clear
printf "\n"
read -p "How many characters you would like the password to have? " pass_length
printf "\n"
```
Generate the passwords and then print it so the user can use it.
```
# This is where the magic happens!
# Generate a list of 10 strings and cut it to the desired value provided from the user
for i in {1..10}; do (tr -cd '[:alnum:]' < /dev/urandom | fold -w${pass_length} | head -n 1); done
# Print the strings
printf "$pass_output\n"
printf "Goodbye, ${USER}\n"
```
## The full script:
```
#!/bin/bash
#=======================================
# Password generator with login option
#=======================================
# Ask user for the string length
clear
printf "\n"
read -p "How many characters you would like the password to have? " pass_length
printf "\n"
# This is where the magic happens!
# Generate a list of 10 strings and cut it to the desired value provided from the user
for i in {1..10}; do (tr -cd '[:alnum:]' < /dev/urandom | fold -w${pass_length} | head -n 1); done
# Print the strings
printf "$pass_output\n"
printf "Goodbye, ${USER}\n"
```
## Conclusion
This is pretty much how you can use simple bash script to generate random passwords.
:warning: **As already mentioned, please make sure to use strong passwords in order to make sure your account is protected. Also whenever is possible use 2 factor authentication as this will provide additional layer of security for your account.**
While the script is working fine, it expects that the user will provide the requested input. In order to prevent any issues you would need to do some more advance checks on the user input in order to make sure the script will continue to work fine even if the provided input does not match our needs.
## Contributed by
[Alex Georgiev](https://twitter.com/alexgeorgiev17)

View File

@@ -0,0 +1,336 @@
# Automatic WordPress on LAMP installation with BASH
Here is an example of a full LAMP and WordPress installation that works on any Debian-based machine.
# Prerequisites
- A Debian-based machine (Ubuntu, Debian, Linux Mint, etc.)
# Planning the functionality
Let's start again by going over the main functionality of the script:
**Lamp Installation**
* Update the package manager
* Install a firewall (ufw)
* Allow SSH, HTTP and HTTPS traffic
* Install Apache2
* Install & Configure MariaDB
* Install PHP and required plugins
* Enable all required Apache2 mods
**Apache Virtual Host Setup**
* Create a directory in `/var/www`
* Configure permissions to the directory
* Create the `$domain` file under `/etc/apache2/sites-available` and append the required Virtualhost content
* Enable the site
* Restart Apache2
**SSL Config**
* Generate the OpenSSL certificate
* Append the SSL certificate to the `ssl-params.conf` file
* Append the SSL config to the Virtualhost file
* Enable SSL
* Reload Apache2
**Database Config**
* Create a database
* Create a user
* Flush Privileges
**WordPress Config**
* Install required WordPress PHP plugins
* Install WordPress
* Append the required information to `wp-config.php` file
Without further ado, let's start writing the script.
# The script
We start by setting our variables and asking the user to input their domain:
```bash
echo 'Please enter your domain of preference without www:'
read DOMAIN
echo "Please enter your Database username:"
read DBUSERNAME
echo "Please enter your Database password:"
read DBPASSWORD
echo "Please enter your Database name:"
read DBNAME
ip=`hostname -I | cut -f1 -d' '`
```
We are now ready to start writing our functions. Start by creating the `lamp_install()` function. Inside of it, we are going to update the system, install ufw, allow SSH, HTTP and HTTPS traffic, install Apache2, install MariaDB and PHP. We are also going to enable all required Apache2 mods.
```bash
lamp_install () {
apt update -y
apt install ufw
ufw enable
ufw allow OpenSSH
ufw allow in "WWW Full"
apt install apache2 -y
apt install mariadb-server
mysql_secure_installation -y
apt install php libapache2-mod-php php-mysql -y
sed -i "2d" /etc/apache2/mods-enabled/dir.conf
sed -i "2i\\\tDirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm" /etc/apache2/mods-enabled/dir.conf
systemctl reload apache2
}
```
Next, we are going to create the `apache_virtualhost_setup()` function. Inside of it, we are going to create a directory in `/var/www`, configure permissions to the directory, create the `$domain` file under `/etc/apache2/sites-available` and append the required Virtualhost content, enable the site and restart Apache2.
```bash
apache_virtual_host_setup () {
mkdir /var/www/$DOMAIN
chown -R $USER:$USER /var/www/$DOMAIN
echo "<VirtualHost *:80>" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e "\tServerName $DOMAIN" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e "\tServerAlias www.$DOMAIN" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e "\tServerAdmin webmaster@localhost" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e "\tDocumentRoot /var/www/$DOMAIN" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e '\tErrorLog ${APACHE_LOG_DIR}/error.log' >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e '\tCustomLog ${APACHE_LOG_DIR}/access.log combined' >> /etc/apache2/sites-available/$DOMAIN.conf
echo "</VirtualHost>" >> /etc/apache2/sites-available/$DOMAIN.conf
a2ensite $DOMAIN
a2dissite 000-default
systemctl reload apache2
}
```
Next, we are going to create the `ssl_config()` function. Inside of it, we are going to generate the OpenSSL certificate, append the SSL certificate to the `ssl-params.conf` file, append the SSL config to the Virtualhost file, enable SSL and reload Apache2.
```bash
ssl_config () {
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt
echo "SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLHonorCipherOrder On" >> /etc/apache2/conf-available/ssl-params.conf
echo "Header always set X-Frame-Options DENY" >> /etc/apache2/conf-available/ssl-params.conf
echo "Header always set X-Content-Type-Options nosniff" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLCompression off" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLUseStapling on" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLStaplingCache \"shmcb:logs/stapling-cache(150000)\"" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLSessionTickets Off" >> /etc/apache2/conf-available/ssl-params.conf
cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak
sed -i "s/var\/www\/html/var\/www\/$DOMAIN/1" /etc/apache2/sites-available/default-ssl.conf
sed -i "s/etc\/ssl\/certs\/ssl-cert-snakeoil.pem/etc\/ssl\/certs\/apache-selfsigned.crt/1" /etc/apache2/sites-available/default-ssl.conf
sed -i "s/etc\/ssl\/private\/ssl-cert-snakeoil.key/etc\/ssl\/private\/apache-selfsigned.key/1" /etc/apache2/sites-available/default-ssl.conf
sed -i "4i\\\t\tServerName $ip" /etc/apache2/sites-available/default-ssl.conf
sed -i "22i\\\tRedirect permanent \"/\" \"https://$ip/\"" /etc/apache2/sites-available/000-default.conf
a2enmod ssl
a2enmod headers
a2ensite default-ssl
a2enconf ssl-params
systemctl reload apache2
}
```
Next, we are going to create the `db_setup()` function. Inside of it, we are going to create the database, create the user and grant all privileges to the user.
```bash
db_config () {
mysql -e "CREATE DATABASE $DBNAME;"
mysql -e "GRANT ALL ON $DBNAME.* TO '$DBUSERNAME'@'localhost' IDENTIFIED BY '$DBPASSWORD' WITH GRANT OPTION;"
mysql -e "FLUSH PRIVILEGES;"
}
```
Next, we are going to create the `wordpress_config()` function. Inside of it, we are going to download the latest version of WordPress, extract it to the `/var/www/$DOMAIN` directory, create the `wp-config.php` file and append the required content to it.
```bash
wordpress_config () {
db_config
apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip -y
systemctl restart apache2
sed -i "8i\\\t<Directory /var/www/$DOMAIN/>" /etc/apache2/sites-available/$DOMAIN.conf
sed -i "9i\\\t\tAllowOverride All" /etc/apache2/sites-available/$DOMAIN.conf
sed -i "10i\\\t</Directory>" /etc/apache2/sites-available/$DOMAIN.conf
a2enmod rewrite
systemctl restart apache2
apt install curl
cd /tmp
curl -O https://wordpress.org/latest.tar.gz
tar xzvf latest.tar.gz
touch /tmp/wordpress/.htaccess
cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php
mkdir /tmp/wordpress/wp-content/upgrade
cp -a /tmp/wordpress/. /var/www/$DOMAIN
chown -R www-data:www-data /var/www/$DOMAIN
find /var/www/$DOMAIN/ -type d -exec chmod 750 {} \;
find /var/www/$DOMAIN/ -type f -exec chmod 640 {} \;
curl -s https://api.wordpress.org/secret-key/1.1/salt/ >> /var/www/$DOMAIN/wp-config.php
echo "define('FS_METHOD', 'direct');" >> /var/www/$DOMAIN/wp-config.php
sed -i "51,58d" /var/www/$DOMAIN/wp-config.php
sed -i "s/database_name_here/$DBNAME/1" /var/www/$DOMAIN/wp-config.php
sed -i "s/username_here/$DBUSERNAME/1" /var/www/$DOMAIN/wp-config.php
sed -i "s/password_here/$DBPASSWORD/1" /var/www/$DOMAIN/wp-config.php
}
```
And finally, we are going to create the `execute()` function. Inside of it, we are going to call all the functions we created above.
```bash
execute () {
lamp_install
apache_virtual_host_setup
ssl_config
wordpress_config
}
```
With this, you have the script ready and you are ready to run it. And if you need the full script, you can find it in the next section.
# The full script
```bash
#!/bin/bash
echo 'Please enter your domain of preference without www:'
read DOMAIN
echo "Please enter your Database username:"
read DBUSERNAME
echo "Please enter your Database password:"
read DBPASSWORD
echo "Please enter your Database name:"
read DBNAME
ip=`hostname -I | cut -f1 -d' '`
lamp_install () {
apt update -y
apt install ufw
ufw enable
ufw allow OpenSSH
ufw allow in "WWW Full"
apt install apache2 -y
apt install mariadb-server
mysql_secure_installation -y
apt install php libapache2-mod-php php-mysql -y
sed -i "2d" /etc/apache2/mods-enabled/dir.conf
sed -i "2i\\\tDirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm" /etc/apache2/mods-enabled/dir.conf
systemctl reload apache2
}
apache_virtual_host_setup () {
mkdir /var/www/$DOMAIN
chown -R $USER:$USER /var/www/$DOMAIN
echo "<VirtualHost *:80>" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e "\tServerName $DOMAIN" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e "\tServerAlias www.$DOMAIN" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e "\tServerAdmin webmaster@localhost" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e "\tDocumentRoot /var/www/$DOMAIN" >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e '\tErrorLog ${APACHE_LOG_DIR}/error.log' >> /etc/apache2/sites-available/$DOMAIN.conf
echo -e '\tCustomLog ${APACHE_LOG_DIR}/access.log combined' >> /etc/apache2/sites-available/$DOMAIN.conf
echo "</VirtualHost>" >> /etc/apache2/sites-available/$DOMAIN.conf
a2ensite $DOMAIN
a2dissite 000-default
systemctl reload apache2
}
ssl_config () {
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt
echo "SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLHonorCipherOrder On" >> /etc/apache2/conf-available/ssl-params.conf
echo "Header always set X-Frame-Options DENY" >> /etc/apache2/conf-available/ssl-params.conf
echo "Header always set X-Content-Type-Options nosniff" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLCompression off" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLUseStapling on" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLStaplingCache \"shmcb:logs/stapling-cache(150000)\"" >> /etc/apache2/conf-available/ssl-params.conf
echo "SSLSessionTickets Off" >> /etc/apache2/conf-available/ssl-params.conf
cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak
sed -i "s/var\/www\/html/var\/www\/$DOMAIN/1" /etc/apache2/sites-available/default-ssl.conf
sed -i "s/etc\/ssl\/certs\/ssl-cert-snakeoil.pem/etc\/ssl\/certs\/apache-selfsigned.crt/1" /etc/apache2/sites-available/default-ssl.conf
sed -i "s/etc\/ssl\/private\/ssl-cert-snakeoil.key/etc\/ssl\/private\/apache-selfsigned.key/1" /etc/apache2/sites-available/default-ssl.conf
sed -i "4i\\\t\tServerName $ip" /etc/apache2/sites-available/default-ssl.conf
sed -i "22i\\\tRedirect permanent \"/\" \"https://$ip/\"" /etc/apache2/sites-available/000-default.conf
a2enmod ssl
a2enmod headers
a2ensite default-ssl
a2enconf ssl-params
systemctl reload apache2
}
db_config () {
mysql -e "CREATE DATABASE $DBNAME;"
mysql -e "GRANT ALL ON $DBNAME.* TO '$DBUSERNAME'@'localhost' IDENTIFIED BY '$DBPASSWORD' WITH GRANT OPTION;"
mysql -e "FLUSH PRIVILEGES;"
}
wordpress_config () {
db_config
apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip -y
systemctl restart apache2
sed -i "8i\\\t<Directory /var/www/$DOMAIN/>" /etc/apache2/sites-available/$DOMAIN.conf
sed -i "9i\\\t\tAllowOverride All" /etc/apache2/sites-available/$DOMAIN.conf
sed -i "10i\\\t</Directory>" /etc/apache2/sites-available/$DOMAIN.conf
a2enmod rewrite
systemctl restart apache2
apt install curl
cd /tmp
curl -O https://wordpress.org/latest.tar.gz
tar xzvf latest.tar.gz
touch /tmp/wordpress/.htaccess
cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php
mkdir /tmp/wordpress/wp-content/upgrade
cp -a /tmp/wordpress/. /var/www/$DOMAIN
chown -R www-data:www-data /var/www/$DOMAIN
find /var/www/$DOMAIN/ -type d -exec chmod 750 {} \;
find /var/www/$DOMAIN/ -type f -exec chmod 640 {} \;
curl -s https://api.wordpress.org/secret-key/1.1/salt/ >> /var/www/$DOMAIN/wp-config.php
echo "define('FS_METHOD', 'direct');" >> /var/www/$DOMAIN/wp-config.php
sed -i "51,58d" /var/www/$DOMAIN/wp-config.php
sed -i "s/database_name_here/$DBNAME/1" /var/www/$DOMAIN/wp-config.php
sed -i "s/username_here/$DBUSERNAME/1" /var/www/$DOMAIN/wp-config.php
sed -i "s/password_here/$DBPASSWORD/1" /var/www/$DOMAIN/wp-config.php
}
execute () {
lamp_install
apache_virtual_host_setup
ssl_config
wordpress_config
}
```
## Summary
The script does the following:
* Install LAMP
* Create a virtual host
* Configure SSL
* Install WordPress
* Configure WordPress
With this being said, I hope you enjoyed this example. If you have any questions, please feel free to ask me directly at [@denctl](https://twitter.com/denctl).

View File

@@ -0,0 +1,15 @@
# Wrap Up
Congratulations! You have just completed the Bash basics guide!
If you found this useful, be sure to star the project on [GitHub](https://github.com/bobbyiliev/introduction-to-bash-scripting)!
If you have any suggestions for improvements, make sure to contribute pull requests or open issues.
In this introduction to Bash scripting book, we just covered the basics, but you still have enough under your belt to start wringing some awesome scripts and automating daily tasks!
As a next step try writing your own script and share it with the world! This is the best way to learn any new programming or scripting language!
In case that this book inspired you to write some cool Bash scripts, make sure to tweet about it and tag [@bobbyiliev_](https://twitter.com) so that we could check it out!
Congrats again on completing this book!