Skip to content

Commit

Permalink
Update example_sqlite.rst
Browse files Browse the repository at this point in the history
  • Loading branch information
Aidar5 committed Oct 14, 2020
1 parent 010a822 commit 50f778f
Showing 1 changed file with 152 additions and 15 deletions.
167 changes: 152 additions & 15 deletions docs/source/book/25_db/example_sqlite.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,19 @@ SQLite will only create a table if it does not exist.

Now you have to create a database file, connect to database and create a table (create_sqlite_ver1.py file):

.. literalinclude:: /pyneng-examples-exercises/examples/18_db/create_sqlite_ver1.py
:language: python
:linenos:
.. code:: python
import sqlite3
conn = sqlite3.connect('dhcp_snooping.db')
print('Creating schema...')
with open('dhcp_snooping_schema.sql', 'r') as f:
schema = f.read()
conn.executescript(schema)
print("Done")
conn.close()
Comments to file:

Expand Down Expand Up @@ -79,9 +89,41 @@ Now it is necessary to write information from the output of *sh ip dhcp snooping

In the second version of the script, the output in dhcp_snooping.txt file is processed with regular expressions and then entries are added to database (create_sqlite_ver2.py file):

.. literalinclude:: /pyneng-examples-exercises/examples/18_db/create_sqlite_ver2.py
:language: python
:linenos:
.. code:: python
import sqlite3
import re
regex = re.compile('(\S+) +(\S+) +\d+ +\S+ +(\d+) +(\S+)')
result = []
with open('dhcp_snooping.txt') as data:
for line in data:
match = regex.search(line)
if match:
result.append(match.groups())
conn = sqlite3.connect('dhcp_snooping.db')
print('Creating schema...')
with open('dhcp_snooping_schema.sql', 'r') as f:
schema = f.read()
conn.executescript(schema)
print('Done')
print('Inserting DHCP Snooping data')
for row in result:
try:
with conn:
query = '''insert into dhcp (mac, ip, vlan, interface)
values (?, ?, ?, ?)'''
conn.execute(query, row)
except sqlite3.IntegrityError as e:
print('Error occured: ', e)
conn.close()
.. note::

Expand Down Expand Up @@ -144,9 +186,51 @@ Let’s modify the script to make it check for the presence of dhcp_snooping.db.

File create_sqlite_ver3.py:

.. literalinclude:: /pyneng-examples-exercises/examples/18_db/create_sqlite_ver3.py
:language: python
:linenos:
.. code:: python
import os
import sqlite3
import re
data_filename = 'dhcp_snooping.txt'
db_filename = 'dhcp_snooping.db'
schema_filename = 'dhcp_snooping_schema.sql'
regex = re.compile('(\S+) +(\S+) +\d+ +\S+ +(\d+) +(\S+)')
result = []
with open('dhcp_snooping.txt') as data:
for line in data:
match = regex.search(line)
if match:
result.append(match.groups())
db_exists = os.path.exists(db_filename)
conn = sqlite3.connect(db_filename)
if not db_exists:
print('Creating schema...')
with open(schema_filename, 'r') as f:
schema = f.read()
conn.executescript(schema)
print('Done')
else:
print('Database exists, assume dhcp table does, too.')
print('Inserting DHCP Snooping data')
for row in result:
try:
with conn:
query = '''insert into dhcp (mac, ip, vlan, interface)
values (?, ?, ?, ?)'''
conn.execute(query, row)
except sqlite3.IntegrityError as e:
print('Error occured: ', e)
conn.close()
Now there is a verification of the presence of database file and dhcp_snooping.db file will only be created if it does not exist. Data is also written only if dhcp_snooping.db file is not created.

Expand Down Expand Up @@ -200,9 +284,32 @@ Now we make a separate script that deals with sending queries to database and di

File get_data_ver1.py:

.. literalinclude:: /pyneng-examples-exercises/examples/18_db/get_data_ver1.py
:language: python
:linenos:
.. code:: python
import sqlite3
import sys
db_filename = 'dhcp_snooping.db'
key, value = sys.argv[1:]
keys = ['mac', 'ip', 'vlan', 'interface']
keys.remove(key)
conn = sqlite3.connect(db_filename)
#Allows to further access data in columns by column name
conn.row_factory = sqlite3.Row
print('\nDetailed information for host(s) with', key, value)
print('-' * 40)
query = 'select * from dhcp where {} = ?'.format(key)
result = conn.execute(query, (value, ))
for row in result:
for k in keys:
print('{:12}: {}'.format(k, row[k]))
print('-' * 40)
Comments to the script:

Expand Down Expand Up @@ -263,9 +370,39 @@ The second version of the script to obtain data with minor improvements:

File get_data_ver2.py:

.. literalinclude:: /pyneng-examples-exercises/examples/18_db/get_data_ver2.py
:language: python
:linenos:
.. code:: python
import sqlite3
import sys
db_filename = 'dhcp_snooping.db'
query_dict = {
'vlan': 'select mac, ip, interface from dhcp where vlan = ?',
'mac': 'select vlan, ip, interface from dhcp where mac = ?',
'ip': 'select vlan, mac, interface from dhcp where ip = ?',
'interface': 'select vlan, mac, ip from dhcp where interface = ?'
}
key, value = sys.argv[1:]
keys = query_dict.keys()
if not key in keys:
print('Enter key from {}'.format(', '.join(keys)))
else:
conn = sqlite3.connect(db_filename)
conn.row_factory = sqlite3.Row
print('\nDetailed information for host(s) with', key, value)
print('-' * 40)
query = query_dict[key]
result = conn.execute(query, (value, ))
for row in result:
for row_name in row.keys():
print('{:12}: {}'.format(row_name, row[row_name]))
print('-' * 40)
There are several drawbacks to this script:

Expand Down

0 comments on commit 50f778f

Please sign in to comment.