January 7, 2023

How to Deploy Django with Nginx Gunicorn and Supervisor on Ubuntu 22.04

Learn how to deploy a Django application with Nginx, Gunicorn, and Supervisor on Ubuntu 22.04. Get step-by-step instructions for setting up a secure, reliable web server using best practices that will help you keep your web application.

Django with Nginx Gunicorn and Supervisor on Ubuntu 22.04

Create Separate User and Group

sudo groupadd --system project-group

Add New User

sudo useradd --system --gid project-group --shell /bin/bash --home/projectroot project-user 

Create a Root Folder for the project

mkdir ~/projectroot
cd ~/projectroot

Then create a virtual environment for the Project

virtualenv app1

Go to the environment folder and activate the virtual environment

cd app1
source bin/activate

Create the requirements.txt file for the Django or flask project

sudo vi requirements.txt

Add the packages then save the file.

Create a log folder in the environment folder

mkdir logs

Now clone the Django or flask project from the GitHub repository

git clone url.git

change the ownership permission for the project and other files

sudo chown -R project-user:project-group .

Create a gunicorn script in bin folder

sudo vi bin/gunicorn_start

Paste the below script into the file

#!/bin/sh

NAME='Project Name'
DJANGODIR=/projectroot/app1/django_project
SOCKFILE=/projectroot/app1/run/gunicorn.sock
USER=project-group
GROUP=project-user
NUM_WORKERS=3
DJANGO_SETTINGS_MODULE=django_project.settingsprod
DJANGO_WSGI_MODULE=django_project.wsgi
TIMEOUT=120

cd $DJANGODIR
source ../bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH

RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR

exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
  --name $NAME \
  --workers $NUM_WORKERS \
  --timeout $TIMEOUT \
  --user=$USER --group=$GROUP \
  --bind=unix:$SOCKFILE \
  --log-level=debug \
  --log-file=-

then make this file Executable

chmod +x bin/gunicorn_start

Now install the Supervisor

sudo apt install supervisor

Create a new config file in the supervisor

sudo vi /etc/supervisor/conf.d/django_project.conf

then add the below script and save

[program:django_project]
command = /projectroot/app1/bin/gunicorn_start
user = project-user
stdout_logfile = /projectroot/app1/logs/supervisor.log
redirect_stderr = true
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8
supervisorctl reread
supervisorctl update
supervisorctl status

Now create the nginx configaration for the project

sudo vi /etc/nginx/sites-available/django_project.conf

paste the below configaration.

upstream django_project_app_server {
server unix:/saulroot/saul_3_6_4/run/gunicorn.sock fail_timeout=0;
}

server {
listen 80;
server_name example.com;
access_log /projectroot/app1/logs/nginx-access.log;
error_log /projectroot/app1/logs/nginx-error.log;

location /static/ {
alias /projectroot/app1/django_project/static/;
}

location /media/ {
alias /projectroot/app1/django_project/media/;
}

location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header Host $http_host;

proxy_redirect off;

if (!-f $request_filename) {
proxy_pass http://django_project_app_server;
}
}
}

Restart Nginx

sudo nginx -t
sudo systemctl restart nginx

open the browser http://example.com

January 5, 2023

How to Install Arduino IDE 2.0(AppImage) on Ubuntu 22.04

In his article we will discuss how to install Arduino IDE 2.0 AppImage Ubuntu 22.04. The following has been performed with the following versions:

    • Ubuntu 22.04 64bits

    • Arduino IDE 2.0.3

Note that you can install the Arduino IDE from Ubuntu Software, but this is not the last version (1.8.19 while the last version is 2.0.3). Arduino IDE can also be installed with the AppImage, but its integration in Ubuntu is not nice. For example, adding the app in your launcher is not easy.

Download

First, download the AppImage file from the Arduino official website.

arduino IDE 2.0.3 AppImage

Install files

Open a terminal in the folder where the AppImage file has been download. change the file permission with following command:

cd Downloads
chmod +x arduino-ide_2.0.3_Linux_64bit.AppImage

Then Extract the file with the following command:

./arduino-ide_2.0.3_Linux_64bit.AppImage --appimage-extract

Create a folder in home

mkdir ~/arduino

copy and rename the extracted above AppImage files to arduino directory

cp -r squashfs-root/* ~/arduino/

Launch IDE

Go to the installation folder:

cd ~/arduino

Launch the Arduino IDE with the following command:

./arduino-ide

The IDE should open.

arduino IDE 2.0.3

Create the app desktop shortcut

To add the Arduino IDE to the launcher, create a new file arduino.desktop in the folder ~/.local/share/applications.

cd ~/.local/share/applications
sudo vi arduino.desktop

Paste the following command and change Exec and Icon path according to your folder path structure.

[Desktop Entry]
Version=1.0
Type=Application
Name=Arduino IDE 2.0
Icon=/home/username/arduino/arduino-ide.png
Exec=/home/username/arduino/arduino-ide
Comment=The Arduino Software IDE
Categories=Development;IDE;
Terminal=false
arduino IDE 2.0.3 Launcher

Happy Coding :)












December 24, 2022

Introduction to MQTT Client Tools using CLI

MQTT (Message Queuing Telemetry Transport) is a machine to machine internet of things connectivity protocol. It is a Publish-Subscribe  very lightweight transport protocol and it is a useful protocol where the bandwidth is a premium. 

In this tutorial we are going to use Mosquitto broker, will see how to install it and use its very important tool mosquitto-clients. 

Installing Mosquitto:

To install Mosquitto in Ubuntu open terminal and type following command 

> sudo apt install mosquitto 

Mosquitto broker will install it on your system. You can check it in the cd /etc/mosquitto directory. 

Now to install client tools type following command

> sudo apt install mosquitto-clients 

Installation part is done now we will to look at some examples of using this mosquitto-client tools 
for publishing and subscribing.

Now lets check that our mosquitto broker is installed properly or not for that type command

> sudo service mosquitto status 

You will see mosquitto is active (running). If not then try typing ‘start’ instead of ‘status’ in the previous command. 

Use of Mosquitto Client tools:

We will start with Subscriber first because MQTT Broker requires it to forward  messages to the clients that are subscribed to a topic/topics. 

Now type the following command to connect with the broker as a subscriber. (-d debug flag set ) and subscribe to topic ‘test/topic’

> mosquitto_sub -h localhost -t test/topic -d

Once entered, the client will always be in listening mode to exit press ctrl+c. 

Useful Flag Options: 

-p → set port number default is 1883
-h → ip address or host name
-t →Topic name 
-u →username
-P →password
-i →provide client id
-r →sets retain flag
-n →sends Null message useful for learning retain message
-q →for Quality of service (0,1,2)
-k →keep alive 
For more info use > mosquitto_sub –help

Now using mosquitto_pub we will publish message to topic ‘test/topic’ .

> mosquitto_pub -h localhost -t test/topic -m "first message" -d

After publishing message publisher client will disconnect automatically. 

Subscribers will receive message on topic ‘test/topic’. 

Publishing using username and password

> mosquitto_pub -h localhost -t test/topic -u nimesh -P passwd -m "first message" -d

Remember that -P (capital P) is for password and -p is for port number.

Publish with Retain Flag and QoS Flag:

use of -r and -q flag

In PUBLISH packet you will notice that q1, r1 flag will be set. 

Retain flag will help to inform the broker to keep the last message on that topic. This feature allows you to store a single message per MQTT topic on broker and send it to all current and future subscribers. 

To save a retained message, simply set a retained flag when publishing it to the broker.

Publish with Client Name:

This option is useful when testing client restrictions using prefixes or client names with ACLs. Uses -i option. You could also use the -I option if you just needed prefixes.

> mosquitto_pub -h localhost -t test/topic -i client_01 -m "first message" -d

Publishing JSON Data: 

Json data always has a key-value pair. When we want to publish data using mosquitto_pub always keep in mind one think that dont use quotes. 

Eg. don’t use {“LED_Status”:”ON”} but instead use: {\”LED_Status\”:\”ON\”}.


If you are publishing multiple datas then you need to put the entire string in quotes: 

Eg. "{\"temp1\":22,\"temp2\":45}" 

Subscribe using -C flag:

A useful option is the -C flag which will disconnect after receiving a certain number of messages. 

> mosquitto_sub -h localhost -t test/topic -C 3 

While publishing with -l flag publisher will not disconnect and we can enter message on terminal. 

Subscribe using -v flag : 

-v means verbose. It will show the topic name as well as the message.

There are more options available that you can try. In the end let's conclude that mosquitto_sub and mosquitto_pub client utility is an excellent tool for troubleshooting and testing purposes for MQTT and Broker.

 

December 7, 2022

Run selenium cases in linux server using Chrome Browser

In this article we will see How to run selenium cases in linux server using Chrome Browser in Headless Mode.

Detailed Steps:

[root@localhost ~]# yum-config-manager --enable ol7_optional_latest

[root@localhost ~]# wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm


[root@localhost ~]# yum -y install redhat-lsb libXScrnSaver

[root@localhost ~]# yum -y install google-chrome-stable_current_x86_64.rpm

 Install xvfb as root:

[root@localhost ~]# yum install xorg-x11-server-Xvfb


Start display:

[root@localhost ~]# Xvfb -ac :99 -screen 0 1280x1024x16 & export DISPLAY=:99


Test The Code:

ChromeOptions chromeOptions = new ChromeOptions();

chromeOptions.setHeadless(true);

System.setProperty("webdriver.chrome.driver", "./src/test/resources/drivers/linux/chromedriver");

WebDriver driver = new ChromeDriver(chromeOptions);

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get("https://demo.example.com/admin");

Trobuleshoot:

1.If the driver is not executable: Copy chromedriver and give 777 permission

2.unknown error: cannot find Chrome binary - Install chrome browser

3.unknown error: Chrome failed to start: crashed. - Run in headless mode 

December 1, 2022

How to change Mysql authentication method from auth_socket to mysql_native_password

In this article, we will see how we can change the MySQL root user default (Auth_Socket) authentication method to mysql_native_password.

Auth_socket Authentication

Auth_socket authentication is a server-side default authentication plugin that is used to authenticate the client input in order to access databases. Auth_Socket authentication plugin uses the SO_PEERCRED Unix socket option to obtain information about the user running the client program.

Mysql_native_password Authentication

The other authentication method is mysql_native_password authentication which is known as a traditional method to authenticate, it is not secure as Auth_socket authentication it uses just a hash of the password. This authentication method is not recommended for authentication.

The process to switch auth_socket to mysql_native_password:

First of all, check the current authentication method for this you can use the following command.

mysql> SELECT user, authentication_string,plugin,host FROM mysql.user;

To configure the root account to authenticate with a password, run the following ALTER USER command. Be sure to change the password to a strong password of your choosing

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'PASSWORD';

Query OK, 0 rows affected (0.00 sec)

Now run the following command to flush the tables and implement new changes

mysql> FLUSH PRIVILEGES;

Query OK, 0 rows affected (0.00 sec)

Now you can see we have changed the authentication method from auth_socket to mysql_native_password

How to Install MySQL on CentOS 8 / RHEL 8 / Oracle Linux 8

In this quick guide, i will show you how to install MYSQL on CentOS 8 / RHEL 8 / Oracle Linux 8 instead of MariaDB.

MariaDB is the default implementation of MySQL in Red Hat Enterprise Linux 8 (RHEL 8) or CentOS 8.

MariaDB is a community-developed fork of the MySQL database project, and provides a replacement for MySQL.

However, in some cases, you still need to install MySQL as your deployment database on you Linux server.

Remove MariaDB installation :

If you server already have MariaDB database server installed, i would suggest you remove it first to avoid conflict.

[root@localhost ~]# sudo yum remove mariadb-server -y

2. Download MySQL 8.0 repo file :

[root@localhost ~]# wget https://dev.mysql.com/get/mysql80-community-release-el8-4.noarch.rpm

3. Install MySQL 8 repo file :

[root@localhost ~]# sudo rpm -ivh mysql80-community-release-el8-4.noarch.rpm

4. Install MySQL 8 database server :

[root@localhost ~]# sudo yum install mysql-server -y

Install MySQL on CentOS 8


5. How to Start MySQL server in linux :

[root@localhost ~]# sudo systemctl start mysqld

6. Enable auto start at boot :

[root@localhost ~]# sudo systemctl enable mysqld

7. At the initial start up of the MySQL database server, the following happens, given that the data directory of the server is empty:

a) The server is initialized.

b) An SSL certificate and key files are generated in the data directory.

c) The validate_password plugin is installed and enabled.

d) A superuser account ‘root’@’localhost is created. The initial root password created can be found in the error log file. You can get the password by issue the following command :

[root@localhost ~]# sudo grep 'temporary password' /var/log/mysqld.log

2016-06-19T23:08:09.439963Z 1 [Note] A temporary password is generated for root@localhost: sj-mMM;o%6Ll

8. Harden MySQL Server

Run the mysql_secure_installation script to address several security concerns in a default MySQL installation.

You will be given the choice to change the MySQL root password, remove anonymous user accounts, disable root logins outside of localhost, and remove test databases. It is recommended that you answer yes to these options.

Install MySQL on CentOS 8 Result

Resource : http://dev.mysql.com/

November 25, 2022

Install MQTT Broker (Mosquitto) on centos 8

 In this article we will see how to Install MQTT Broker (Mosquitto) on centos 8.

We will be using the Eclipse-Mosquitto for MQTT configuration. 

Overview of Steps:

Install the Mosquitto

Configure The Mosquitto

Test the Server

Detailed Steps:

Step 1. Install the Mosquitto

[root@localhost ~]# sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm -y

[root@localhost ~]# sudo yum -y install mosquitto

[root@localhost ~]# sudo systemctl start mosquitto

[root@localhost ~]# sudo systemctl enable mosquitto

Step 2. Configure The Mosquitto with Auth, let's choose username/password auth.:

[root@localhost ~]# sudo mosquitto_passwd -c /etc/mosquitto/passwd username

then Choose the password

Step 3. Adding Port: Run the following command to allow port in firewall:

[root@localhost ~]# sudo firewall-cmd --permanent --zone=public --add-port=1883/tcp

[root@localhost ~]# sudo firewall-cmd --reload

Step 4. Test The Server

[root@localhost ~]# mosquitto_sub -t demo/one -h 127.0.0.1 -u username -P password -p 1883

[root@localhost ~]# mosquitto_pub -t demo/one -h 127.0.0.1 -u username -P password -p 1883 -m '{"message": 1}'



November 20, 2022

How to Build Your Own Discord Bots For Free in 5 Minutes

Think Discord is just a chat app? Think again! With these amazing tools and tutorials, you'll be able to build bots for your Discord server in 5 minutes! It doesn't matter if you've never coded before, now there's no excuse for not having a fully automated and customized Discord server.

# main.py

from flask import Flask

from threading import Thread

app = Flask('')

@app.route('/')

def home():

    return "Hello. I am alive!"

def run():

  app.run(host='0.0.0.0',port=8080)

def keep_alive():

    t = Thread(target=run)

    t.start()

Verify URL - https://discord.com/api/oauth2/authorize?client_id=[Client ID]&permissions=[Permission Integer]&scope=bot

# keep_ailve.py

import discord

import os

from keep_alive import keep_alive

client = discord.Client()

@client.event

async def on_ready():

    print('We have logged in as {0.user}'.format(client))

@client.event

async def on_message(message):

    if message.author == client.user:

        return

    if message.content.startswith('ping'):

        await message.channel.send('pong!')

client.run(os.getenv('TOKEN'))


 


November 19, 2022

How to Create MacOS Monterey Bootable USB on Mac

In this article we will see how to Create MacOS Monterey Bootable USB on Mac.

We will be using the mac command line terminal to create a bootable disk. 

This article has been created with the intention of helping MacOS Monterey Bootable USB users who are looking for a tutorial on how to create a MacOS Monterey Bootable USB on Mac.

Overview of Steps:

  • Download the Image file
  • Create Bootable Drive

Detailed Steps:

Step 1. Download the image file of MacOS Monterey using Safari Browser. 

https://apps.apple.com/us/app/macos-monterey/id1576738294?mt=12


Step 2. Insert the disk format the drive as shown in the below video.