Planet Collab

🔒
❌ About FreshRSS
There are new available articles, click to refresh the page.
Before yesterdayYour RSS feeds

[Book] Regex basics 1 – metacharacters for repetition

By italchemy

Written on 24/11/2019 at 20:30

# Use of Python regex metacharacters
Search, extract, replace complicated texts
very powerful metacharacter based searching tool using various character pattern combinations.
Regular Expression function is provided by re module in Python.

#.1 metacharacters
Regular Expression has many built-in metacharacters to display characters or character patterns.
These metacharacters allow repetition possible.

#.1 Python metacharacters - repetition

metacharacters | Description | Example

1 * | repeats 0 or more times |  zo*m matches zm, zom, zoom, zooom, zoooom, zooooom
Note: repeats the character infront of the *, so in this case alphabet 'o'

import re

maz = re.findall("zo*m" , "zm, zom, zoom, zooom, zoooom, zooooom")
print(maz)
['zm', 'zom', 'zoom', 'zooom', 'zoooom', zooooom]

2 + | repeats once or more than once | zo+m matches zom, zoom, zooom, zoo..m etc.
Note: repeats the character infront of the +, so in this case alphabet 'o'

import re

maz = re.findall("zo+m" , "zm, zom, zoom, zooom, zoooom, zooooom")
print(maz)
['zom', 'zoom', 'zooom', 'zoooom', 'zooooom']

3 ? | repeats 0 times or once | zo?m matches zm and zom.
Note: repeats the character infront of the ?, so in this case alphabet 'o'

import re

maz = re.findall("zo?m" , "zm, zom, zoom, zooom, zoooom, zooooom")
print(maz)
['zm', 'zom']

4 {m} | repeats m number of times | zo{3}m matches zooom.
Note: repeats the character infront of the {m}, so in this case alphabet 'o'

import re

maz = re.findall("zo{3}m" , "zm, zom, zoom, zooom, zoooom, zooooom")
print(maz)
['zooom']


5 {m, n} | repeats m number of times | zo{2,4}m matches zoom - zoooom
Note: repeats the character infront of the {m}, so in this case alphabet 'o'

import re

maz = re.findall("zo{2,4}m" , "zm, zom, zoom, zooom, zoooom, zooooom")
print(maz)
['zoom', 'zooom', 'zoooom']

Catpure Gigabit interface only – GigabitEthernet\d[/]\d\d?

By italchemy

s= “””

Interface IP-Address OK? Method Status Protocol
Vlan1 unassigned YES NVRAM administratively down down
Vlan10 10.193.40.11 YES NVRAM up up
FastEthernet0 unassigned YES NVRAM administratively down down
GigabitEthernet0/1 unassigned YES unset up up
GigabitEthernet0/2 unassigned YES unset down down
GigabitEthernet0/3 unassigned YES unset up up
GigabitEthernet0/4 unassigned YES unset down down
GigabitEthernet0/5 unassigned YES unset down down
GigabitEthernet0/6 unassigned YES unset down down
GigabitEthernet0/7 unassigned YES unset up up
GigabitEthernet0/8 unassigned YES unset down down
GigabitEthernet0/9 unassigned YES unset down down
GigabitEthernet0/10 unassigned YES unset down down

“””

 

>>> m = re.findall(r”(GigabitEthernet\d[/]\d\d?)”, s)

>>> m

[‘GigabitEthernet0/1’, ‘GigabitEthernet0/2’, ‘GigabitEthernet0/3’, ‘GigabitEthernet0/4’, ‘GigabitEthernet0/5’, ‘GigabitEthernet0/6’, ‘GigabitEthernet0/7’, ‘GigabitEthernet0/8’, ‘GigabitEthernet0/9’, ‘GigabitEthernet0/10’]

Catpure Gigabit interface only – GigabitEthernet\d[/]\d\d?

By italchemy

s= “””

Interface IP-Address OK? Method Status Protocol
Vlan1 unassigned YES NVRAM administratively down down
Vlan10 10.193.40.11 YES NVRAM up up
FastEthernet0 unassigned YES NVRAM administratively down down
GigabitEthernet0/1 unassigned YES unset up up
GigabitEthernet0/2 unassigned YES unset down down
GigabitEthernet0/3 unassigned YES unset up up
GigabitEthernet0/4 unassigned YES unset down down
GigabitEthernet0/5 unassigned YES unset down down
GigabitEthernet0/6 unassigned YES unset down down
GigabitEthernet0/7 unassigned YES unset up up
GigabitEthernet0/8 unassigned YES unset down down
GigabitEthernet0/9 unassigned YES unset down down
GigabitEthernet0/10 unassigned YES unset down down

“””

 

>>> m = re.findall(r”(GigabitEthernet\d[/]\d\d?)”, s)

>>> m

[‘GigabitEthernet0/1’, ‘GigabitEthernet0/2’, ‘GigabitEthernet0/3’, ‘GigabitEthernet0/4’, ‘GigabitEthernet0/5’, ‘GigabitEthernet0/6’, ‘GigabitEthernet0/7’, ‘GigabitEthernet0/8’, ‘GigabitEthernet0/9’, ‘GigabitEthernet0/10’]

1. Python – navigating to working directory using os module

By italchemy

# Import os
>>> import os

# Check current workind directory
>>> cwd = os.getcwd()
>>> cwd
‘/root’

# Check the directories and files
>>> os.listdir(‘.’)
[‘.bash_logout’, ‘.bash_profile’, ‘.bashrc’, ‘.cshrc’, ‘.tcshrc’, ‘anaconda-ks.cfg’, ‘.cache’, ‘.dbus’, ‘.config’, ‘initial-setup-ks.cfg’, ‘.esd_auth’, ‘.ICEauthority’, ‘.local’, ‘Desktop’, ‘Downloads’, ‘Templates’, ‘Public’, ‘Documents’, ‘Music’, ‘Pictures’, ‘Videos’, ‘.pki’, ‘.bash_history’, ‘.python_history’, ‘.mozilla’, ‘.docker’, ‘dockerfile1’, ‘Dockerfile1’, ‘Dockerfile001’, ‘Dockerfile002’, ‘Dockerfile’, ‘pan_set_test’, ‘animal_list.txt’, ‘convert_txt2excel.py’, ‘animal_list.xlsx’, ‘test01.xlsx’, ‘pan_config_diff.xlsx’, ‘pan_config_old.xlsx’, ‘pan_config.xlsx’, ‘pan_config_df1_diff.xlsx’, ‘pan_config_df3_diff.xlsx’, ‘panda_test01’, ‘t1’]

# Change the workind directory to your desired location.
>>> os.chdir(“/root/pan_set_test”)

# Check the files and directories under your workind directory.
>>> os.listdir(‘.’)
[‘pan_set1.py’, ‘tools1.py’, ‘__pycache__’, ‘pan_set2.py’, ‘pan_set3.py’, ‘pan_set4.py’, ‘pan_set5.py’, ‘txt_to_xlsx.py’, ‘txt_to_xlsx1.py’, ‘compare_2_xlsx.py’, ‘excelcompare.py’, ‘excelcompare1.py’, ‘txt_to_xlsx2.py’, ‘pan_set6.py’, ‘pan1_session.out’, ‘pan1_config.out’, ‘pan2_config.out’, ‘192.168.30.154_vs_192.168.30.157_compared.html’, ‘pan2_session.out’, ‘pan_config.xlsx’, ‘pan_config_test1.xlsx’, ‘pan1_config.xlsx’, ‘pan2_config.xlsx’, ‘compare_test100.py’, ‘where_am_i.py’]

1. Python – navigating to working directory using os module

By italchemy

# Import os
>>> import os

# Check current workind directory
>>> cwd = os.getcwd()
>>> cwd
‘/root’

# Check the directories and files
>>> os.listdir(‘.’)
[‘.bash_logout’, ‘.bash_profile’, ‘.bashrc’, ‘.cshrc’, ‘.tcshrc’, ‘anaconda-ks.cfg’, ‘.cache’, ‘.dbus’, ‘.config’, ‘initial-setup-ks.cfg’, ‘.esd_auth’, ‘.ICEauthority’, ‘.local’, ‘Desktop’, ‘Downloads’, ‘Templates’, ‘Public’, ‘Documents’, ‘Music’, ‘Pictures’, ‘Videos’, ‘.pki’, ‘.bash_history’, ‘.python_history’, ‘.mozilla’, ‘.docker’, ‘dockerfile1’, ‘Dockerfile1’, ‘Dockerfile001’, ‘Dockerfile002’, ‘Dockerfile’, ‘pan_set_test’, ‘animal_list.txt’, ‘convert_txt2excel.py’, ‘animal_list.xlsx’, ‘test01.xlsx’, ‘pan_config_diff.xlsx’, ‘pan_config_old.xlsx’, ‘pan_config.xlsx’, ‘pan_config_df1_diff.xlsx’, ‘pan_config_df3_diff.xlsx’, ‘panda_test01’, ‘t1’]

# Change the workind directory to your desired location.
>>> os.chdir(“/root/pan_set_test”)

# Check the files and directories under your workind directory.
>>> os.listdir(‘.’)
[‘pan_set1.py’, ‘tools1.py’, ‘__pycache__’, ‘pan_set2.py’, ‘pan_set3.py’, ‘pan_set4.py’, ‘pan_set5.py’, ‘txt_to_xlsx.py’, ‘txt_to_xlsx1.py’, ‘compare_2_xlsx.py’, ‘excelcompare.py’, ‘excelcompare1.py’, ‘txt_to_xlsx2.py’, ‘pan_set6.py’, ‘pan1_session.out’, ‘pan1_config.out’, ‘pan2_config.out’, ‘192.168.30.154_vs_192.168.30.157_compared.html’, ‘pan2_session.out’, ‘pan_config.xlsx’, ‘pan_config_test1.xlsx’, ‘pan1_config.xlsx’, ‘pan2_config.xlsx’, ‘compare_test100.py’, ‘where_am_i.py’]

Python os module – prepend first line before converting to xlsx file

By italchemy

 

import os

#This adds the first line header to  animal_list.txt file.
os.system(“sed -i ‘1s/^/DOMESTIC_ANIMALS\\n/’ /root/animal_list.txt”)

 

[root@localhost ~]# cat animal_list.txt
1. dog
2. cat
3. cow
4. sheep
5. pig

 

>>> import os
>>> #This adds the first line header to  animal_list.txt file.

>>> os.system(“sed -i ‘1s/^/DOMESTIC_ANIMALS\\n/’ /root/animal_list.txt”)
0
>>>

[root@localhost ~]# cat animal_list.txt
DOMESTIC_ANIMALS <<< New line prepended
1. dog
2. cat
3. cow
4. sheep
5. pig

Python os module – prepend first line before converting to xlsx file

By italchemy

 

import os

#This adds the first line header to  animal_list.txt file.
os.system(“sed -i ‘1s/^/DOMESTIC_ANIMALS\\n/’ /root/animal_list.txt”)

 

[root@localhost ~]# cat animal_list.txt
1. dog
2. cat
3. cow
4. sheep
5. pig

 

>>> import os
>>> #This adds the first line header to  animal_list.txt file.

>>> os.system(“sed -i ‘1s/^/DOMESTIC_ANIMALS\\n/’ /root/animal_list.txt”)
0
>>>

[root@localhost ~]# cat animal_list.txt
DOMESTIC_ANIMALS <<< New line prepended
1. dog
2. cat
3. cow
4. sheep
5. pig

Python code run timer 2– make your own tool

By italchemy

You can use datetime module to get both the date and difference in time. Follow this in Python IDLE or Interpreter to comprehend datetime module.

 

Import datetime

# >>> start_time = datetime.datetime.now().strftime(‘%y-%m-%d %a %H:%M:%S’) #When you want to format the string
# >>> start_time
# ’20-04-30 Thu 07:17:21′

# To get the date only as string
>>> yyyymmdd = datetime.date.today().strftime(‘%Y_%m_%d’)
>>> yyyymmdd
‘2020_04_30’

# To get the start time before the script runs
>>> start_time = datetime.datetime.now()
>>> start_time
datetime.datetime(2020, 4, 30, 7, 18, 19, 578317)
### PUT YOUR SCRIPT HERE

# I am using the date to create a new file. A single file will be created each day as it is using w+ privilages.

with open(“/home/” + yyyymmdd + “_hello_monkey.txt”, “w+”) as f:
f.write(“Hello World! Hello Mr. Mokey”)

 

# To get the end time after the script finishes
>>> end_time = datetime.datetime.now()
>>> end_time
datetime.datetime(2020, 4, 30, 7, 18, 35, 799375)

# If you simply print the difference, it will print in full module format.
>>> x = end_time – start_time
>>> x
datetime.timedelta(0, 16, 221058)

# To conver the timedelta to total seconds
>>> y = datetime.timedelta.total_seconds(end_time-start_time)
>>> y
16.221058

Python code run timer 2– make your own tool

By italchemy

You can use datetime module to get both the date and difference in time. Follow this in Python IDLE or Interpreter to comprehend datetime module.

 

Import datetime

# >>> start_time = datetime.datetime.now().strftime(‘%y-%m-%d %a %H:%M:%S’) #When you want to format the string
# >>> start_time
# ’20-04-30 Thu 07:17:21′

# To get the date only as string
>>> yyyymmdd = datetime.date.today().strftime(‘%Y_%m_%d’)
>>> yyyymmdd
‘2020_04_30’

# To get the start time before the script runs
>>> start_time = datetime.datetime.now()
>>> start_time
datetime.datetime(2020, 4, 30, 7, 18, 19, 578317)
### PUT YOUR SCRIPT HERE

# I am using the date to create a new file. A single file will be created each day as it is using w+ privilages.

with open(“/home/” + yyyymmdd + “_hello_monkey.txt”, “w+”) as f:
f.write(“Hello World! Hello Mr. Mokey”)

 

# To get the end time after the script finishes
>>> end_time = datetime.datetime.now()
>>> end_time
datetime.datetime(2020, 4, 30, 7, 18, 35, 799375)

# If you simply print the difference, it will print in full module format.
>>> x = end_time – start_time
>>> x
datetime.timedelta(0, 16, 221058)

# To conver the timedelta to total seconds
>>> y = datetime.timedelta.total_seconds(end_time-start_time)
>>> y
16.221058

IOS Date conversion to calculate in number of days or years

By italchemy

Test this in your Python Interpreter

 

>>>from datetime import datetime

>>> IOS_rel_date = ’12-Jul-17′
>>> x = IOS_rel_date.replace(‘-‘, ‘ ‘)
>>> y = datetime.strptime(x, ‘%d %b %y’)
>>> y
datetime.datetime(2017, 7, 12, 0, 0)
>>>y.date()
datetime.date(2017, 7, 12)
>>> y_day = y.date()
>>> datetime.today()
datetime.datetime(2020, 4, 15, 11, 56, 3, 370515)
>>> datetime.today().date()
datetime.date(2020, 4, 15)
>>> t_day = datetime.today().date()
>>> delta = t_day – y_day
>>> print(delta.days)
1008
>>> years = round(((delta.days)/365), 2)
2.76

#####################################################

# reiteration:
from datetime import datetime
x = IOS_rel_date.replace(‘-‘, ‘ ‘)
y_day = (datetime.strptime(x, ‘%d %b %y’)).date()
t_day = datetime.today().date()
delta = t_day – y_day
years = round(((delta.days)/365), 2)

IOS Date conversion to calculate in number of days or years

By italchemy

Test this in your Python Interpreter

 

>>>from datetime import datetime

>>> IOS_rel_date = ’12-Jul-17′
>>> x = IOS_rel_date.replace(‘-‘, ‘ ‘)
>>> y = datetime.strptime(x, ‘%d %b %y’)
>>> y
datetime.datetime(2017, 7, 12, 0, 0)
>>>y.date()
datetime.date(2017, 7, 12)
>>> y_day = y.date()
>>> datetime.today()
datetime.datetime(2020, 4, 15, 11, 56, 3, 370515)
>>> datetime.today().date()
datetime.date(2020, 4, 15)
>>> t_day = datetime.today().date()
>>> delta = t_day – y_day
>>> print(delta.days)
1008
>>> years = round(((delta.days)/365), 2)
2.76

#####################################################

# reiteration:
from datetime import datetime
x = IOS_rel_date.replace(‘-‘, ‘ ‘)
y_day = (datetime.strptime(x, ‘%d %b %y’)).date()
t_day = datetime.today().date()
delta = t_day – y_day
years = round(((delta.days)/365), 2)

Python Time module – Check how long your script took to run.

By italchemy

With a simple time module, you can measure the speed of your script. In this example, I am printing my name in  ASCII art 10000 times. It only took 1.74 seconds!

=======================================================================

# source code: print_myname.py

import time
start_time = time.time()
local_time = time.ctime(start_time)
print(“Start time : “, local_time)

Brendan_ascii1

print(“*** All tasks completed normally and you have reached the end of script. “)
end_time = time.time()
local_time = time.ctime(end_time)
print(“End time : “, local_time)
duration = end_time – start_time
duration = format(duration, “.2f”)
print(“Duration :”, duration, ” secs”)

=======================================================================

=======================================================================

#Result:

[root@localhost nuggets]# python3 print_myname.py
Start time : Fri Jan 10 14:42:26 2020

[… output omitted]

Brendan_ascii2.jpg

*** All tasks completed normally and you have reached the end of script.
End time : Fri Jan 10 14:44:00 2020
Duration : 1.74 secs
=======================================================================

Python Time module – Check how long your script took to run.

By italchemy

With a simple time module, you can measure the speed of your script. In this example, I am printing my name in  ASCII art 10000 times. It only took 1.74 seconds!

=======================================================================

# source code: print_myname.py

import time
start_time = time.time()
local_time = time.ctime(start_time)
print(“Start time : “, local_time)

Brendan_ascii1

print(“*** All tasks completed normally and you have reached the end of script. “)
end_time = time.time()
local_time = time.ctime(end_time)
print(“End time : “, local_time)
duration = end_time – start_time
duration = format(duration, “.2f”)
print(“Duration :”, duration, ” secs”)

=======================================================================

=======================================================================

#Result:

[root@localhost nuggets]# python3 print_myname.py
Start time : Fri Jan 10 14:42:26 2020

[… output omitted]

Brendan_ascii2.jpg

*** All tasks completed normally and you have reached the end of script.
End time : Fri Jan 10 14:44:00 2020
Duration : 1.74 secs
=======================================================================

Accessing the ASA Firepower software module (SFR)

When you have an ASA with a firepower software module (sfr) . The physical management interface on the ASA appliance is shared with the management interface mgmt0/0 of the physical appliance. which means that you can SSH to management of the sfr software module.

to fins out what its IP address is, run

 show module sfr details

from the ASA's CLI.  This will provide you with the IP address of the sfr.

available commands:

>

configure  Change to Configuration mode
end        Return to the default mode
exit       Exit this CLI session
expert     Invoke a shell
help       Display an overview of the CLI syntax
history    Display the current session's command line history
logout     Logout of the current CLI session
show       Change to Show Mode
system     Change to System Mode



Once on the sfr module, you can go to expert mode by typing 'expert', drive the CLI pretty much like a linux box, using commands like 'top' to see process utilisation, and cd /var/log to view logs etc.

Reloading or resetting the module, can be done through the ASA's CLI:

sw-module module sfr {reload | reset}


o



❌