Calculate square root in Python 3

In this tutorial, three methods will be used to calculate the square root (sqrt) in python 3

  1. The math library.
  2. The ** operator and.
  3. The NumPy library.

 

1. The math library

It is important to import the math library. The math library is a built-in library in Python 3 core language. It is a core feature and very easy to use. First import the library

>>> import math

For example, we know that the square root of 16 is 4. In Python 3

>>> math.sqrt(16)
4.0

Or

>>> from math import sqrt
>>> sqrt(16)
4.0

2. The ** operator

You can use the power operator which is ** and calculate the square root of 16 and it will give you

>>> 16 ** 1/2
8.0

But the power operator will give you a minus result if you square root of -16 and that is mathematically impossible. It must return either an error value or an imaginary number i. Let us take an example

>>> x = -16
>>> x ** 1/2
-8.0
>>> sqrt(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

As you can see from the example above,

-16 ** 1/2 = -8

To solve this, take the absolute value of -16. This will make it possible.

>>> x = -16
>>> abs(x) ** 1/2
8.0

3. The NumPy library

Numpy is a very advanced mathematical library. Widely used by the community and is used for scientific computing. If you went to learn more about NumPy, visit http://www.numpy.org/. We will cover the installation of it and use it to calculate the square root of 16.

To install it, in Windows, run the powershell terminal from the start menu, then type the following

PS > python -m pip install numpy

In Linux Ubuntu distro, make sure to install the following dependencies:-

lamda@alexpc:~$ sudo apt install python3-pip 
lamda@alexpc:~$ sudo -H python3 -m pip install numpy # Wide user or
lamda@alexpc:~$ sudo python3 -m pip install numpy # single user

Then import sqrt from NumPy library:-

>>> from numpy import sqrt
>>> sqrt(16)
4.0

The advantage of using NumPy is scalability. You can compute an multidimensional array in one single function as follow

>>> sqrt([4,16,256])
array([ 2.,  4., 16.])
>>> sqrt([[1,2,3],[4,5,6],[7,8,9]])
array([[1.        , 1.41421356, 1.73205081],
       [2.        , 2.23606798, 2.44948974],
       [2.64575131, 2.82842712, 3.        ]])

the above examples of NumPy can be extended more and take the advantage of python language to make a very pretty easy coding experience.

How to Create Backup for MySQL Server Database

In this post, I will demonstrate MySQL server database backup. Creating a backup is a must. It provide safety for your data and full retrieve them back if something happens. It reduces the cost for data recovery if server breach and it is a good practice as IT security administrative to do it so.

In this guide I will provide you an easy way to create the backup yourself by integrating GNU tools and open source software to achieve it.

Three type of backup to follow:-

  1. Manual Backup.
  2. Semi-Automatic Backup and
  3. Automated Backup.

Manual MySQL Backup

Manual backup is very easy and straight forward. In MySQL Database you must have a root access to the service. Type the following

fahad@my-server.com # mysqldump -u root --all-databases | gzip > ~/database_backup.sql.gz

The above code will dump all databases in a single SQL file and compress the file to gunzip. Then you can transfer it back to your own computer either by using WinSCP (If you have a Windows) or using Rsync in Linux. Rsync is very easy to use. In your computer type tbe following :-

mypc@fahad $ rsync fahad@my-server.com:~/database_backup.sql.gz ~/ --progress

Also, you can dump the database and change the file name to a datetime format using date program

fahad@my-server.com # mysqldump -u root  --all-databases | gzip > "$(date "+%Y-%m-%d_%H:%M:%S")-db.sql.gz"

The output will be

2019-03-02_16:18:37-db.sql.gz
How the file will appear in the server
Example of the output of the non date formatted and formatted date

In small scale application, any developer can backup manually from the MySQL server easily. But in terms of quite good volume, IT administrator must consider a new ways for backups other than manual backup.

Semi-Automatic MySQL Backup

In semi-automatic backup, we will introduce server side automatic backup to specified directory in the server (like /var/lib/mysql-backup). The backup will run chronologically using a time-based job scheduler. Then all the backup files can be retrieved from the server using your favorite tools such as WinSCP or rsync or whatever you like.

In Semi-automatic backup, we will use the following programs

  1. Cron Job, and
  2. Rsync

Cron job will schedule a backup every defined time to a specified location in the server using file time formatting. Then you can download all the backup files manually to your computer. But first, we must set up the server to create automatic backups. Let’s us assume that the directory located in

/var/lib/my-backups/mysql

First create the directory file

fahad@my-server.com # mkdir /var/lib/my-backups && mkdir /var/lib/my-backups/mysql

Then type the following, this will open cron task file.

fahad@my-server.com # crontab -e 

Make sure that you are running as root

Open a crontab file in server to create automatic mysql database backup
Crontab file for root user

Type the following at the end of the file

0 1 * * * mysqldump -u root  --all-databases | gzip > "$(date '+\%Y-\%m-\%d_\%H:\%M:\%S")-db.sql.gz"

The above code do the following:-

  1. First, run mysqldump built-in program with root user, and dump all the databases using –all-databases argument.
  2. Then pass all the databases dump into gzip compressor.
  3. After that, gunzip will write the archive to a file in date time format.

Save and exit the file by typing (:wq) or CTRL+X CTRL+Y then press Enter for Nano file editor.

Then from your computer type the following

mypc@fahad $ mkdir ~/myserverbackups
mypc@fahad $ rsync --progress --recursive fahad@my-server.com:/var/lib/my-backups/mysql/* ~/myserverbackups/

The backup will run daily at 1 A.M. and the file will be stored in

/var/lib/my-backups/mysql

Automatic MySQL Backup

After creating a Cron job in semi-automatic backup, add another Cron job in your personal Linux computer to retrieve the backup automatically by using rsync for data synchronization

Open crontab and add the following code

10 1 * * * rsync --progress --recursive --ignore-existing fahad@my-server.com:/var/lib/my-backups/mysql/* ~/myserverbackups/

I recommend you to use the following argument--ignore-existing to only copy newer files and skip copying existing files

What is SSH Attack and How to Protect Your Website

Cmatrix software for Linux

In this post. I will demonstrate how SSH attack works and how to prevent your server from it.

SSH attack by definition is to try to access an internal server in the local or wide network. The person who went to access the server have many intentions to do, like stealing vital data, destroying server and demanding money to restore all the data on it.

The term SSH brute-force is one of many types of SSH attacks. SSH brute force is a username and password guessing mechanism to gain access to enabled secure shell users. In the internet, servers expose their default SSH port number (22) to the public and use a common usernames and passwords for either access convenience or lack of expertise in the information technology. If the attack is successful, the hacker may gain root access to the machine, harvest data and destroy the machine and/or inject SSH brute-force bot to attack other local servers or online servers.

How to Protect Your server from SSH attack?

Here is a list of how to protect your server from SSH attack.

Update Your server.

Yes updating your server to the latest version is one of the key factor to prevent SSH attack. Espcecially if you are dealing with an out of date server operating system. You need to update the SSH server.

In debian distro, use the following command to update your server to the latest version

me@jessy# apt-get update && apt-get upgrade -y

Change OpenSSH port number

Head to /etc/ssh directory

# cd /etc/ssh

Open OpenSSH configuration, but before that, make a backup:-

# cp sshd_config sshd_config.backup

Then open the sshd_config with your desired editor, I prefer Vim:-

# vi sshd_config

Change the following line:-

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

To

Port 842
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

Change the port number according to what you need. I chose 842, it depends on you. Then restart the OpenSSH service

me@wheezy# service ssh restart 

Use VPN (Virtual Private Network)

This is one of many solutions available to mitigate any problem against SSH attack, once and for all. Is by using VPN.

Client (YOU) -----> VPN Server (Gateway) <----> (Local Network) <----> ( Your Server )
Local IP | 10.128.0.5 | |10.128.0.1/24| | 10.128.0.10 |
Public IP | Something | | Something |

Edit the following configuration to allow local network access. To know the static IP of your local network, use ifconfig command to get your local IPv4 address. 

me@wheezy $ ifconfig
ens4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1460
inet 10.128.0.10 netmask 255.255.255.255 broadcast 0.0.0.0
inet6 fe80::4001:aff:fe80:2 prefixlen 64 scopeid 0x20<link>
ether 42:01:0a:80:00:02 txqueuelen 1000 (Ethernet)
RX packets 1841401 bytes 279033542 (279.0 MB)
RX errors 0 dropped 0 overruns 0 frame 551261
TX packets 3925046 bytes 541319731 (541.3 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 26850 bytes 10265384 (10.2 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 26850 bytes 10265384 (10.2 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

In sshd config, change the following:-


#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

TO

#Port 22
#AddressFamily any
ListenAddress 10.128.0.10
#ListenAddress ::

Then restart ssh server.

You can find many VPN solutions, one of them is openvpn-install.

Disable Password login on OpenSSH and Use SSH key Instead

Before disable it. Generate your default SSH key from your computer. It is very simple, if you are using a Linux distribution, write the following code:-

$ ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ploto/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/ploto/.ssh/id_rsa.
Your public key has been saved in /home/ploto/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:OCpNlym9v5pnkE3p6SytfagnWzpVQKFq3iw+o/WLXf0 ploto@someserver
The key's randomart image is:
+---[RSA 2048]----+
|       .o.       |
|       ..        |
|      .  o       |
|     o +o .      |
|    = B=So       |
|   = *oo=.       |
|  . * +*o..      |
|   +o=+BO ..     |
|  ..oo@&+o  E    |
+----[SHA256]-----+

If you are using a Windows Operating System, you can use Putty Key generator from the start menu, or download it from Putty Official Website

Then copy that key to your server

$ ssh-copy-id dorango@my-server
dorango@my-server's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'dorango@my-server'"
and check to make sure that only the key(s) you wanted were added.

Then open sshd_config and edit the following line

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

To

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication no
#PermitEmptyPasswords no

Then restart your OpenSSH server.

Disable OpenSSH for Internet Wide

YES disable it. No more SSH brute-force. This is the last thing you wanna do right, YES. because many cloud service providers offer a secure tunnel to your server (VPN – Virtual Private Network), you need to know your private subnet. Let’s say your cloud local network is 192.168.1.0/16, you can authorize SSH access to this subnet and block internet-wide SSH connection. Change the firewall rule to allow SSH port to certin address

# ufw allow from 192.168.1.0/16 to any port ssh

Disable OpenSSH forever

This is the last thing to do, I don’t recommend it.

# systemctl stop sshd
# systemctl disable sshd
# systemctl mask sshd

Install Visual Studio in Ubuntu 18.04

The Easy Way

You can install visual studio code in Ubuntu from snap environment

alex@alexa-pc:~$ sudo snap install vscode

The problem with the snap application that they are installed in sand boxed environment. Hard to recommend it.

Another way around

Go to https://code.visualstudio.com/ and click for the .deb package. After download. Press CTRL+ALT+T, the terminal will appear and write:-

alex@alexa-pc:~$ cd ~/Downloads
alex@alexa-pc:~/Downloads$ sudo dpkg -i code_1.27.2-1536736588_amd64.deb

And enjoy using it. The version 1.27.2-1536736588 from previous code is changing.