Database operations in Python (Tutorial 2019)

 

Database operations in Python

Database operations in Python are fairly simple. This tutorial using SQLite3 for implementing database operations such as retrieving and updating and deleting using Python.

 

Let us start with SQLite3

Consider this code:

<code>
#!/usr/bin/python3
import sqlite3
def main():
db = sqlite3.connect('test.db')
db.row_factory = sqlite3.Row
db.execute('drop table if exists test1')
db.execute('create table test1 (t1 text, i1 int)')
db.execute('insert into test1 (t1, i1) values (?, ?)', ('Babu', 1))
db.execute('insert into test1 (t1, i1) values (?, ?)', ('Mana', 2))
db.execute('insert into test1 (t1, i1) values (?, ?)', ('Bappa', 3))
db.execute('insert into test1 (t1, i1) values (?, ?)', ('Babua', 4))
db.execute('insert into test1 (t1, i1) values (?, ?)', ('Anju', 5))
db.execute('insert into test1 (t1, i1) values (?, ?)', ('Patai', 6))
db.execute('insert into test1 (t1, i1) values (?, ?)', ('GasaBuddhu', 7))
db.execute('insert into test1 (t1, i1) values (?, ?)', ('Tapas', 8))
db.commit()
DatabaseRead = db.execute('select * from test order by i1')
for row in DatabaseRead:
# print(dict(row))
print(row['t1'])
# print(row['t1'], row['i1'])
# print(type(row))
if __name__ == "__main__":main()
</code>

If you run this code, you will see a list of names I just added. As you see, we have connected with a database, “test”. Next, we added a table with two columns. The first column is the id integer and we keep the ID of each name inside it. The second column is the placeholder of the text. We keep a few names there.

 

You can write the same code and test it. It will give you the same result. Once you run the code, you will find that a file “test.db” has been created inside your project.

 

MySQL for Big Project

SQLite3 is good for a small amount of work. But for a big project, it is better to opt for a database like MySQL. To work with MySQL in Python3 you need to download and install MySQL connector.

 

The download and installation part is quite easy. In Python2 you can by default import MySQL Connector. But for Python3, you need to download the file. Open Welcome to Python.org and search for MySQL Connector.

 

Download the file and run “http://setup.py”.

Once you download and install the MySQL Connector module it is fairly simple and easy to connect to any MySQL database. Consider this code where we simply connect to a MySQL database and have a printout “connected.” 

 

If MySQL or any database operation is completely new to you, it is better to learn about the simple database operations and database query language. In Windows or Linux, installing PHPMyAdmin is very easy. Just install it and you need not to write all the SQL code to build a database and all the tables.

 

Let us assume that we have a database called “python-MySQL”. In that database, we have some tables. Now we are going to connect to that database first.

<code>
#!/usr/bin/python3
import mysql.connector
from mysql.connector import Error
def ConnectionTest():
### connecting to MySQL Database ###
try:
### you can either use a dictionary object or you can connect directly ###
### using a dictioanry connection object ###
kwargs = dict(host = 'localhost', database = 'python_mysql', user = 'root', password = 'pass')
conn = mysql.connector.connect(**kwargs)
### connecting directly ###
connection = mysql.connector.connect(host = 'localhost',
database = 'python_mysql',
user = 'root',
password = 'pass')
if conn.is_connected():
print("Connected from 'conn' object")
except Error as e:
print(e)
finally:
connection.close()
if __name__ == "__main__":
ConnectionTest()
</code>

It will give us a printout “Connected from a conn object”. It means the database connection has been set up. Now it is time to retrieve the value from the table.

 

In this database, we have two tables. One is of “authors” and the other is “blogs”. MySQL Connector class has all the functions needed to perform any task to those tables. You can fetch all the records. You can decide how many blogs or how many authors you would like to fetch. The following code shows you both. But a few parts have been commented out.

 

To test this code you need to have a database first. Name it “python-MySQL”. Next, you need to have two tables called “authors” and “blogs”. You also need to fill up those tables.

 

It is always better to search online and download a ready-made MySQL database and tables. They are available. It is highly suggested that you search for MySQL Connector and see what you find.

 

In the following code, please go through the commented sections also. That says a lot about how you can retrieve your records and show them to the world.

<code>
#!/usr/bin/python3
import mysql.connector
from mysql.connector import Error
def RetrieveValues():
try:
kwargs = dict(host = 'localhost', database = 'python_mysql', user = 'root', password = 'pass')
conn = mysql.connector.connect(**kwargs)
### shows you how to query data from a MySQL database in Python by using MySQL Connector/Python API
# such as fetchone() , fetchmany() , and fetchall() ###
if conn.is_connected(): cursors = conn.cursor() cursors.execute('SELECT * FROM authors')
# row = cursors.fetchone()
# output (1, 'Bel and the Dragon ', '123828863494')
######
# now we try to get all the blogs
# row = cursors.fetchall()
# print(type(row))
# output <class 'list'>, so we can use for loop
# for blogs in row:
# print(blogs)
# it will give us list of all the blogs
######
### now we give the size of how many blogs we want to get ###
# HowManyblogs = 8
# row = cursors.fetchmany(HowManyblogs)
# for blogs in row:
# print(blogs)
# we get the output of 8 blogs
row = cursors.fetchall()
for blogs in row:
print(blogs)
except Error as e:
print(e)
finally: conn.close()
if __name__ == "__main__":
RetrieveValues()
</code>

 

We have used the try and error method so that if the connection fails, it would not show an ugly “Error” message on your project. Second, this method is quite direct. You can also use a configuration file to do the same thing. 

 

It is strongly advisable to use a configuration file (we say “config file”). The configuration file has all the things necessary to connect to the database. We can write in the configuration file like this and save it as “mysql_config.ini”.

<code>
[mysql]
host = localhost
database = YourDatabaseName
user = root
password = pass
</code>
Let us see how this “.ini” file can be parsed through our Python code. We save this file as “MySQL_Connector.py”.
<code>
#!/usr/bin/python3
from configparser import ConfigParser
def ReadingMySQLConfig(filemame = 'mysql_config.ini', section = 'mysql'):
parser = ConfigParser()
parser.read(filemame)
db = dict()
if parser.has_section(section):
items = parser.items(section)
for item in items:
db[item[0]] = item[1]
else:
raise Exception('{0} not found in the {1} file'.format(section,
filemame))
return db
</code>

 

You see that we have imported the necessary modules for parsing the configuration file and finally we have used that configuration file to connect to the database.

 

And in the above code of “MySQL_Connector.py” we have included that “mysql_config.ini” file in this line—def ReadingMySQLConfig(filemame = 'mysql_config.ini', section = 'mysql'):—as an argument.

How we can use this configuration file to test our connection is shown below.

<code>
#!/usr/bin/python3
from mysql.connector import MySQLConnection, Error
from MySQL_Connector.mysql_config import ReadingMySQLConfig def Connect():
kwargs = ReadingMySQLConfig() MyConnection = MySQLConnection(**kwargs) try:
if MyConnection.is_connected():
print("Connected")
except Error as e:
print(e)
finally:
MyConnection.close()
if __name__ == "__main__":
Connect()
</code>

 

Now we have decoupled our code more. We are able to divide it into small segments so that our connection code looks extremely small and organized. But you can always connect to your MySQL database like below.

<code>
#!/usr/bin/python3
# -*- coding: utf-8 -*-import mysql.connector
from mysql.connector import Error def connect():
""" Connect to MySQL database """
try:
conn = mysql.connector.connect(host='localhost',
database='YourDatabase',
user='root',
password='YourPassword')
if conn.is_connected():
print('Connected to MySQL database')
except Error as e:
print(e)
finally:
conn.close()
if __name__ == '__main__':
connect()
</code>

 

Now the time has come to retrieve records from the database. We are able to connect to the database. Now, there should not be any trouble fetching records from the tables of the database. We have two built-in methods in our Python library.

The methods are “fetchmany()” and “fetchall()”.

The first method, “fetchmany()”, gives you the liberty to decide how many rows you are going to fetch. Let us see the code:

<code>
#!/usr/bin/python3
from mysql.connector import MySQLConnection, Error
from Databases.python_mysql_dbconfig import read_db_config def iter_row(cursor, size=10):
while True:
rows = cursor.fetchmany(size)
if not rows:
break
for row in rows:
yield row
def query_with_fetchmany():
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT * FROM EMPLOYEE")
# EMPLOYEE is the table name
for row in iter_row(cursor, 10):
print(row)
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
query_with_fetchmany()
</code>
The method “fetchall()” brings all the records from a table.
<code>
#!/usr/bin/python3
from mysql.connector import MySQLConnection, Error
from Databases.python_mysql_dbconfig import read_db_config def query_with_fetchall():
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT * FROM EMPLOYEE")
rows = cursor.fetchall()
print('Total Row(s):', cursor.rowcount)
for row in rows:
print("First Name = ", row[0])
print("Second Name = ", row[1])
print("Age = ", row[2])
print("Sex = ", row[3])
print("Salary = ", row[4])
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
query_with_fetchall()
</code>

You see how we can fetch the records as our requirements. Now let us try to test the insertion process. In our CRUD application, the first “C” stands for “Create.” Here the word “Create” means nothing but the insertion of new records. Through MySQL Connector it is quite simple. All you need is that the connection must be on. After that, you need to insert your records.

 

Here is the code. We have a “blog” table in our database and we are going to insert two records into it. One is the title of the blog and the other is the ISBN code of the blog.

<code>
#!/usr/bin/python3
from mysql.connector import MySQLConnection, Error
from MySQL_Connector.mysql_config import ReadingMySQLConfig def Insertblogs(blogs):
query = "INSERT INTO blogs(title, isbn) VALUES(%s, %s)"
try:
kwargs = ReadingMySQLConfig() MyConnection = MySQLConnection(**kwargs) if MyConnection.is_connected():
cursor = MyConnection.cursor()
cursor.executemany(query, blogs)
MyConnection.commit()
except Error as e:
print(e)
finally:
MyConnection.close()
def main():
blogs = [("Testblog", 1236547890)]
Insertblogs(blogs)
print("Inserted one blog")
if __name__ == "__main__":
main()
</code>

 

We have successfully inserted one blog title and ISBN code. The next process will be updating that title and ISBN code. That is also very easy. All you need is the unique ID of the blog. Once you have provided the unique ID of the blog, you can update it easily.

<ocde>
#!/usr/bin/python3
from mysql.connector import MySQLConnection, Error
from MySQL_Connector.mysql_config import ReadingMySQLConfig def Updateblogs(blog_id, title):
kwargs = ReadingMySQLConfig()
data = (title, blog_id)
query = "UPDATE blogs SET title = %s WHERE id = %s"
try:
MyConnection = MySQLConnection(**kwargs)
cursor = MyConnection.cursor()
cursor.execute(query, data)
MyConnection.commit()
except Error as e:
print(e)
finally:
MyConnection.close()
def main():
for id in range(1, 25):
if id == 3:
Updateblogs(id, "I Have A Dream")
print("One blog has been updated")
elif id == 4:
Updateblogs(id, "Laravel 5 Unfolded")
print("One blog has been updated")
elif id == 5:
Updateblogs(id, "Play With Python")
print("One blog has been updated")
if __name__ == "__main__":
main()
</code>

 

We have successfully updated three blogs which have unique IDs of 3, 4, and 5, respectively. Finally, we will see how we can delete a record. To delete a record, once again you need the unique ID.

<code>
#!/usr/bin/python3
from mysql.connector import MySQLConnection, Error
from MySQL_Connector.mysql_config import ReadingMySQLConfig def Deleteblogs(blog_id):
kwargs = ReadingMySQLConfig()
query = "DELETE FROM blogs WHERE id = %s"
try:
MyConnection = MySQLConnection(**kwargs)
cursor = MyConnection.cursor()
cursor.execute(query, (blog_id,))
MyConnection.commit()
except Error as e:
print(e)
finally:
MyConnection.close()
def main():
id = 87
Deleteblogs(id)
print("Deleted ", id, "number of blog from blogs")
if __name__ == "__main__":
main()
</code>

In this code, this line—“cursor.execute(query, (blog_id,))”—is extremely important. You probably notice that we have used a “,” separator after the “blog_id”. It is your task to find out why this comma separator has been used. The only clue is it is related to either “tuples” or “lists”. It is your task that you find out what is the actual reason.

 

Like every modern version of relational databases, MySQL also allows you to keep a binary large object inside it. Normally when you write numbers or strings they do not take up much space. But what about the images?

 

Let us assume that we have an author table where we need to keep images for the authors. We may also want to keep the cover pictures of the blogs in our blog table.

 

Normally this image or any binary large object is called, in short, “BLOB”. Let us update our author table with an image and see how it works.

<code>
#!/usr/bin/python3
from mysql.connector import MySQLConnection, Error
from MySQL_Connector.mysql_config import ReadingMySQLConfig def ReadFile(filename):
with open(filename, 'rb') as f:
images = f.read()
return images
def UpdateImage(author_id, filename):
kwargs = ReadingMySQLConfig()
data = ReadFile(filename)
query = "UPDATE authors SET photo = %s WHERE id = %s"
args = (data, author_id)
try:
MyConnection = MySQLConnection(**kwargs)
cursor = MyConnection.cursor()
cursor.execute(query, args)
MyConnection.commit()
except Error as e:
print(e)
finally:
MyConnection.close()
def main():
id = 47
UpdateImage(id, "/home/hagudu/Pictures/ss.jpg")
print("Image of author ID", id, "has been updated.")
if __name__ == "__main__":
main()
</code>

The code is fairly simple. At least at this stage, you should find it simple. The steps are like this:

\1.\ Read the file with the help of the “with” keyword and store it in a variable and return it. We pass the parameter through the function. See the first function: “ReadFile(filename)”.

 

\2.\ The second function is crucial because it passes the same file name as one of the parameters. It also connects to the database and commits. See the second function: “UpdateImage(author_id, filename)”.

 

\3.\ Finally, we call the second function and pass the path of the image file as an argument so that our Python code reaches there and retrieves the image by opening it and finally committing to the database.

 

Now we are going to retrieve one image from the database and write it on our local disk. In the previous code we have read the file. Now it is time to write the file on our disk. The code is almost similar except for a few changes.

<code>
#!/usr/bin/python3
from mysql.connector import MySQLConnection, Error
from MySQL_Connector.mysql_config import ReadingMySQLConfig def WriteFile(data, filename):
with open(filename, 'wb') as files:
files.write(data)
def ReadImage(author_id, filename):
kwargs = ReadingMySQLConfig()
query = 'SELECT photo FROM authors WHERE id = %s' try:
MyConnection = MySQLConnection(**kwargs) cursor = MyConnection.cursor() cursor.execute(query, (author_id,)) photo = cursor.fetchone()[0] WriteFile(photo, filename)
except Error as e:
print(e)
finally:
MyConnection.close()
def main():
id = 47
ReadImage(id, "/home/hagudu/Pictures/ss1.jpg")
if __name__ == "__main__":
main()
</code>
Module

 

In Python when you leave the shell or terminal or Python interpreter, the script is lost. After all, you don’t write programs to lose at the end of the day. It may be a simple calculator program. But you want to use it again. Another important thing is you need to use your one code in your other code. You may want to use other people’s code also.

 

To solve this dilemma, the concept of “module” comes in.

You write a simple calculator program and save the file as “http://cal.py”. If you are in the root directory of your project you can easily use your calculator in your other program. Once you write a Python code and save it with a name, that name becomes a module.

 

In this case, “cal” becomes a module. Now you can “import” that “cal” module into any other code or module. In the large Python library, there are tons of modules. You can always import them and use them. Consider the code below. In this code, we have imported three modules. The first is “sys” or system-specific module.

 

The second one is “os” or operating system–specific module
? and the third one is “urllib” which means a library that is URL-specific. 
?You notice that we write "urllib.request".

 

The “dot” notation means we actually call something called “request” from the Python URL library. Actually, web architecture primarily depends upon two things: request and respond. Here we are going to request something from a URL.

<code>
#!/usr/bin/python3
import sys, os, urllib.request
def main():
print("This is Python Version : {}.{}.{}".format(*sys.version_info))
# os module print(http://os.name) print(os.getenv('PATH')) print(os.getcwd())
#urllib module
page = urllib.request.urlopen('http://arshinagar.in/')
for line in page:
print(str(line, encoding='utf-8'), end='')
if __name__ == "__main__":
main()
</code>

You see that in the first part of the code we have used the “sys” module and wanted to know the version of Python our system is using. The second part is all about the operating system. It gives us the name, path, and many other things. And in the last part, we are requesting a web page.

 

Let us see the output in a Linux Debian distribution like Ubuntu first. The first line is the version and the second line is about the operating system, which is “POSIX”. The third line is the environment path and the fourth line is the actual path where this file is stored.

 

From the fifth line, you see the “urllib. request” starts working in and fetches the whole index page from a website. I have used my friend’s website. I do not print out the whole HTML output, as it would take lots of space. Go through each line and see how different modules work.

<blockquote>
This is Python Version : 3.4.3
posix
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/
usr/local/games
/home/hagudu/PycharmProjects/FirstPythonProject/modules
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8 />
<meta name=viewport content="width=device-width" /> <meta name=viewport content="initial-scale=1.0" /> <meta name=HandheldFriendly content="true"/> <link rel=profile href="XFN 1.1 profile" />
<link rel=pingback href=http://www.arshinagar.in/xmlrpc.php /> <title>Arshinagar &#8211; Just another WordPress site</title>
<link rel=alternate type=application/rss+xml title="Arshinagar &raquo; Feed" href=http://www.arshinagar.in/feed/ />
<link rel=alternate type=application/rss+xml title="Arshinagar &raquo; Comments Feed" href=http://www.arshinagar.in/comments/feed/ />
//the details are removed for brevity
Process finished with exit code 0
</blockquote>
Now we can try this same code in Windows and compare the output.
<blockquote>
This is Python Version : 3.4.4
nt
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\
Microsoft SQL Server\90\Tools\binn\
D:\pthon-files-fromwindows
</blockquote>

In this output you see the Python version has been changed. The operating system is not “posix” anymore.

It is “nt” now. The environment path and the file path are also poles apart. I removed the “urllib.request” module output for concision.

 

We can see more module examples here.

<code>
#!/usr/bin/python3
import sys, os, urllib.request, random, datetime def main():
print("This is Python Version : {}.{}.{}".format(*sys.version_info))
# random module print(random.randint(1, 1000)) x = list(range(25)) print(x) random.shuffle(x)
print(x)
random.shuffle(x)
print(x)
random.shuffle(x)
print(x)
PresentTime = datetime.datetime.now() print(PresentTime)
print(PresentTime.year, PresentTime.month, PresentTime.day, PresentTime. hour, PresentTime.minute, PresentTime.second, PresentTime.microsecond)
if __name__ == "__main__":
main()
</code>

Each time you run the code, you get a new number as the “random” module always produces new numbers. To get more ideas, you need to go through the Python Standard Library in the official Python website or download the Python 3.4.4 documentation.

 

It is available in many file types, including a simple text file or PDF. The “DateTime” module page in Python Standard Library in the documentation looks like this:

 

Now you can go back to your old codes and see them again in a new light. Now you will easily understand why we have used the MySQL Connector module or Configuration Parser module.

 

[Note: You can free download the complete Office 365 and Office 2019 com setup Guide.]

 

Debugging, Unittest Module

In the Python standard library, you get a lot of information about this module. You may also search the Internet about the “nose” tool, which does something similar. The basic concept is, you have a code repository somewhere and you have a separate unit testing schedule. It is an automated test.

 

Suppose we have a folder called “MyTest/brain and soul”. Inside this folder, we have a Python file called “http://saytimedate.py”. It is a very simple file that will tell us the version of Python and the present time and date.

 

To get that output, we need two modules: “sys” and “DateTime”. We have two methods to get those outputs. To get the output, all we need to do is call them under “main()” function. We do exactly that.

 

At the same time, we have two separate methods that begin with the word “test”.

The methods are “test_PyVar()” and “test_main()”.
<code>
#!/usr/bin/python3
# coding=utf-8 import sys, datetime def PyVer():
print("This is Python Version : {}.{}.{}".format(*sys.version_info)) def PyTime():
PresentTime = datetime.datetime.now() print(PresentTime)
print(PresentTime.year, PresentTime.month, PresentTime.day, PresentTime. hour, PresentTime.minute,
PresentTime.second, PresentTime.microsecond) #print(obj)
def main(): PyVer()
PyTime()
def test_Pyvar():
PyVer()
def test_Main():
PyTime()
if __name__ == "__main__":
main()
<code>
When you run this code, your main() function calls the two methods defined inside it. And the output below is what is expected.
</blockquote>
This is Python Version : 3.4.2
2016-04-22 23:30:30.435691
2016 4 22 23 30 30 435691
</blockquote>

 

Now, in a completely separate folder, we would like to run the “unittest” module and see whether this code passes or fails. Since we have already run the code and gotten a successful output, we can safely say that this code will pass the test.

The name of our unit testing code is “http://TestUnitTest.py” and the code looks like this:
<code>
#!/usr/bin/python3
# coding=utf-8
import MyProject.BrainAndSoul.saytimedate import unittest
class SayTiemDate(unittest.TestCase):
def setUP(self):
pass
def test_Version(self): self.assertEqual(MyProject.BrainAndSoul. saytimedate.PyVer(), MyProject.BrainAndSoul.saytimedate.test_Pyvar())
def test_Time(self): self.assertEqual(MyProject.BrainAndSoul. saytimedate.main(), MyProject.BrainAndSoul.saytimedate.test_Main())
if __name__ == "__main__":
unittest.main()
</code>

What does this code say? As you see, there are two methods: “test_Time()” and “test_ Version()”. We have not passed any argument. Both the methods call one default method from the “unittest” module. And that is “assertEqual()”.

 

Through this method, we have passed two methods that we have defined earlier in the “MyTest/brain and soul” folder. Inside that folder, we have a Python file called “http://saytimedate.py”. We are now comparing two methods through our “unittest” module.

 

Finally, it gives a nice output like this if everything runs properly.

<blockquote>
Testing started at 8:58 PM ...
This is Python Version : 3.4.2
This is Python Version : 3.4.2
Process finished with exit code 0
</blockquote>

 

When you run the code it looks like the following image in your “PyCharm” IDE. If we run that code again we may get an output like this:

<blockquote>
This is Python Version : 3.4.2
2016-04-23 05:47:23.608853
2016 4 23 5 47 23 608853
2016-04-23 05:47:23.608951
2016 4 23 5 47 23 608951
This is Python Version : 3.4.2
This is Python Version : 3.4.2
Ran 2 tests in 0.001s
OK
Process finished with exit code 0
</blockquote>

Now for testing purposes, we change our source code and make some mistakes intentionally to see whether our “unittest” module fails or not. If there is an error, the output will change and give an error message something like this:

<blockquote>
This is Python Version : 3.4.2
2016-04-23 05:51:45.994547
2016 4 23 5 51 45 994547
This is Python Version : 3.4.2
This is Python Version : 3.4.2
E.
ERROR: test_Time (__main__.SayTiemDate)
Traceback (most recent call last):
File "/home/ss/FirstPythonProjects/PlayWithPython-master/MyTest/ http://TestUnitTest.py", line 17, in test_Time
self.assertEqual(MyProject.BrainAndSoul.saytimedate.main(), MyProject. BrainAndSoul.saytimedate.test_Main())
File "/home/ss/FirstPythonProjects/MyProject/BrainAndSoul/saytimedate.py", line 20, in main
PyTime()
File "/home/ss/FirstPythonProjects/MyProject/BrainAndSoul/saytimedate.py", line 15, in PyTime
print(obj)
NameError: name 'obj' is not defined
Ran 2 tests in 0.001s
FAILED (errors=1)
Process finished with exit code 1
</blockquote>

Now you can try to run more unit testing modules. Here is another example where the test is successful.

 

Nmap: the Network Mapper

Other Platforms (BSD, Solaris, AIX, AmigaOS) Nmap Network Scanning

If in your ‘Linux’ version of default operating system you don’t get this listing you can install ‘Nmap’ by issuing a simple command. sudo apt-get install map

 

In your virtual machine, if you run Kali Linux, you’ll find that ‘Nmap’ has already been installed. Now after this installation part is over we can very quickly have a short python script to see how our ‘Nmap’ module is working.

 

 You’ve already learned how to use ‘nano’ text editor on your terminal. So open it up with this command: sudo nano http://test.py

 

It will first ask for your root password and then open up the nano text editor on your terminal. Write a short script like this:

#!/usr/bin/python
import nmap
nm = nmap.PortScannerAsync()
def callback_result(host, scan_result):
print ('------------------')
print (host, scan_result)
nm.scan('127.0.0.1', arguments="-O -v", callback=callback_result)
while nm.still_scanning():
print("Waiting ")
nm.wait(2)
nm1 = nmap.PortScanner()
a = nm1.nmap_version()
print (a)
If you run your ‘http://test.py’ script, you’d get this output:
Waiting
------------------
('127.0.0.1', None)
(6, 40)

It’s your localhost address. But we are interested in the remote target. Run up the Kali Linux in your Virtual Box and open the ‘Tor’ browser. Search ‘what is my IP address’. It will give you an anonymous IP address all the time. Each time you search that IP address changes.

In your case, it may come out as x.x.xx.xxx ISP: Some Internet LTD

 

It’s usually too far from your original location! Anyway, you can test the IP and see the result. But it’s a good practice to test the IP of Nmap: the Network Mapper

Recommend