------ FUNCTIONS ------
def func1():
print('This function was called')
def func2(v1):
print('This function was called with a value of ' + v1)
func1()
func2('Monday')
------ COMMON COMMANDS ------
python --version // show version (python -v opens terminal!)
------ VIRTUAL ENVIRONMENT + WSL ------
! In VS Code use 'wsl' Terminal // Gives access to Ubuntu Python rather than Windows Python !
$ python3 --version // For Syntax
apt install python3-venv // Install through Linux apt!! Not pip
python3 -m venv ./ // Ceates in the folder you are in
source bin/activate // To activate Virtual Environment
deactivate // To deactivate
--- On Windows ---
cd Scripts // Navigate to the Scripts folder
.\activate // Execute the activate command
------ INSTALL PYTHON ON WINDOWS + WSL ------
Windows - Typically uses 'python' which refers to python3
WSL - Use pyton3 to refer to Python version 3
sudo apt install python3 // Install on WSL
sudo apt install python3-pip // install pip for python 3
------ VARIABLES ------
print('Enter your name:')
v1 = input()
print('Hello, ' + v1)
------ CLASSES ------
class Number:
x = 10
p1 = Number() # creates a object from Number class
print(p1.x) # prints the value of x from the class
class Date:
def __init__(self, month, day, year):
self.month = month
self.day = day
self.year = year
p2 = Date('June', 24, 2024)
print(p2.month, p2.day, p2.year)
------ MODULES ------
import math
import calendar
import myModule
from myModule import employee
myModule.hello('Martin')
print(employee['firstname'])
print(math.sqrt(25))
print(calendar.month(2024, 6))
pip list // check installed modules
pip lis | grep ufw // check and filter for spacific module
------ (1) LISTS ------
// List is a collection which is ordered and changeable. Allows duplicate members.
myList = ['Apple','Orange','Banana','Pear']
------ (2) DICTIONARY ------
// Dictionary is a collection which is ordered** and changeable. No duplicate members.
// **As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries were unordered.
myDictionary = {'Name':'Bob', 'Car':'BMW', 'Colur':'Blue'}
for x, y in myDictionary.items(): // can also loop through just .values or .keys
print(x, y)
------
d1 = {'name': 'Bob', 'age': 21, 'marks': 60, 'course': 'Computer Eng'}
print(d1.keys())
print(d1.values())
------
d1 = {
"name":"Martin",
"car":"VW",
"colour":"Blue",
"food": ["Pizza","Chinese","Fish Fingers"]
}
print(f'My name is {d1["name"]}')
------
d1 = {
"p1": {
"name": "Bill",
"car": "VW",
"colour": "Silver",
"food": ["Pizza", "Chinese", "Fish Fingers"]
},
"p2": {
"name": "Ben",
"car": "Peugeot",
"colour": "White",
"food": ["Pizza", "Chinese", "Fish Fingers"]
}
}
for i in d1.values():
print(f'\nMy name is {i["name"]}, I drive a {i["colour"]} {i["car"]}. \nMy favourite food is {i["food"][0]}, {i["food"][1]} and {i["food"][2]}.\n')
------ (3) TUPLE ------
// Tuple items are ordered, unchangeable (immutable), and allow duplicate values.
// Tuple items are indexed, the first item has index [0]
myTuple = ("abc", 34, True, 40, "string")
print(type(myTuple)) // <class 'tuple'>
------ (4) SET ------
// Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
// *Set items are unchangeable, but you can remove and/or add items whenever you like.
mySet = {"abc", 34, True, 40, "male", False, 0}
print(len(mySet)) // length will be 6 not 7 because False and 0 are the same and can't have duplicates
print(type(mySet))
------ PRINT ------
msg = f'\n{person} has {str(coins)} coins left! \n'
print(msg)
------
data = "192.168.1.1, 10.1.1.1, 172.16.0.1"
splitData = data.split(', ')
print(splitData)
for index, octet in enumerate(splitData):
print(f"The IP address in position: {index+1}, will be: {octet}")
------ LOOPS ------
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
for i in range(5):
print(i)
----
dict = {'person':'Martin','coins':3}
for x in dict.items():
print(x)
---- WHILE ----
------ READ FILE ------
with open("text.txt", "r") as f:
content = f.read()
print(content)
------ CLASSES ------
class Router:
'''This is my router class'''
def __init__(self, model, sw, ip):
self.model = model
self.sw = sw
self.ip = ip
def desc(self):
'''Formatted layout'''
desc = f'Router Model: {self.model}\n'\
f'Router Software: {self.sw}\n'\
f'Router IP Address: {self.ip}'
return desc
R1 = Router('4331', '16.2.8', '192.168.0.14')
R2 = Router('ASR 2000', '11.2.4', '10.1.1.1')
print('R1\n',R1.desc(),'\n', sep='')
print('R2\n',R2.desc(),'\n', sep='')
------ SIMPLE WEB SERVER ------
// Run as .bat file in windows
@echo off
cd /d C:\Users\mickey\some - folder O1\Desktop\www
echo Starting server at http://localhost:8000
python -m http.server 8000
pause
------ SCRAPLI ------
// Start Virtual Environment - Then ...
$ pip install scrapli
$ pip install scrapli[textfsm]
--- SHOW IP INTERFACE BRIEF ---
from scrapli.driver.core import IOSXEDriver
my_device = {
"host": "10.1.1.108",
"auth_username": "cisco",
"auth_password": "cisco",
"auth_strict_key": False,
}
conn = IOSXEDriver(**my_device)
conn.open()
response = conn.send_command("sh ip int br")
print(response.result)
--- SHOW VERSION ---
from scrapli.driver.core import IOSXEDriver
my_device = {
"host": "10.1.1.108",
"auth_username": "cisco",
"auth_password": "cisco",
"auth_strict_key": False,
}
conn = IOSXEDriver(**MY_DEVICE)
conn.open()
response = conn.send_command("show ver")
data = response.result
# print(type(data))
structured_result = response.textfsm_parse_output()
# print(structured_result)
for info in structured_result:
print(f"Software Version is {info['version']}")
v1 = info['version'].replace(".", "").replace("a", "")
if int(v1) < 1796:
print('Please upgrade your software!')
else:
print('Your software is up to date!')
conn.close()
--- LOOP THROUGH UP INTERFACES ---
from scrapli.driver.core import IOSXEDriver
my_device = {
"host": "10.1.1.108",
"auth_username": "cisco",
"auth_password": "cisco",
"auth_strict_key": False,
}
conn = IOSXEDriver(**MY_DEVICE)
conn.open()
response = conn.send_command("show ip interface brief")
data = response.result
# print(type(data))
structured_result = response.textfsm_parse_output()
for info in structured_result:
if info['intf'].startswith('Loop'):
if 'unassigned' not in info['ipaddr']:
print(f"Interface {info['intf']} has a ip {info['ipaddr']} and is {info['proto']} {info['status']}")
conn.close()
------ INSTALL PYTHON-PIP-VENV-GUNICORN-FLASK + RUN ------
// all commands run in the shell
apt install python3
apt install python3-pip
apt install python3-venv
python3 -m venv ./ // install virtual environment
source bin/activate // start virtual environment
pip install gunicorn
pip install flask
pip install requests
pip install flask-cors
pip list // will show you what modules are installed - shell command!
gunicorn --bind 0.0.0.0:5000 wsgi:app
flask run
------ SCRAP ------
# ------ Challenge 1 + 2 ------
# v1 = "katie"
# v2 = input("Please Enter your Name? ")
# v3 = 1
# while v2.lower() != v1:
# print("You have had " + str(v3) + " Guesses")
# v3 = v3 + 1
# v2 = input("Please Enter your Name? ")
# --------- Challenge 3 ------
# count = 1
# while count < 11:
# print("the count number is " + str(count))
# count = count + 1
# print('Time Up!')
# --------- Challenge 4 ------
# total = 0
# while True:
# v1 = input("Please Enter a Number: ")
# if v1 == "0":
# break
# total = total + int(v1)
# print("The total sum is: " + str(total))
# --------- Challenge 5 ------
# i = 0
# n = 10
# while i <= n:
# print("i is less than or equal to n")
# i = i + 1
# print("Wile loop ended!")
# --------- Challenge 6 ------
# count = 1
# while count <= 3:
# v1 = int(input("Enter number a ? "))
# v2 = int(input("Enter number b ? "))
# avg = (v1+v2/2)
# print(avg)
# count = count + 1
# --------- Challenge 7 ------
# count = 2
# v1 = "katie"
# v2 = input("Guess a Name ? ")
# while count >= 1:
# if (v2 == v1):
# print("You Guessed It!")
# break
# elif (v2 != v1):
# print("Guess Again you have " + str(count) + " Go Left")
# v2 = input("Guess a Name ? ")
# count = count - 1
# --------- Challenge 8 ------
# v1 = input("Pleas Enter a Password ? ")
# while len(v1) < 10:
# v1 = input("Pleas Enter a Longer Password ? ")
# print("Thanks, you have entered 10 or more characters!")
------ INSTALL Z-SH SHELL ------
apt install zsh
// add oh my zsh which allows you to customise
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
// first time it runs choose empty file with one comment
nano ~/.zshrc // change themes - ZSH_THEME="robbyrussell" - change this "af-magic"
chsh -s [path] [user] // change shell command
chsh -s $(which zsh) // use the which command if unsure of path above
grep "^$USER" /etc/passwd // show current user and shell
echo $SHELL // show default shell