ljust
end=
strip
lstrip
replace
split
upper
index
count
find
startswith
endswith
in
not
%
"""
type
isinstance
str,int,float
list,tuple
Array Functions
list
len
range
min
max
append
del
pop
remove
insert
extend
sort
reverse
sorted
reversed
set
intersection
difference
union
clear
tuples
dictionary
range
re.search
re.match
re.findall
System Functions
sys.exit
_
__
__a__
__all__
date
General Functions
pip
help
dir
id
File Functions
mode
seek
tell
read
readline
readlines
String Functions
The method ljust() returns the string left justified in a string of length width. Padding is done using the
specified fillchar (default is a space). The original string is returned if width is less than len(s).
The default value of end is \n meaning that after the print statement it will print a new line. So simply stated
end is what you want to be printed after the print statement has been executed
Return a copy of the string with leading and trailing characters removed. If chars is omitted or None,
whitespace characters are removed. If given and not None, chars must be a string; the characters in the
string will be stripped from the both ends of the string this method is called on.
The method replace() returns a copy of the string in which the occurrences of old have been replaced with
new, optionally restricting the number of replacements to max
The method split() returns a list of all the words in the string, using str as the separator (splits on all
whitespace if left unspecified), optionally limiting the number of splits to num.
conevrt to upper case
To get the index of the letter in the string
To get the occurence of the letter in the string
To get the starting location of the characters in the string
To check the starting character
To check the ending character
To check the presence of letter in a string
To check the not presence of letter in a string
Format operators
Old Style
New Style
To slice and get the part of the text from the string
we can create tuple of values and tuple and variables, and use this variables to access values
unordred set of key value pairs enclosed in curly braces seperated by commas
it gives values from 0 to the value-1 in the paranthesis
real usuage
Regular Expression Functions
search the string in the whole sentence for the given patterrn, and extarct the matched string in groups.
group(0): Whole string that matches with the whole given pattern.
group(1), group(2)..group(n): It contains the respective matched string with the given pattern.
Note: The groups are starts and ends with parenthesis.
match the string in the beginning of the sentence and returns the address if exist else returns none.
One underscore at the start of a method or attribute name makes it private and you cannot access this
method from outside of the class. And if we want to access it should be from another public method.
Two underscores at the beginning:
This causes a lot of confusion. It should not be used to create a private method. It should be used to avoid
your method to be overridden by a subclass or accessed accidentally.
When we see a method like __this__, don't call it. Because it means it's a method which python calls, not by
you. There is always an operator or native function which calls these magic methods. Sometimes it's just a
hook python calls in specific situations. For example __init__() is called when the object is created after
__new__() is called to build the instance
when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from
<module> import * is used on the module.
Note: In the given example If the __all__ above is commented out, this code will then execute to
completion, as the default behaviour of import * is to import all symbols that do not begin with an
underscore, from the given namespace.
In python prompt, dir will give the details of the functions in the module
To get the system address where variable stores
File Functions
Read(r), Write(w), Append(a)
When file opens in read mode, the file read happens and cursor reaches the file end and to bring the cursor
back to required position we use seek.
To get the current cursor position
To read the number of characters from the file
To read a line
To read multiple lines
tions
answer=answer.replace("test", "extend")
answer=answer.split(' ')
address = address_tmp.split('\r\n')[3].split()[2]
answer=answer.upper()
a = "Cisco" , a.index("i") === 2
a = "Ciscoii" , a.count("i") === 3
a = "Ciscoii" , a.find("oii") === 4 no match retutrns -1
a = "Ciscoii" , a.startswith("C") === True
a = "Ciscoii" , a.endswith("q") === False
a = "Ciscoii" , "o" in a === True
a = "Ciscoii" , "o" not in a === False
"model: %s, slots %s", ("1000", "200")
a = 10, b = test, print("%d%s" % (a,b)) OP: 10test
print("{}{}".format(a,b)) OP: 10test
a = "Ciscoii" , a[1:3] === is no match retutrns -1
x = """this\
is\
test"""
type("python") = str type(123) = int
Example screenshot ---->
str(num),int(str), float(num)
list(tup), tuple(lst), set(lst)
ons
a = [], a = ["cisco", "avaya", "juniper"] a[-1] == juniper
value="check" value = [1,2,3,4,5,6]
len(value)=5 len(value)=6
for i in range(0,len(hst),3) Start = 0; End = len(hst), Step = 3
a=[1,2.3,4] , min(a) === 1
a=[1,2.3,4] , max(a) === 4
a.append(100)
del a[2]
a.pop(1)
a.remove("3")
a.insert(2,"7)"
b = [9, 99, 999] a.extend(b)
a.sort()
a.reverse()
sorted(a)
sorted(a, reverse = True)
set(a), set([10, 20, 10]) == 10, 20
a.intersection(b)
a.difference(b)
a.union(b)
a.clear()
c = (1,2.3,4,5), c[0] === 1
device === Cisco
tup=("Cisco", "2600")
(device, model) = tup
OR
("Cisco", "2600") = (device, model)
a = { "Vendor" : "Cisco", "Model" : "100" } a["Vendor"] == Cisco
range(5) === 0,1,2,3,4
vendors = ["Cisco", "HP", "Avaya", "Juniper"]
for elem in range(len(vendors)):
Print(vendors[elem])
Functions
class test(object):
def _testfun(self):
print("Hi") Here the output is "Hi"
def testfun1(self):
self._testfun()
t = test()
t.testfun1()
class test(object):
def __testfun(self):
print("From Class test")
def testfun(self):
self.__testfun()
class test1(test):
def __testfun(self):
print("From Class test1") Here the output is "From Class test"
t = test1()
t.testfun()
class FalseCalculator(object):
List Declaration
__main__
Set in jinja
To install PIL
To get form values with same field name
import os
import getpass
import paramiko
import socket
import re
import sys
def enterPassword():
from __future__ import print_function
whilenetmiko
from True: # import
repeat ConnectHandler
forever
password
import sys = getpass.getpass('Enter corresponding password:')
password_again
import time = getpass.getpass('Confirm password:')
if password
import select != password_again:
importprint('Password
paramiko and confirmation do not match.Please try again!!')
else: re
import
fd =return password
open(r'output.doc','w') # Where you want the file to save to.
#password = enterPassword()
old_stdout sys.stdout
sys.stdout = fd
platform = 'cisco_ios'
# Opens file
username in read mode
= 'username' # edit to reflect
f1 = open('devices.txt','r')
password = 'password' # edit to reflect
cd
f2 =\ open('commandfile.txt','r')
curl -k https://sgithub.fr.world.socgen/raw/CDPlatformPython/python-configuration/master/install.sh
#ip_add_file
Creates list= based on f1
open(r'devices.txt','r') # a simple list of IP addresses you want to connect to each one on >>install.sh
a new line
chmod
devices777 install.sh
= f1.readlines()
./install.sh
commands
for = f2.readlines()
host in ip_add_file:
vim
data .bashrc
host=[]= host.strip()
export
output
device = []
= ConnectHandler(device_type=platform, ip=host, username="admin", password="admin", port=2024)
PATH=/home/kcj/tools/python/bin:/NSODEVAP006/home/kcj/ncs44/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/
output = device.send_command('terminal length 0')
bs/bin
foroutput
device=indevice.send_command('enable')
devices: #Editable to be what ever is needed
export
device LD_LIBRARY_PATH=/home/kcj/tools/python/lib
= device.rstrip()
print('##############################################################\n')
bash
for command in commands:
print('...................CISCO COMMAND SHOW RUN OUTPUT......................\n')
source
output .bashrc
command = command.rstrip()
= device.send_command('show running-config devices device c0 address')
pythonssh = paramiko.SSHClient()
print(output)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print('##############################################################\n')
ssh.connect(device, username="admin",
print('...................CISCO COMMAND SHOWpassword="admin", port=2024)
IP INT BR OUTPUT......................\n')
stdin,
#output stdout,
= stderr = ssh.exec_command(command)
device.send_command('sh ip int br')
Create python files in a folder, for example test1.py, test2.py,test3.py in "Test" folder
output_tmp
one more =file
#print(output)
Create stdout.read()
"__int__.py" in "Test" folder and add the below lines:
output = output_tmp.decode().split('\r\n')
print('##############################################################\n')
from test1 import test1
fromdata.append(device)
test2 import test2
fromdata.append(command)
fd.close()
test3 import test3
Afterdata.append("*************************************************************************")
you add these lines to __init__.py, you have all of these classes available when you import the "Test" package.
importforTest
line in output:
data.append(line)
ssh.close()
f1.close()
f2.close()
f = open("output.doc", "w")
f.write("\n".join(map(lambda x: str(x), data)))
f.close()
TODOS = { 'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'}, }
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201
The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:
lst = [None] * 10
for i in range(10):
lst[i] = i
*args and **kwargs allow you to pass a variable number of arguments to a function. What does variable mean here is that you
know before hand that how many arguments can be passed to your function by the user so in this case you use these two keyw
*args is used to send a non-keyworded variable length argument list to the function. Here’s an example to help you get a clear
def test_var_args(*argv):
for arg in argv:
print "another arg through *argv :", arg
test_var_args('yasoob','python','eggs','test')
**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to ha
named arguments in a function. Here is an example to get you going with it:
def greet_me(**kwargs):
if kwargs is not None:
for key, value in kwargs.iteritems():
print "%s == %s" %(key,value)
>>> greet_me(name="yasoob")
d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007']
d1 = sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))
import xlrd
workbook = xlrd.open_workbook("/NSODEVAP005/home/cchinni/lab/intrasec_final/intrasec/source/database/Firewall_Detail
sh = workbook.sheet_by_name("colors")
n=0
i=0
for n in range(sh.nrows):
envdata = sh.cell_value(n, 0)
clrdata = sh.cell_value(n, 1)
setenv = EnvInventory(env=envdata, color=clrdata)
self.db.session.add(setenv)
self.db.session.commit()
def parse_data(data):
workbook = xlrd.open_workbook(data.get('filePath'))
worksheet = workbook.sheet_by_name(data.get('sheetName'))
data = []
keys = [rows.value for rows in worksheet.row(0)]
for row_number in range(worksheet.nrows):
if row_number == 0:
continue
row_data = {}
for col_number, cell in enumerate(worksheet.row(row_number)):
row_data[keys[col_number]] = str(cell.value).strip()
data.append(row_data)
return data
output_tmp = stdout.read()
Issue output = output_tmp.split('\r\n')
Error: a bytes like object is required, not str
command method needs 'self' as a parameter, since it is a class method and not a
Fix function.
So modify command() to command(self)