0% found this document useful (0 votes)
8 views223 pages

Hacking With Python-Code Blocks

The document provides an overview of basic Linux terminal commands and Python programming concepts. It includes examples of file management, user creation, and Python syntax, along with explanations of variables, data types, and control structures. The content is structured into chapters that guide the reader through practical applications and programming fundamentals.

Uploaded by

alshykhtarq507
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views223 pages

Hacking With Python-Code Blocks

The document provides an overview of basic Linux terminal commands and Python programming concepts. It includes examples of file management, user creation, and Python syntax, along with explanations of variables, data types, and control structures. The content is structured into chapters that guide the reader through practical applications and programming fundamentals.

Uploaded by

alshykhtarq507
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

1

Chapter 5. Linux Terminal, Basic

Commands

Code block

root@kali:/home# pwd

/home

root@kali:/home#

Code block

Code block

root@kali:/# cd /home/sanjib/

root@kali:/home/sanjib# cd ..

root@kali:/home#

Code block
2

Code block

root@kali:/home# cp -v [Link]

/home/sanjib/Documents/

‘[Link]’ ->

‘/home/sanjib/Documents/[Link]’

root@kali:/home#

Code block

Code block

root@kali:/home# cd sanjib/Documents/

root@kali:/home/sanjib/Documents# ls

[Link]

root@kali:/home/sanjib/Documents#

Code block
3

Code block

cat [Link]

Code block

Code block

nano [Link]

Code block

Code block

hagudu@hagudu-H81M-S1:/etc/apt$ cat [Link] |

grep src

deb-src [Link] trusty

main restricted

deb-src [Link]

trusty-updates main restricted


4

deb-src [Link] trusty

universe

deb-src [Link]

trusty-updates universe

deb-src [Link] trusty

multiverse

deb-src [Link]

trusty-updates multiverse

deb-src [Link]

trusty-backports main restricted universe

multiverse

deb-src [Link] trusty-

security main restricted

deb-src [Link] trusty-

security universe

deb-src [Link] trusty-

security multiverse
5

# deb-src [Link]

trusty partner

deb-src [Link] trusty main

# deb-src [Link] trusty

universe

hagudu@hagudu-H81M-S1:/etc/apt$

Code block

Code block

cat [Link] | grep –i src

Code block

Code block

hagudu@hagudu-H81M-S1:~$ echo "I DON'T LIKE THIS

NOVEL ANYMORE SO I CHANGE IT" > [Link]


6

hagudu@hagudu-H81M-S1:~$ cat [Link]

I DON'T LIKE THIS NOVEL ANYMORE SO I CHANGE IT

hagudu@hagudu-H81M-S1:~$

Code block

Code block

mkdir Ethical Hacking

Code block

Code block

hagudu@hagudu-H81M-S1:~$ sudo rm -rf Ethical/

Hacking/

[sudo] password for hagudu:

hagudu@hagudu-H81M-S1:~$ ls
7

Code block

Code block

hagudu@hagudu-H81M-S1:~$ mkdir Ethical-Hacking

hagudu@hagudu-H81M-S1:~$ cd Ethical-Hacking/

hagudu@hagudu-H81M-S1:~/Ethical-Hacking$ ls

hagudu@hagudu-H81M-S1:~/Ethical-Hacking$ touch

file1 file2

hagudu@hagudu-H81M-S1:~/Ethical-Hacking$ ls

file1 file2

hagudu@hagudu-H81M-S1:~/Ethical-Hacking$

Code block

Code block

sanjib@kali:~$ cd Documents/
8

sanjib@kali:~/Documents$ ls

[Link]

sanjib@kali:~/Documents$ ls -la

total 7048

drwxr-xr-x 2 sanjib sanjib 4096 May 29 10:30 .

drwxr-xr-x 18 sanjib sanjib 4096 Jun 3 09:59 ..

-r-xr-xr-x 1 root root 7208397 May 29 10:30

[Link]

sanjib@kali:~/Documents$

Code block

Code block

-r-xr-xr-x 1 root root 7208397 May 29 10:30

[Link]

Code block
9

Code block

r-xr-xr-x

Code block

Code block

root@kali:~# adduser xman

Adding user `xman' ...

Adding new group `xman' (1002) ...

Adding new user `xman' (1001) with group `xman' ...

Creating home directory `/home/xman' ...

Copying files from `/etc/skel' ...

Enter new UNIX password:

Retype new UNIX password:


10

passwd: password updated successfully

Changing the user information for xman

Enter the new value, or press ENTER for the default

Full Name []: xman anonymous

Room Number []: 123

Work Phone []: 321

Home Phone []: 213

Other []: anon

Is the information correct? [Y/n] y

root@kali:~#

Code block

Code block

xman@kali:~$ cd Documents/

xman@kali:~/Documents$ ls
11

xman@kali:~/Documents$ ls -la

total 8

drwxr-xr-x 2 xman xman 4096 Jun 3 10:33 .

drwxr-xr-x 14 xman xman 4096 Jun 3 10:33 ..

xman@kali:~/Documents$

Code block

Code block

#!/usr/bin/python3

print("TYpe your name.")

inputs = input(">>>>>>")

outputs = inputs

def main():

print(outputs)

if __name__ == '__main__':

main()
12

Code block

xman@kali:~/Documents$ ls -la

total 12

drwxr-xr-x 2 xman xman 4096 Jun 3 10:50 .

drwxr-xr-x 15 xman xman 4096 Jun 3 10:42 ..

-rw-r--r-- 1 xman xman 86 Jun 3 10:44 [Link]

xman@kali:~/Documents$

Code block

Code block

xman@kali:~/Documents$ chmod +x [Link]

xman@kali:~/Documents$ ls -la

total 12

drwxr-xr-x 2 xman xman 4096 Jun 3 10:50 .


13

drwxr-xr-x 15 xman xman 4096 Jun 3 10:42 ..

-rwxr-xr-x 1 xman xman 86 Jun 3 10:44 [Link]

xman@kali:~/Documents$

Code block

Code block

xman@kali:~/Documents$ ./[Link]

TYpe your name.

>>>>>>xman

xman

Code block

PART TWO
14

Chapter 7. – Python Environment

Code block

hagudu@hagudu-H81M-S1:~$ python3

Python 3.4.3 (default, Oct 14 2015, [Link])

[GCC 4.8.4] on linux

Type "help", "copyright", "credits" or "license"

for more information.

>>>

Code block

Code block

>>> name = "Sanjib"

>>> print(name)

Sanjib

>>>
15

Code block

Code block

#!/usr/bin/python3

def main():

print(“Hello Python!”)

if __name__ == "__main__":

main()

Code block

Code block

sudo chmod +x [Link]

Code block

Code block
16

./[Link]

Code block

Chapter 8. – General Syntaxes

8.1 - Create the main() function

Code block

#!/usr/bin/python3

def main():

print(“I am a general syntax Python file”)

if __name__ == "__main__":

main()

Code block

Code block
17

#!/usr/bin/python3

def main():

print(“I am a general syntax Python file”)

LetUsDoSomething()

def LetUsDoSomething():

print(“I am doing something”)

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

LetUsDoSomething()
18

def LetUsDoSomething():

print(“I am doing something”)

Code block

8.2 - Indentation and White Space

Code block

# coding=utf-8

def main():

print('A line inside main function.')

print("A line outside main function.")

if __name__ == main():main()

Code block

Code block
19

# coding=utf-8

def main():

print('A line inside main function.')

print("A line outside main function.")

if __name__ == main():main()

Code block

Code block

# coding=utf-8

def main():

# print('A line inside main function.')

# print("A line outside main function.")

OutsideMainFunction()

def OutsideMainFunction():
20

x = 0

while x < 5:

print(x)

x = x + 1

if __name__ == main():main()

Code block

8.3 – Commenting

Code block

# this is main() function

def main():

OutsideMainFunction()

# this function is outside main() function

def OutsideMainFunction():
21

x = 0

while x < 5:

print(x)

x = x + 1

if __name__ == main():main()

Code block

8.4 - Assigning Values

Code block

#!/usr/bin/python3

# coding=utf-8

a = 1

print(a)

print(type(a))
22

print(id(a))

a = "One"

print(a)

print(type(a))

print(id(a))

Code block

Chapter 9. – Variables, Objects and

Values Code block

#!/usr/bin/python3

def main():

x = 1
23

print(x)

print(id(x))

print(type(x))

x = 2

print(x)

print(id(x))

print(type(x))

x = 1

print(x)

print(id(x))

print(type(x))

if __name__ == "__main__":

main()

Code block
24

Code block

#!/usr/bin/python3

# in python everything is object

# a variable is a reference to an object

# each object has an identity or an ID

x = 1

print(type(x))

print(id(x))

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

# class 'int'

# 139113568

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

# number, string, tuple -> immutable


25

# list, dictionary -> mutable

x = 1

y = 1

print(type(x))

print(id(x))

print(type(y))

print(id(y))

if x == y:

print("True")

else:

print("False")

if x is y:

print("True")

else:

print("False")

##################
26

# see the last two lines, both are true

# class 'int'

# 139113568

# class 'int'

# 139113568

# True

# True

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

a = dict(x = 1, y = 1)

print(type(a))

print(id(a))

b = dict(x = 1, y = 1)

print(id(b))

if a == b:

print("True")

else:
27

print("False")

if a is b:

print("True")

else:

print("False")

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

# see the last two lines, one is true but the

id is not same so it is false

# class 'dict'

# 3072650252

# 3072692524

# True

# False

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

for i in range(0, 3):

print(i, "=", id(i))


28

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

# 0 = 139113552

# 1 = 139113568

# 2 = 139113584

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

Code block

9.1 – Using Numbers

Code block

#!/usr/bin/python3

def main():

x = 3

print(x)

print(id(x))
29

print(type(x))

print("*********")

x = 3 /2

print(x)

print(id(x))

print(type(x))

print("*********")

x = round(42 / 9)

print(x)

print(id(x))

print(type(x))

print("*********")

# we want to round it up

x = 42 // 9

print(x)

print(id(x))
30

print(type(x))

print("*********")

# how many digits we want to round to

x = round(42 / 9, 3)

print(x)

print(id(x))

print(type(x))

print("*********")

x = 43 % 7

print(x)

print(id(x))

print(type(x))

print("*********")

x = int(34.78)

print(x)

print(id(x))
31

print(type(x))

print("*********")

x = float(23)

print(x)

print(id(x))

print(type(x))

print("*********")

if __name__ == "__main__":

main()

Code block

9.2 – String

Code block

#!/usr/bin/python3
32

def main():

strings = "I love you."

print(strings)

anotherStrings = "I love you but\nI don't know

how much you love me."

print(anotherStrings)

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

def main():
33

strings = "I love you."

print(strings)

anotherStrings = "I love you but\nI don't know

how much you love me."

print(anotherStrings)

rawStrings = r"I love you but\nI don't know how

much you love me."

print(rawStrings)

if __name__ == "__main__":

main()

Code block

Code block

days = 8
34

lyrics = "%s days a week is not enough to love

you." %days

print(lyrics)

Code block

Code block

days = 8

lyrics = "{} days a week is not enough to love

you."

print([Link](days))

Code block

Code block
35

newLines = """\

first line

second line

third line

more to come...

"""

print(newLines)

Code block

9.3 - What is Type and ID

Code block

>>> x = 10

>>> x
36

10

>>> type(x)

<class 'int'>

>>> id(x)

10455328

>>> y = 10

>>> y

10

>>> type(y)

<class 'int'>
37

>>> id(y)

10455328

>>> a = dict(name='sanjib')

>>> a

{'name': 'sanjib'}

>>> type(a)

<class 'dict'>

>>> id(a)
38

139984318683592

>>> b = dict(name='sanjib')

>>> b

{'name': 'sanjib'}

>>> type(b)

<class 'dict'>

>>> id(b)

139984318683720
39

>>> a == b

True

>>> a is b

False

>>>

Code block

Code block

>>> x == y

True
40

>>> x is y

True

>>>

Code block

Code block

>>> a = dict(name='sanjib')

>>> a

{'name': 'sanjib'}

>>> type(a)

<class 'dict'>
41

>>> id(a)

139984318683592

>>> b = dict(name='sanjib')

>>> b

{'name': 'sanjib'}

>>> type(b)

<class 'dict'>

>>> id(b)
42

139984318683720

>>> a == b

True

>>> a is b

False

>>>

Code block

9.4 - Logical Values


43

Let us consider another shell script for testing

logical values True and False.

Code block

>>> a, b = 0, 1

>>> a == b

False

>>> a < b

True

>>> a > b

False
44

>>> a = True

>>> a

True

>>> type(a)

<class 'bool'>

>>> id(a)

10348608

>>> b = True
45

>>> b

True

>>> type(b)

<class 'bool'>

>>> id(b)

10348608

>>>

Code block
46

9.5 - Tuples And Lists

Code block

x = (1, 2, 3, 4)

print(x)

print(type(x))

Code block

Code block

for i in x:

print(i)

Code block

Code block

a = [1, 2, 3, 4]

print(a)

print(type(a))
47

Code block

Code block

#!/usr/bin/python3

# tuple

x = (1, 2, 3, 4)

# list

a = [1, 2, 3, 4]

# appending tuple x to list

[Link](x)

print(a)

# inserting tuple x in the first position

[Link](0, x)
48

print(a)

# Now iterating the final list a

for i in a:

print(i)

Code block

Code block

strings = "This is a string."

for WeWillIterateThroughIt in strings:

print(WeWillIterateThroughIt)

Code block

Code block

strings = "string."

print(strings[1:3])
49

Code block

9.6 – Dictionary

Code block

#!usr/bin/python3

EnglishDictionaries = {'bare':'jejune',

'anger':'dudgeon', 'abuse':'vituperate',

'howl':'ululate'}

print(EnglishDictionaries)

# getting in a nmore human readable form

for keys in EnglishDictionaries:

print(keys, "=", EnglishDictionaries[keys])

Code block

Code block

EnglishDictionaries = {'bare':'jejune',
50

'anger':'dudgeon', 'abuse':'vituperate',

'howl':'ululate'}

for keys in sorted([Link]()):

print(keys, "=", EnglishDictionaries[keys])

Code block

Code block

synonyms = dict(bare='jejune', anger='dudgeon',

abuse= 'vituperate', howl= 'ululate')

Code block

9.7 – Object

Code block

#!/usr/bin/python3

class Human:
51

def __init__(self, kind = "Good"):

[Link] = kind

def whatKind(self):

return [Link]

def main():

GoodHuman = Human()

print([Link]())

BadHuman = Human("Bad")

print([Link]())

if __name__ == "__main__":

main()

Code block

Code block

class Human:

def __init__(self, kind = "Good"):


52

[Link] = kind

def whatKind(self):

return [Link]

Code block

Code block

def whatKind(self):

return [Link]

Code block

Code block

def main():

GoodHuman = Human()

print([Link]())

BadHuman = Human("Bad")

print([Link]())
53

if __name__ == "__main__":

main()

Code block

Chapter 10 – Conditionals

Code block

def conditionals_exec():

a, b = 1, 3

if a < b:

print("a is less than b")

elif a > b:

print("a is greater than b")

else:

print("a is equal to b")

conditionals_exec()
54

Code block

Code block

def conditional_values():

a, b = 1, 2

statements = "less than " if a < b else " not

less than."

print(statements)

conditional_values()

Code block

Code block

def main():

print("This is main function.")

conditionals_exec()

conditional_values()
55

def conditionals_exec():

a, b = 1, 3

if a < b:

print("a is less than b")

elif a > b:

print("a is greater than b")

else:

print("a is equal to b")

def conditional_values():

a, b = 1, 2

statements = "less than " if a < b else " not

less than."

print(statements)
56

if __name__ == "__main__": main()

Code block

Chapter 11 – Loops

11.1 – While Loops

Code block

b = 1

while b < 50:

print(b)

b = b + 1

Code block

Code block

#!/usr/bin/python3
57

# simple fibonacci series

# sum of two numbers define the next set

a, b = 0, 1

while b < 50:

print(b, end=' ')

a, b = b, a + b

Code block

Code block

#!/usr/bin/python3

a, b = 0, 1

while b < 30:

print(b, end=' ')

a = b

b = a + b

Code block
58

Code block

#!/usr/bin/python3

# simple fibonacci series

# sum of two numbers define the next set

a, b = 0, 1

while b < 30:

print("a = ", a, "=" , "b = ", b, "," , end='

')

a, b = b, a + b

print("***********")

a, b = 0, 1

while b < 30:

print("a = ", a, "=" , "b = ", b, "," , end='

')

a = b
59

b = a + b

Code block

11.2 - For Loops

Code block

#!/usr/bin/python3

songs = open('[Link]')

for lines in [Link]():

print(lines, end='')

Code block

Code block

# enumerate

songs = open('[Link]')

for index, lines in enumerate([Link]()):

print(index, lines, end='')


60

Code block

Code block

strings = "This is a string."

# now we are going to find how many 's' is inside

this string

for index, s in enumerate(strings):

if s == 's':

print("Hi I am 's' and I am located at

position {}".format(index))

Code block

Code block

#!/usr/bin/python3

def main():

loops(0)
61

loops()

loops(3)

def loops(a = 4):

for i in range(a, 6):

print(i, " ")

print("*************")

if __name__ == "__main__":

main()

Code block

Chapter 12. - Regular Expressions

12.1 – Using ‘re’ Module

Code block
62

#!/usr/bin/python3

import re

def main():

ReplaceWord()

DEmarcationLine()

MatchAndReplaceWord()

def ReplaceWord():

try:

files = open("../primary/[Link]")

for line in files:

# you can search any word

print([Link]('lenor|more', "#####",

line), end=' ')

except FileNotFoundError as e:

print("File was not found:", e)


63

def MatchAndReplaceWord():

try:

files = open("../primary/[Link]")

for line in files:

# you can search any pattern that can

match and then replace with this word

match = [Link]('(len|neverm)ore',

line)

if match:

print([Link]([Link](),

"#####"), end=' ')

except FileNotFoundError as e:

print("File was not found:", e)

def DEmarcationLine():
64

print("*************")

if __name__ == "__main__":

main()

Code block

12.2 - Reusing With Regular Expressions

Code block

#!/usr/bin/python3

import re

def main():

CompilerAndReplaceWord()

def CompilerAndReplaceWord():

try:
65

files = open("../primary/[Link]")

# you can search any pattern that can match

ignoring the upper or lower case

pattern = [Link]('(len|neverm)ore',

[Link])

for line in files:

# re module search that pattern in a

line

if [Link](pattern, line):

# we found that patetrn and now it

is time to replace them with a new string

print([Link]("######", line),

end=' ')

except FileNotFoundError as e:

print("File was not found:", e)

if __name__ == "__main__":
66

main()

Code block

12.3 - Searching With Regular

Expressions

Code block

#!/usr/bin/python3

import re

def main():

FindWord()

DEmarcationLine()

MatchWord()

def FindWord():

try:

files = open("../primary/[Link]")
67

for line in files:

# you can search any word

if [Link]('lenor|more', line):

print(line, end=' ')

except FileNotFoundError as e:

print("Fiel was not found:", e)

def MatchWord():

try:

files = open("../primary/[Link]")

for line in files:

# you can search any pattern that can

match this word

match = [Link]('(len|neverm)ore',

line)

if match:

print([Link]())
68

except FileNotFoundError as e:

print("Fiel was not found:", e)

def DEmarcationLine():

print("*************")

if __name__ == "__main__":

main()

Code block

Chapter 13. – Exceptions, Catching

Errors

Code block

>>> for i in range(10) print(i)

SyntaxError: invalid syntax

Code block
69

Code block

>>> 10 * x

Traceback (most recent call last):

File "<pyshell#1>", line 1, in <module>

10 * x

NameError: name 'x' is not defined

>>> 10 / 0

Traceback (most recent call last):

File "<pyshell#2>", line 1, in <module>

10 / 0

ZeroDivisionError: division by zero

>>> '2' + 2

Traceback (most recent call last):

File "<pyshell#3>", line 1, in <module>

'2' + 2
70

TypeError: Can't convert 'int' object to str

implicitly

>>> inputs = input("Please enter a number.")

Please enter a number.

>>> inputs + 2

Traceback (most recent call last):

File "<pyshell#5>", line 1, in <module>

inputs + 2

TypeError: Can't convert 'int' object to str

implicitly

>>> inputs = input("Please enter a number.")

Please enter a number.12

>>> inputs - 10

Traceback (most recent call last):

File "<pyshell#7>", line 1, in <module>

inputs - 10
71

TypeError: unsupported operand type(s) for -: 'str'

and 'int'

>>> int(inputs) - 10

>>>

Code block

Code block

#!/usr/bin/python3

def main():

FileRead()

DemarcationLine()

LineStrip()

DemarcationLine()

CheckFileExtension()

def ReadFile(filename):
72

files = open(filename)

lines = [Link]()

for index, line in enumerate(lines):

print(index, "=", line)

def StripFile(filename):

files = open(filename)

for lines in files:print([Link]())

def RaisingError(filename):

if [Link](".txt"):

lines = open(filename)

for line in lines:print([Link]())

else:

raise ValueError("File must end with .txt")

def FileRead():

try:

ReadFile("../primary/[Link]") # path is
73

okay, it reads file

except IOError as e:

print("Could not open file:", e)

def LineStrip():

try:

StripFile("primary/[Link]")

except IOError as e:

print("Could not open file:", e) # it will

give error

def CheckFileExtension():

try:

RaisingError("../primary/[Link]")

except IOError as e:

print("Could not open file:", e)

except ValueError as e:

print("Bad Filename:", e)
74

def DemarcationLine():

print("******************")

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

def main():

GetARangeOfNumber()

def GetARangeOfNumber():

for index in IteratingStepByStep(1,123, 7):

print(index, end=' ')

def IteratingStepByStep(start, stop, step):

number = start

while number <= stop:


75

yield number

number += step

if __name__ == "__main__":

main()

Code block

Chapter 14. - Functions

Code block

#!/usr/bin/python3

def main():

print("This is main function.")

if __name__ == "__main__":

main()

Code block
76

Code block

print(“*************”)

Code block

Code block

def DemarcationLine():

print(“*********”)

DemarcationLine():

DemarcationLine():

DemarcationLine():

Code block

Code block

def AnotherFunction():

print("I am another function.")

def TestFunction():
77

print("I am going to call another function.")

AnotherFunction()

TestFunction()

Code block

Code block

def TestFunction():

print("I am going to call another function.")

AnotherFunction()

TestFunction()

def AnotherFunction():

print("I am another function.")

Code block
78

Code block

#!/usr/bin/python3

def main():

TestFunction()

def TestFunction():

print("I am going to call another function.")

AnotherFunction()

def AnotherFunction():

print("I am another function.")

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

def main():
79

PassingParameters(1,2,3)

def PassingParameters(argument1, argument2,

argument3):

print("Here is our arguments:", argument1,

argument2, argument3)

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

def main():

PassingParameters(1)

def PassingParameters(argument1, argument2 = 4,

argument3 = 6):

print("Here is our arguments:", argument1,


80

argument2, argument3)

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

def main():

PassingParameters(1, 10, 14)

def PassingParameters(argument1, argument2 = 4,

argument3 = 6):

print("Here is our arguments:", argument1,

argument2, argument3)

if __name__ == "__main__":

main()

Code block
81

Code block

#!/usr/bin/python3

def main():

PassingParameters(1)

def PassingParameters(argument1, argument2 = None,

argument3 = 6):

if argument2 == None:

print("Here is our arguments:", argument1,

argument2, argument3)

else:

print("Here is our arguments:", argument1,

argument2, argument3)

if __name__ == "__main__":

main()

Code block
82

Code block

#!/usr/bin/python3

def main():

PassingParameters(1, 12)

def PassingParameters(argument1, argument2 = None,

argument3 = 6):

if argument2 == None:

print("Here is our arguments:", argument1,

argument2, argument3)

else:

print("Here is our arguments:", argument1,

argument2, argument3)

if __name__ == "__main__":

main()

Code block
83

14.1 - Return Values

Code block

#!/usr/bin/python3

def main():

for index in ReturnValues():

print(index, end=" ")

def ReturnValues():

#return "Returning string."

#return 56

return range(10)

if __name__ == "__main__":

main()

Code block
84

14.2 - Generate Functions

Code block

#!/usr/bin/python3

def main():

RangeFunctions()

def RangeFunctions():

for i in range(10):

print(i, end=' ')

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

def main():
85

for index in RangeFunctions(0, 10, 1):

print(index, end=' ')

def RangeFunctions(start, stop, step):

i = start

while i <= stop:

yield i

i += step

if __name__ == "__main__":

main()

Code block

Code block

for index in RangeFunctions(15, 1025, 102):

print(index, end=' ')

Code block
86

Code block

def AnotherRangeFunctions(start = 0, stop, step =

1):

i = start

while i <= stop:

yield i

i += step

Code block

Code block

for index in AnotherRangeFunctions(25):

print(index, end=' ')

Code block

Code block
87

def AnotherRangeFunctions(*args):

numberOfArguments = len(args)

if numberOfArguments < 1: raise TypeError('At

least one argument is required.')

elif numberOfArguments == 1:

stop = args[0]

start = 0

step = 1

elif numberOfArguments == 2:

# start and stop will be tuple

(start, stop) = args

step = 1

elif numberOfArguments == 3:

# all start and stop and step will be tuple

(start, stop, step) = args


88

i = start

while i <= stop:

yield i

i += step

Code block

14.3 - Lists of Arguments

Code block

#!/usr/bin/python3

def main():

PassingListsOfArguments(1, 2, 3, 5, 7, 45, 98,

56, 4356, 90876543)

PassingAnotherListsOfArguments(1, 2, 3, 5, 7,

45, 98, 76, 987654, 3245, 2345, 98760)


89

def PassingListsOfArguments(arg1, arg2, arg3, arg4,

*args):

print(arg1, arg2, arg3, arg4, args)

def PassingAnotherListsOfArguments(param1, param2,

*params):

print(param1, param2)

for index in params:

if index == 76:

x = 10

y = index + x

print("We are going to add 10 with",

index, "and the new value is:", y)

continue

print(index, end=' ')


90

if __name__ == "__main__":

main()

Code block

18.4 - Named Arguments

Code block

#!/usr/bin/python3

def main():

NamedArguments(name = 'Sanjib', address =

'Pluto', hobby = "Gardening")

def NamedArguments(**kwargs):

for key in kwargs:

print(key, "=", kwargs[key])

if __name__ == "__main__":

main()

Code block
91

Code block

#!/usr/bin/python3

def main():

NamedArguments(name = 'Sanjib', address =

'Pluto', hobby = "Gardening")

DemarcationLine()

AnotherNamedArguments('Hi', 1235, 1,2,3, one =

1, two = 2, three = 3)

def NamedArguments(**kwargs):

for key in kwargs:

print(key, "=", kwargs[key])

def AnotherNamedArguments(arg1, arg2, *args,

**kwargs):
92

print(arg1, arg2)

for index in args:

print(index, end=' ')

DemarcationLine()

for keys in kwargs:

print(keys, "=", kwargs[keys])

def DemarcationLine():

print("********")

if __name__ == "__main__":

main()

Code block

Chapter 15 - Classes
93

15.1 – Object Oriented Methodology

15.1 - Understanding Classes and Objects

Code block

#!/usr/bin/python3

class Robot:

def __init__(self):

pass

def WalkLikeARobot(self):

print("walks like a robot.")

def CareLikeARobot(self):

print("takes care like a robot.")

robu1 = Robot()

print(type(robu1))

print(id(robu1))
94

robu2 = Robot()

print(type(robu2))

print(id(robu2))

del robu2

def main():

robu = Robot()

print(type(robu))

print(id(robu))

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

class Robots:

def __init__(self):
95

pass

def WalkLikeARobot(self, style):

[Link] = style

return [Link]

def CareLikeARobot(self):

print("takes care like a robot.")

class Humans:

def __init__(self, nature = "good"):

[Link] = nature

def GoodHumanBeing(self):

print("need not repeat, a good human being

is always", [Link])

def BadHUmanBeing(self):

[Link] = "need not repeat, bad human

being is always bad."

print([Link])
96

def WalkLikeARobot(self, style):

[Link] = style

return [Link]

def main():

robu = Robots()

[Link]()

print([Link]("walks like a

robot"))

GoodMan = Humans()

print([Link])

[Link]()

BadMan = Humans()

[Link] = "bad"

print([Link])

[Link]()

print([Link]("he is human but


97

walks like a robot"))

if __name__ == "__main__":

main()

Code block

Code block

print(type([Link](dict(one=1,

two=2))))

st = [Link](dict(one=1, two=2))

for keys in sorted(st):

print(keys, st[keys])

ws = [Link]({'one':56, 'two':2})

for keys in sorted(ws):

print(keys, ws[keys])

Code block
98

15.2 – Write Your Own Game “Good VS Bad”

Code block

Sudo chmod +x [Link]

Code block

Code block

./ [Link]

Code block

Code block

#!/usr/bin/python3

class Robots:

def __init__(self):

pass

def WalkLikeARobot(self, WalkingStyle):


99

[Link] = WalkingStyle

return [Link]

def CareLikeARobot(self):

print("takes care like a robot.")

class Humans:

def __init__(self, nature = "good"):

[Link] = nature

def GoodHumanBeing(self):

print("need not repeat, a good human being

is always", [Link])

def BadHUmanBeing(self):

[Link] = "need not repeat, bad human

being is always bad."

print([Link])

def WalkLikeARobot(self, WalkingStyle):

[Link] = WalkingStyle
100

return [Link]

def main():

robu = Robots()

# [Link]()

# print([Link]("A robot walks like

a robot and nothing happens."))

GoodMan = Humans()

# print([Link])

# [Link]()

BadMan = Humans()

# [Link] = "bad"

# print([Link])

# [Link]()

# print([Link]("he is human but

walks like a robot"))

# when a bad man wlaks like a robot many things


101

happen

WhenABadManWalksLikeARobot =

[Link](dict(change = 'he becomes a

monster inside',

act = 'he kills

fellow people',

feel = 'he enjoys

torturing animals',

care = 'he cares for

none',

look = 'he looks a

normal human being',

state = 'finally he

destroys himself'))

# there are lot of actions that take place

print("What happens when a Bad Man walks like a

Robot?")
102

change = input("Tell us what kind of change may

take place inside him?\n Choose between 'monster'

and 'angel',"

"and type here...>>>>")

WhenABadManWalksLikeARobot['change'] = change

reward = 0

if change == 'monster':

print("You have won the first round:",

change)

reward = 1000

print("You have won ", reward, "points.")

print("What does he do? :",

WhenABadManWalksLikeARobot['act'])

change = input("Now tell us what the

monster feels inside while killing people?\n Choose

between 'great' and 'sad',"

"and type here...>>>>")


103

WhenABadManWalksLikeARobot['change'] =

change

if change == 'great':

print("You have won the second round:")

reward = 10000

print("You have won ", reward,

"points.")

print("What he feels inside? :",

WhenABadManWalksLikeARobot['feel'])

change = input("Tell us does the

monster care for anyone?\n Choose between 'yes' and

'no',"

"and type here...>>>>")

WhenABadManWalksLikeARobot['change'] =

change

if change == 'no':

print("You have won the third


104

round:")

reward = 100000

print("You have won ", reward,

"points.")

print("What he feels inside? :",

WhenABadManWalksLikeARobot['care'])

change = input("Tell us does the

monster look like a normal human being?\n Choose

between 'yes' and 'no',"

"and type here...>>>>")

WhenABadManWalksLikeARobot['change'

] = change

if change == 'yes':

print("You have won the fourth

round:")

reward = 1000000

print("You have won ", reward,


105

"points.")

print("What does he look

like? :", WhenABadManWalksLikeARobot['look'])

change = input("Tell us what

happens to the monster finally? Does he destroy

himself\n Choose between 'yes' and 'no',"

"and type

here...>>>>")

WhenABadManWalksLikeARobot['cha

nge'] = change

if change == 'yes':

print("You have won the

fifth round:")

reward = 100000000

print("You have won

Jackpot.", reward, "points.")

else:
106

print("You have changed the

course of game. It ends here. You have lost",

reward - 100000, "points.")

else:

print("You have changed the

course of game. It ends here. You have lost",

reward - 1000, "points.")

else:

print("You have changed the course

of game. It ends here. You have lost", reward -

100, "points.")

else:

print("You have changed the course of

game. It ends here. You have lost", reward - 10,

"points.")

else:

print("You have changed the course of game.


107

It ends here and you have won no point.")

if __name__ == "__main__":

main()

Code block

15.3 - Primary Class and Object

Code block

#!/usr/bin/python3

class Human:

def __init__(self, kind = "good"):

[Link] = kind

def BeingHuman(self):

return [Link]

def main():

good = Human()

bad = Human("bad")
108

print([Link] ())

print([Link] ())

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

class MySelf:

def __init__(self, name, quantity):

[Link] = name

[Link] = quantity

def Eat(self):

print([Link], "eats", [Link],

"bananas each day.")

def main():
109

hagu = MySelf("Hagu", 2)

mutu = MySelf("Mutu", 3)

[Link]()

[Link]()

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

import sqlite3

import [Link]

from [Link] import Error

class MySQLiteConnection:

def __init__(self):

db = [Link]('[Link]')
110

[Link]()

print("Connected to SqLite3")

class MyMySQLConnection:

def __init__(self):

try:

### you can either use a dictionary object

or you can connect directly ###

### using a dictioanry object ###

kwargs = dict(host = 'localhost',

database = 'python_mysql', user = 'root', password

= 'pass')

conn =

[Link](**kwargs)

### connecting directly ###

connection =

[Link](host = 'localhost',
111

database = 'python_mysql',

user =

'root',

password = 'pass')

if connection.is_connected():

print("Connected to MySQL from

'conneection' object")

# if conn.is_connected():

# print("Connected from 'conn'

object")

except Error as e:

print(e)

finally:

[Link]()

def main():

ConnectToMySQL = MyMySQLConnection()
112

ConenctToSqLite = MySQLiteConnection()

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

import sqlite3

import [Link]

from [Link] import MySQLConnection, Error

class MySQLiteConnection:

def __init__(self, db =

[Link]('[Link]')):
113

[Link] = db

db.row_factory = [Link]

print("Connected to SqLite3")

def Retrieve(self):

print("Retreiving values from table test1

of SqLite database test")

read = [Link]('select * from test1

order by i1')

for row in read:

print(row['t1'])

class MyMySQLConnection:

def __init__(self, kwargs = dict(host =

'localhost', database = 'testdb', user = 'root',

password = 'pass')):

try:

### you can either use a dictionary object

or you can connect directly ###


114

### using a dictioanry object ###

[Link] = kwargs

conn =

[Link](**kwargs)

if conn.is_connected():

print("Connected to MySql database

testdb from 'conn' object")

except Error as e:

print(e)

finally:

[Link]()

def Retrieve(self):

print("Retreiving records from MySql

database testdb.")

try:
115

conn = MySQLConnection(**[Link])

cursor = [Link]()

[Link]("SELECT * FROM

EMPLOYEE")

rows = [Link]()

print('Total Row(s):', [Link])

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:

[Link]()
116

[Link]()

def main():

ConnectToMySQL = MyMySQLConnection()

[Link]()

ConenctToSqLite = MySQLiteConnection()

[Link]()

if __name__ == "__main__":

main()

Code block

15.4 – Accessing Object Data

Code block

#!/usr/bin/python3

class Human:

def __init__(self, height = 5.08):

[Link] = height
117

def main():

ramu = Human()

print([Link])

[Link] = 5.11 # it is called side effect

and hard to track

print([Link])

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

class Human:

def __init__(self):

pass

# accessor
118

def set_height(self, height):

[Link] = height

def get_height(self):

return [Link]

def main():

ramu = Human()

# [Link] = 5.11 # it is called side effect

and hard to track

ramu.set_height(5.12)

print(ramu.get_height())

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3
119

class Human:

def __init__(self, **kwargs):

[Link] = kwargs

def set_manyVariables(self, **kwargs):

[Link] = kwargs

def set_variables(self, key, value):

[Link][key] = value

def get_variables(self, key):

return [Link](key, None)

def main():

mana = Human(name = 'Mana')

print("Object Mana's name:",

[Link]['name'])

ManaName = [Link]['name']

mana.set_variables('class', 'two')

print(ManaName, "reads at class",


120

mana.get_variables('class'))

mana.set_manyVariables(school = 'balika

school', height = 4.54)

print(ManaName, "has height of",

[Link]['height'], "and her school's name

is", [Link]['school'])

babu = Human(name = 'Babu', student_of = 'Class

Three', reads_at = ' Balak School', height = 5.21)

BabuName = [Link]['name']

print(BabuName, "he is a student of",

[Link]['student_of'], "and he reads at",

[Link]['reads_at'], "and his

height is", [Link]['height'])

if __name__ == "__main__":

main()

Code block
121

19.5 - Polymorphism

Code block

#!/usrbin/python3

class Table:

def __init__(self):

pass

def ItHolds(self):

print("A table holds books, writing pads on

it.")

def YouCanWriteOnit(self):

print("You can write on a table.")

class Book:

def __init__(self):

pass

def ItHelps(self):
122

print("A book helps us to know something

new.")

def main():

MyTable = Table()

MyBook = Book()

[Link]()

[Link]()

[Link]()

if __name__ == "__main__":

main()

Code block

Code block

#!/usrbin/python3

class Table:
123

def __init__(self):

pass

def Get(self):

print("Please get me that table.")

def Put(self):

print("Please put the table on the corner

of the room.")

def Destroy(self):

print("Some people came and they did not

want us to read and write. They destroted the

table.")

class Book:

def __init__(self):

pass

def Get(self):
124

print("Please get me that book.")

def Put(self):

print("We put some new books on the

table.")

def Destroy(self):

print("Some people came and they did not

want us to read and write. They destroyed the

book.")

def main():

MyTable = Table()

MyBook = Book()

InMistake(MyBook)

Intentionally(MyTable)

def InMistake(Table):

[Link]()

[Link]()
125

[Link]()

def Intentionally(Book):

[Link]()

[Link]()

[Link]()

if __name__ == "__main__":

main()

Code block

15.6 - Using Generators

Code block

#!/usr/bin/python3

class InclusiveRange:

def __init__(self, *args):

numberOfArguments = len(args)
126

if numberOfArguments < 1: raise

TypeError('At least one argument is required.')

elif numberOfArguments == 1:

[Link] = args[0]

[Link] = 0

[Link] = 1

elif numberOfArguments == 2:

# start and stop will be tuple

([Link], stop) = args

[Link] = 1

elif numberOfArguments == 3:

# all start and stop and step will be

tuple

([Link], [Link], [Link]) =

args

else: raise TypeError("Maximum three


127

arguments. You gave {}".format(numberOfArguments))

def __iter__(self):

i = [Link]

while i <= [Link]:

yield i

i += [Link]

def main():

ranges = InclusiveRange(5, 210, 10)

for x in ranges:

print(x, end=' ')

if __name__ == "__main__":

main()

Code block
128

Code block

## the function below is perfectly working also but

that is not a generator ##

def RangeFunctions(self, *args):

numberOfArguments = len(args)

if numberOfArguments < 1: raise

TypeError('At least one argument is required.')

elif numberOfArguments == 1:

[Link] = args[0]

[Link] = 0

[Link] = 1

elif numberOfArguments == 2:

# start and stop will be tuple

([Link], stop) = args


129

[Link] = 1

elif numberOfArguments == 3:

# all start and stop and step will be

tuple

([Link], [Link], [Link]) =

args

else: raise TypeError("Maximum three

arguments. You gave {}".format(numberOfArguments))

i = [Link]

while i <= [Link]:

yield i

i += [Link]

Code block
130

15.7 - Inheritance

Code block

#!/usr/bin/python3

class AllUsers:

def __init__(self):

pass

def Register(self):

print("Please Register")

def Login(self):

print("Welcome Member.")

class Admin(AllUsers):

def __init__(self):

pass

def Register(self):

print("Admins need not register")


131

def Login(self):

print("Welcome Admin")

class Members(AllUsers):

def __init__(self):

pass

def main():

admin = Admin()

[Link]()

[Link]()

member = Members()

[Link]()

[Link]()

if __name__ == "__main__":

main()

Code block
132

19.8 -Decorator

Code block

#!/usr/bin/python3

class Dog:

def __init__(self, **kwargs):

[Link] = kwargs

def get_properties(self):

return [Link]

def set_properties(self, key):

[Link](key, None)

def main():

lucky = Dog(nature = 'obedient')

print([Link]('nature'))
133

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

class Dog:

def __init__(self, **kwargs):

[Link] = kwargs

@property

def Color(self):

return [Link]('color', None)

@[Link]

def Color(self, color):

[Link]['color'] = color
134

@[Link]

def Color(self):

del [Link]['color']

def main():

lucky = Dog()

# now we are going to use the decorator function as

a normal property

[Link] = 'black and yellow'

print([Link])

if __name__ == "__main__":

main()

Code block

Chapter 16 - String Methods


135

Code block

hagudu@hagudu-H81M-S1:~$ python3

Python 3.4.0 (default, Jun 19 2015, [Link])

[GCC 4.8.2] on linux

Type "help", "copyright", "credits" or "license"

for more information.

>>> 'this is a string'

'this is a string'

>>> s = 'this is a string'


136

>>> s

'this is a string'

>>> [Link]()

'THIS IS A STRING'

>>> s = 'this is a string now we are going to add

an integer into it as string {}'

>>> [Link](100)

'this is a string now we are going to add an

integer into it as string 100'


137

>>> 'in python2 it was written like %d' % 100

'in python2 it was written like 100'

>>>

Code block

Code block

>>> s = 'this is a string'

>>> s

'this is a string'

>>> [Link]()
138

'THIS IS A STRING'

>>> [Link]()

'this is a string'

>>> s = 'This Is A String'

>>> s

'This Is A String'

>>> [Link]()

'tHIS iS a sTRING'
139

>>> s

'This Is A String'

>>> s = 'this is a string'

>>> [Link]('is')

>>>

Code block

Code block

#!/usr/bin/python3
140

s = 'this is a string'

print([Link]('is'))

newstring = [Link]('this', 'that')

print(newstring)

UpperString = [Link]()

print(UpperString)

# string is mutable, so id has been changed for the

same string

print(id(s))

print(id(UpperString))

a = ' this is string with lot of whitespace at

the beginning and at the end '

# by default it removes white space from start and

end

RemovingWhiteSpace = [Link]()

print(RemovingWhiteSpace)
141

print([Link]('this'))

Code block

Code block

x, y = 10, 11

f = "this {} is added and thereafter we add {}"

FormattedString = [Link](x, y)

print(FormattedString)

# we could have written it in C style

m, n = 10, 11

f = "this %d is added and thereafter we add %d"

FormattedString = f % (x, y)

print(FormattedString)

Code block

Code block
142

a, b = 10, 11

s = "This is {}, and that is {}"

FormattedStirng = [Link](a, b)

print(FormattedStirng)

# we change the position

FormattedStirng = [Link](b, a)

print(FormattedStirng)

s = "This is {0}, and that is {1} and this too is

{0} and that too is {1}"

FormattedStirng = [Link](a, b)

print(FormattedStirng)

# we can change it according to our wish with the

positional argument

s = "This is {1}, and that is {1} and this too is

{0} and that too is {1}"

FormattedStirng = [Link](a, b)
143

print(FormattedStirng)

# we can use it as dictionary

s = "This is {mine}, and that is {your} and this

too is {your} and that too is {mine}"

FormattedStirng = [Link](mine = a, your = b)

print(FormattedStirng)

# more dictionary staff

s = "This is my wish: {mine}, and that is your wish

:{your} and this too is mine: {mine} and that too

is mine: {mine}"

FormattedStirng = [Link](mine = "I want to remove

'I'", your = "Do you want to remove 'yourself'?")

print(FormattedStirng)

Code block

Code block
144

strings = "This is a string"

print(type(strings))

print(id(strings))

AnotherStrings = "This is a string"

print(type(AnotherStrings))

print(id(AnotherStrings))

print([Link]())

words = [Link]()

[Link]("and that ia also a string.")

print(type(words))

print(words[0])

NewWords = ":".join(words)

print(NewWords)

NewWords = ",".join(words)

print(NewWords)

words[0] = "That"
145

print(words)

Code block

Chapter 17. - File Input And Output

Code block

infile = open('[Link]', 'r')

outfile = open('[Link]', 'w')

for line in infile:

print(line, file=outfile)

print("Done")

Code block

Code block

BufferSize = 500000
146

infile = open('[Link]', 'r')

outfile = open('[Link]', 'w')

buffer = [Link](BufferSize)

while len(buffer):

[Link](buffer)

print("It is copying, it might take some

time...please wait....", end='')

buffer = [Link](BufferSize)

print()

print("Copying Done.")

Code block

Code block

BufferSize = 5000000

infile = open('[Link]', 'rb')

outfile = open('[Link]', 'wb')


147

buffer = [Link](BufferSize)

while len(buffer):

[Link](buffer)

print("It is copying an image, it might take

some time...please wait....", end='')

buffer = [Link](BufferSize)

print()

print("Copying Done.")

Code block

Chapter 18. - Containers

Code block

#!/usr/bin/python3

tuples1 = 1, 2, 3, 4

print(type(tuples1))
148

print(id(tuples1))

tuples2 = (1, 2, 3, 4)

print(type(tuples2))

print(id(tuples2))

print(tuples1[0])

print(tuples2[0])

# it will give the last item

print(tuples2[-1])

print(type(tuples1[0]))

print(type(tuples2[0]))

print(id(tuples1[0]))

print(id(tuples2[0]))

# tuple is immutable we can not change any value

# 'tuple' object does not support item assignment

# tuples2[0] = 120

# print(tuples2)
149

# to make an integer tuple you need to add comma

separator

IsItTuple = (1)

print(type(IsItTuple))

IsItTuple = (1,)

print(type(IsItTuple))

# let us see how list behaves

list1 = [1, 2, 3, 4]

print(type(list1))

print(id(list1))

# first item

print(list1[0])

# last item

print(list1[-1])

# we can change the value of a list item

list1[0] = 120
150

print(list1) # output: [120, 2, 3, 4]

Code block

18.1 - Operating on Tuple and List

Object

Code block

root@kali:~# python3

Python 3.4.4 (default, Jan 5 2016, [Link])

[GCC 5.3.1 20160101] on linux

Type "help", "copyright", "credits" or "license"

for more information.

>>> t = (1,2,3,4)

>>> t

(1, 2, 3, 4)

>>> t[0]

1
151

>>> t = tuple(range(25))

>>> type(t)

<class 'tuple'>

>>> 50 in t

False

>>> 10 in t

True

>>> for i in t:print(i)

...

6
152

10

11

12

13

14

15

16

17

18

19

20

21

22
153

23

24

>>> l = list(range(20))

>>> type(l)

<class 'list'>

>>> for i in l:

... print(i)

File "<stdin>", line 2

print(i)

IndentationError: expected an indented block

>>> for i in l:print(i)

...

2
154

10

11

12

13

14

15

16

17

18
155

19

>>> l[2]

>>> 50 in l

False

>>> 12 in l

True

>>> t[0] = 25

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item

assignment

>>> l[0] = 25

>>> print(l)

[25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,

15, 16, 17, 18, 19]


156

>>> [Link](50)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: 'tuple' object has no attribute

'append'

>>> [Link](120)

>>> print(l

l lambda

len( license( list( locals(

>>> print(l)

[25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,

15, 16, 17, 18, 19, 120]

>>> [Link]()

Traceback (most recent call last):

File "<stdin>", line 1, in <module>


157

TypeError: count() takes exactly one argument (0

given)

>>> [Link](5)

>>> [Link](25)

>>> [Link](25)

>>> [Link](10)

10

>>> [Link](10)

10

>>> [Link](range(25))

>>> for i in l:print(i)

...

25

1
158

10

11

12

13

14

15

16

17
159

18

19

120

25

10

11
160

12

13

14

15

16

17

18

19

20

21

22

23

24

>>> [Link](0, 4656)

>>> l[0]

4656
161

>>> [Link](12, 147)

>>> [Link](12)

14

>>> l[12]

147

>>> [Link](12)

>>> l[12]

147

>>> print(l)

[4656, 25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 147, 11,

13, 14, 15, 16, 17, 18, 19, 120, 25, 0, 1, 2, 3, 4,

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,

19, 20, 21, 22, 23, 24]

>>> [Link](12)

>>> print(l)
162

[4656, 25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 147, 11,

13, 14, 15, 16, 17, 18, 19, 120, 25, 0, 1, 2, 3, 4,

5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19,

20, 21, 22, 23, 24]

>>> [Link](0)

4656

>>> print(l)

[25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 147, 11, 13,

14, 15, 16, 17, 18, 19, 120, 25, 0, 1, 2, 3, 4, 5,

6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20,

21, 22, 23, 24]

>>> [Link]()

24

>>> print(l)

[25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 147, 11, 13,

14, 15, 16, 17, 18, 19, 120, 25, 0, 1, 2, 3, 4, 5,


163

6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20,

21, 22, 23]

>>>

Code block

18.2 - Operating on Dictionary Object

Code block

root@kali:~# python3

Python 3.4.4 (default, Jan 5 2016, [Link])

[GCC 5.3.1 20160101] on linux

Type "help", "copyright", "credits" or "license"

for more information.

>>> x = {'one':1, 'two':2, 'three':3}

>>> type(x)

<class 'dict'>

>>> y = dict(four = 4, five = 5, six = 6)


164

>>> type(y)

<class 'dict'>

>>> z = dict(seven = 7, eight = 8, nine = 9, **x,

**y)

File "<stdin>", line 1

z = dict(seven = 7, eight = 8, nine = 9, **x,

**y)

SyntaxError: invalid syntax

>>> z = dict(seven = 7, eight = 8, nine = 9, **x)

>>> type(z)

<class 'dict'>

>>> print(z)

{'eight': 8, 'two': 2, 'nine': 9, 'one': 1,

'seven': 7, 'three': 3}

>>> for i in z:print(i)


165

...

eight

two

nine

one

seven

three

>>> for key, value in [Link]():print(key, value)

...

eight 8

two 2

nine 9

one 1

seven 7

three 3

>>> for key, value in [Link]():


166

... if key == two:

... print(value)

...

Traceback (most recent call last):

File "<stdin>", line 2, in <module>

NameError: name 'two' is not defined

>>> [Link]()

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: pop expected at least 1 arguments, got 0

>>> [Link](three)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'three' is not defined

>>> [Link]('three')

3
167

>>> for i in z:print(i)

...

eight

two

nine

one

seven

>>> for key, value in [Link]():

... if key == 'nine':

... print(value)

...

>>>

Code block

Chapter 19. – Database


168

19.1 - Let us start with SQLite3

Code block

#!/usr/bin/python3

import sqlite3

def main():

db = [Link]('[Link]')

db.row_factory = [Link]

[Link]('drop table if exists test1')

[Link]('create table test1 (t1 text, i1

int)')

[Link]('insert into test1 (t1, i1) values

(?, ?)', ('Babu', 1))

[Link]('insert into test1 (t1, i1) values

(?, ?)', ('Mana', 2))

[Link]('insert into test1 (t1, i1) values

(?, ?)', ('Bappa', 3))


169

[Link]('insert into test1 (t1, i1) values

(?, ?)', ('Babua', 4))

[Link]('insert into test1 (t1, i1) values

(?, ?)', ('Anju', 5))

[Link]('insert into test1 (t1, i1) values

(?, ?)', ('Patai', 6))

[Link]('insert into test1 (t1, i1) values

(?, ?)', ('GasaBuddhu', 7))

[Link]('insert into test1 (t1, i1) values

(?, ?)', ('Tapas', 8))

[Link]()

DatabaseRead = [Link]('select * from test

order by i1')

for row in DatabaseRead:

# print(dict(row))

print(row['t1'])

# print(row['t1'], row['i1'])
170

# print(type(row))

if __name__ == "__main__":main()

Code block

19.2 – MySQL for Big Project

Code block

#!/usr/bin/python3

import [Link]

from [Link] 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

###
171

kwargs = dict(host = 'localhost', database

= 'python_mysql', user = 'root', password = 'pass')

conn = [Link](**kwargs)

### connecting directly ###

connection = [Link](host =

'localhost',

databa

se = 'python_mysql',

user =

'root',

passwo

rd = 'pass')

if conn.is_connected():

print("Connected from 'conn' object")

except Error as e:

print(e)

finally:
172

[Link]()

if __name__ == "__main__":

ConnectionTest()

Code block

Code block

#!/usr/bin/python3

import [Link]

from [Link] import Error

def RetrieveValues():

try:

kwargs = dict(host = 'localhost', database

= 'python_mysql', user = 'root', password = 'pass')

conn = [Link](**kwargs)

### shows you how to query data from a MySQL

database in Python by using MySQL Connector/Python


173

API

# such as fetchone() , fetchmany() , and

fetchall() ###

if conn.is_connected():

cursors = [Link]()

[Link]('SELECT * FROM

authors')

# row = [Link]()

# output (1, 'Bel and the Dragon ',

'123828863494')

######

# now we try to get all the books

# row = [Link]()

# print(type(row))

# output <class 'list'>, so we can use

for loop
174

# for books in row:

# print(books)

# it will give us list of all the books

######

### now we give the size of how many

books we want to get ###

# HowManyBooks = 8

# row = [Link](HowManyBooks)

# for books in row:

# print(books)

# we get the output of 8 books

row = [Link]()

for books in row:

print(books)

except Error as e:

print(e)
175

finally: [Link]()

if __name__ == "__main__":

RetrieveValues()

Code block

Code block

[mysql]

host = localhost

database = YourDatabaseName

user = root

password = pass

Code block

Code block

#!/usr/bin/python3

from configparser import ConfigParser


176

def ReadingMySQLConfig(filemame =

'mysql_config.ini', section = 'mysql'):

parser = ConfigParser()

[Link](filemame)

db = dict()

if parser.has_section(section):

items = [Link](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 block

Code block
177

#!/usr/bin/python3

from [Link] 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:

[Link]()

if __name__ == "__main__":

Connect()
178

Code block

Code block

#!/usr/bin/python3

# -*- coding: utf-8 -*-

import [Link]

from [Link] import Error

def connect():

""" Connect to MySQL database """

try:

conn =

[Link](host='localhost',

database='Yo

urDatabase',

user='root',

password='Yo
179

urPassword')

if conn.is_connected():

print('Connected to MySQL database')

except Error as e:

print(e)

finally:

[Link]()

if __name__ == '__main__':

connect()

Code block

Code block

#!/usr/bin/python3

from [Link] import MySQLConnection, Error

from Databases.python_mysql_dbconfig import

read_db_config
180

def iter_row(cursor, size=10):

while True:

rows = [Link](size)

if not rows:

break

for row in rows:

yield row

def query_with_fetchmany():

try:

dbconfig = read_db_config()

conn = MySQLConnection(**dbconfig)

cursor = [Link]()

[Link]("SELECT * FROM EMPLOYEE")

# EMPLOYEE is the table name

for row in iter_row(cursor, 10):

print(row)
181

except Error as e:

print(e)

finally:

[Link]()

[Link]()

if __name__ == '__main__':

query_with_fetchmany()

Code block

Code block

#!/usr/bin/python3

from [Link] import MySQLConnection, Error

from Databases.python_mysql_dbconfig import

read_db_config

def query_with_fetchall():

try:
182

dbconfig = read_db_config()

conn = MySQLConnection(**dbconfig)

cursor = [Link]()

[Link]("SELECT * FROM EMPLOYEE")

rows = [Link]()

print('Total Row(s):', [Link])

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:

[Link]()
183

[Link]()

if __name__ == '__main__':

query_with_fetchall()

Code block

Code block

#!/usr/bin/python3

from [Link] import MySQLConnection, Error

from MySQL_Connector.mysql_config import

ReadingMySQLConfig

def InsertBooks(books):

query = "INSERT INTO books(title, isbn)

VALUES(%s, %s)"

try:

kwargs = ReadingMySQLConfig()

MyConnection = MySQLConnection(**kwargs)
184

if MyConnection.is_connected():

cursor = [Link]()

[Link](query, books)

[Link]()

except Error as e:

print(e)

finally:

[Link]()

def main():

books = [("TestBook", 1236547890)]

InsertBooks(books)

print("Inserted one book")

if __name__ == "__main__":

main()

Code block
185

Code block

#!/usr/bin/python3

from [Link] import MySQLConnection, Error

from MySQL_Connector.mysql_config import

ReadingMySQLConfig

def UpdateBooks(book_id, title):

kwargs = ReadingMySQLConfig()

data = (title, book_id)

query = "UPDATE books SET title = %s WHERE id =

%s"

try:

MyConnection = MySQLConnection(**kwargs)

cursor = [Link]()

[Link](query, data)

[Link]()

except Error as e:
186

print(e)

finally:

[Link]()

def main():

for id in range(1, 25):

if id == 3:

UpdateBooks(id, "I Have A Dream")

print("One book has been updated")

elif id == 4:

UpdateBooks(id, "Laravel 5 Unfolded")

print("One book has been updated")

elif id == 5:

UpdateBooks(id, "Play With Python")

print("One book has been updated")

if __name__ == "__main__":

main()
187

Code block

Code block

#!/usr/bin/python3

from [Link] import MySQLConnection, Error

from MySQL_Connector.mysql_config import

ReadingMySQLConfig

def DeleteBooks(book_id):

kwargs = ReadingMySQLConfig()

query = "DELETE FROM books WHERE id = %s"

try:

MyConnection = MySQLConnection(**kwargs)

cursor = [Link]()

[Link](query, (book_id,))

[Link]()

except Error as e:
188

print(e)

finally:

[Link]()

def main():

id = 87

DeleteBooks(id)

print("Deleted ", id, "number of book from

books")

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

from [Link] import MySQLConnection, Error

from MySQL_Connector.mysql_config import


189

ReadingMySQLConfig

def ReadFile(filename):

with open(filename, 'rb') as f:

images = [Link]()

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 = [Link]()

[Link](query, args)

[Link]()
190

except Error as e:

print(e)

finally:

[Link]()

def main():

id = 47

UpdateImage(id, "/home/hagudu/Pictures/[Link]")

print("Image of author ID", id, "has been

updated.")

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

from [Link] import MySQLConnection, Error


191

from MySQL_Connector.mysql_config import

ReadingMySQLConfig

def WriteFile(data, filename):

with open(filename, 'wb') as files:

[Link](data)

def ReadImage(author_id, filename):

kwargs = ReadingMySQLConfig()

query = 'SELECT photo FROM authors WHERE id =

%s'

try:

MyConnection = MySQLConnection(**kwargs)

cursor = [Link]()

[Link](query, (author_id,))

photo = [Link]()[0]

WriteFile(photo, filename)

except Error as e:
192

print(e)

finally:

[Link]()

def main():

id = 47

ReadImage(id, "/home/hagudu/Pictures/[Link]")

if __name__ == "__main__":

main()

Code block

Chapter 20. - Module

Code block

#!/usr/bin/python3

import sys, os, [Link]


193

def main():

print("This is Python Version : {}.{}.

{}".format(*sys.version_info))

# os module

print([Link])

print([Link]('PATH'))

print([Link]())

#urllib module

page =

[Link]('[Link]

for line in page:

print(str(line, encoding='utf-8'), end='')

if __name__ == "__main__":

main()

Code block
194

Code block

#!/usr/bin/python3

import sys, os, [Link], random, datetime

def main():

print("This is Python Version : {}.{}.

{}".format(*sys.version_info))

# random module

print([Link](1, 1000))

x = list(range(25))

print(x)

[Link](x)

print(x)

[Link](x)

print(x)
195

[Link](x)

print(x)

PresentTime = [Link]()

print(PresentTime)

print([Link], [Link],

[Link], [Link],

[Link], [Link],

[Link])

if __name__ == "__main__":

main()

Code block

Chapter 21. – Debugging, UnitTest

Module

Code block
196

#!/usr/bin/python3

# coding=utf-8

import sys, datetime

def PyVer():

print("This is Python Version : {}.{}.

{}".format(*sys.version_info))

def PyTime():

PresentTime = [Link]()

print(PresentTime)

print([Link], [Link],

[Link], [Link],

[Link],

[Link],

[Link])

#print(obj)

def main():
197

PyVer()

PyTime()

def test_Pyvar():

PyVer()

def test_Main():

PyTime()

if __name__ == "__main__":

main()

Code block

Code block

#!/usr/bin/python3

# coding=utf-8

import [Link]

import unittest

class SayTiemDate([Link]):

def setUP(self):
198

pass

def test_Version(self):

[Link]([Link]

.PyVer(),

[Link].test_Pyvar())

def test_Time(self):

[Link]([Link]

.main(),

[Link].test_Main())

if __name__ == "__main__":

[Link]()

Code block

Chapter 22. – Socket and Networking


199

Code block

# coding=utf-8

import socket

print([Link]("[Link].

com"))

print([Link]("[Link]

[Link]"))

Code block

Chapter 23 – Importing Nmap Module

Code block

nmap

Nmap 6.40 ( [Link] )


200

Usage: nmap [Scan Type(s)] [Options] {target

specification}

TARGET SPECIFICATION:

Can pass hostnames, IP addresses, networks, etc.

Ex: [Link], [Link]/24,

[Link]; 10.0.0-255.1-254

-iL <inputfilename>: Input from list of

hosts/networks

-iR <num hosts>: Choose random targets

--exclude <host1[,host2][,host3],...>: Exclude

hosts/networks

--excludefile <exclude_file>: Exclude list from

file

HOST DISCOVERY:

-sL: List Scan - simply list targets to scan

-sn: Ping Scan - disable port scan


201

-Pn: Treat all hosts as online -- skip host

discovery

-PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP

discovery to given ports

-PE/PP/PM: ICMP echo, timestamp, and netmask

request discovery probes

-PO[protocol list]: IP Protocol Ping

-n/-R: Never do DNS resolution/Always resolve

[default: sometimes]

--dns-servers <serv1[,serv2],...>: Specify custom

DNS servers

--system-dns: Use OS's DNS resolver

--traceroute: Trace hop path to each host

SCAN TECHNIQUES:

-sS/sT/sA/sW/sM: TCP

SYN/Connect()/ACK/Window/Maimon scans

-sU: UDP Scan


202

-sN/sF/sX: TCP Null, FIN, and Xmas scans

--scanflags <flags>: Customize TCP scan flags

-sI <zombie host[:probeport]>: Idle scan

-sY/sZ: SCTP INIT/COOKIE-ECHO scans

-sO: IP protocol scan

-b <FTP relay host>: FTP bounce scan

PORT SPECIFICATION AND SCAN ORDER:

-p <port ranges>: Only scan specified ports

Ex: -p22; -p1-65535; -p U:53,111,137,T:21-

25,80,139,8080,S:9

-F: Fast mode - Scan fewer ports than the default

scan

-r: Scan ports consecutively - don't randomize

--top-ports <number>: Scan <number> most common

ports
203

--port-ratio <ratio>: Scan ports more common than

<ratio>

SERVICE/VERSION DETECTION:

-sV: Probe open ports to determine

service/version info

--version-intensity <level>: Set from 0 (light)

to 9 (try all probes)

--version-light: Limit to most likely probes

(intensity 2)

--version-all: Try every single probe (intensity

9)

--version-trace: Show detailed version scan

activity (for debugging)

SCRIPT SCAN:

-sC: equivalent to --script=default

--script=<Lua scripts>: <Lua scripts> is a comma

separated list of
204

directories, script-files or script-

categories

--script-args=<n1=v1,[n2=v2,...]>: provide

arguments to scripts

--script-args-file=filename: provide NSE script

args in a file

--script-trace: Show all data sent and received

--script-updatedb: Update the script database.

--script-help=<Lua scripts>: Show help about

scripts.

<Lua scripts> is a comma separted list

of script-files or

script-categories.

OS DETECTION:

-O: Enable OS detection

--osscan-limit: Limit OS detection to promising

targets
205

--osscan-guess: Guess OS more aggressively

TIMING AND PERFORMANCE:

Options which take <time> are in seconds, or

append 'ms' (milliseconds),

's' (seconds), 'm' (minutes), or 'h' (hours) to

the value (e.g. 30m).

-T<0-5>: Set timing template (higher is faster)

--min-hostgroup/max-hostgroup <size>: Parallel

host scan group sizes

--min-parallelism/max-parallelism <numprobes>:

Probe parallelization

--min-rtt-timeout/max-rtt-timeout/initial-rtt-

timeout <time>: Specifies

probe round trip time.

--max-retries <tries>: Caps number of port scan

probe retransmissions.
206

--host-timeout <time>: Give up on target after

this long

--scan-delay/--max-scan-delay <time>: Adjust

delay between probes

--min-rate <number>: Send packets no slower than

<number> per second

--max-rate <number>: Send packets no faster than

<number> per second

FIREWALL/IDS EVASION AND SPOOFING:

-f; --mtu <val>: fragment packets (optionally

w/given MTU)

-D <decoy1,decoy2[,ME],...>: Cloak a scan with

decoys

-S <IP_Address>: Spoof source address

-e <iface>: Use specified interface

-g/--source-port <portnum>: Use given port number


207

--data-length <num>: Append random data to sent

packets

--ip-options <options>: Send packets with

specified ip options

--ttl <val>: Set IP time-to-live field

--spoof-mac <mac address/prefix/vendor name>:

Spoof your MAC address

--badsum: Send packets with a bogus TCP/UDP/SCTP

checksum

OUTPUT:

-oN/-oX/-oS/-oG <file>: Output scan in normal,

XML, s|<rIpt kIddi3,

and Grepable format, respectively, to the

given filename.

-oA <basename>: Output in the three major formats

at once
208

-v: Increase verbosity level (use -vv or more for

greater effect)

-d: Increase debugging level (use -dd or more for

greater effect)

--reason: Display the reason a port is in a

particular state

--open: Only show open (or possibly open) ports

--packet-trace: Show all packets sent and

received

--iflist: Print host interfaces and routes (for

debugging)

--log-errors: Log errors/warnings to the normal-

format output file

--append-output: Append to rather than clobber

specified output files

--resume <filename>: Resume an aborted scan


209

--stylesheet <path/URL>: XSL stylesheet to

transform XML output to HTML

--webxml: Reference stylesheet from [Link] for

more portable XML

--no-stylesheet: Prevent associating of XSL

stylesheet w/XML output

MISC:

-6: Enable IPv6 scanning

-A: Enable OS detection, version detection,

script scanning, and traceroute

--datadir <dirname>: Specify custom Nmap data

file location

--send-eth/--send-ip: Send using raw ethernet

frames or IP packets

--privileged: Assume that the user is fully

privileged
210

--unprivileged: Assume the user lacks raw socket

privileges

-V: Print version number

-h: Print this help summary page.

EXAMPLES:

nmap -v -A [Link]

nmap -v -sn [Link]/16 [Link]/8

nmap -v -iR 10000 -Pn -p 80

SEE THE MAN PAGE ([Link]

FOR MORE OPTIONS AND EXAMPLES

Code block

sudo apt-get install nmap


211

sudo nano [Link]

#!/usr/bin/python

import nmap

nm = [Link]()

def callback_result(host, scan_result):

print ('------------------')

print (host, scan_result)

[Link]('[Link]', arguments="-O -v",

callback=callback_result)

while nm.still_scanning():

print("Waiting >>>")

[Link](2)

nm1 = [Link]()

a = nm1.nmap_version()
212

print (a)

Waiting >>>

------------------

('[Link]', None)

(6, 40)

It’s your localhost address. But we are interested

about the remote target.

[Link]

ISP: Some Internet LTD

Chapter 24 – Building an Nmap

Network Scanner
213

Code block

#!/usr/bin/python

import nmap

nm = [Link]()

print (nm.nmap_version())

[Link]('[Link]', '1-1024', '-v')

print([Link]())

print([Link]())

Code block

hagudu@hagudu-H81M-S1:~$ ./[Link]

(6, 40)

{'tcp': {'services': '1-1024', 'method':

'connect'}}
214

host;hostname;hostname_type;protocol;port;name;stat

e;product;extrainfo;reason;version;conf;cpe

[Link];host3.x0x;PTR;tcp;22;ssh;open;;;syn-

ack;;3;

[Link];host3.x0x;PTR;tcp;25;smtp;open;;;syn-

ack;;3;

[Link];host3.x0x;PTR;tcp;53;domain;open;;;syn-

ack;;3;

[Link];host3.x0x;PTR;tcp;80;http;open;;;syn-

ack;;3;

[Link];host3.x0x;PTR;tcp;137;netbios-

ns;filtered;;;no-response;;3;

[Link];host3.x0x;PTR;tcp;138;netbios-

dgm;filtered;;;no-response;;3;

[Link];host3.x0x;PTR;tcp;139;netbios-

ssn;filtered;;;no-response;;3;
215

[Link];host3.x0x;PTR;tcp;445;microsoft-

ds;filtered;;;no-response;;3;

Code block

#!/usr/bin/python

import nmap

nm = [Link]()

print (nm.nmap_version())

[Link]('[Link]', '1-1024', '-v')

print([Link]())

print([Link]())

(6, 40)

{'tcp': {'services': '1-1024', 'method':

'connect'}}
216

host;hostname;hostname_type;protocol;port;name;stat

e;product;extrainfo;reason;version;conf;cpe

[Link];;;tcp;25;smtp;open;;;syn-ack;;3;

[Link];;;tcp;53;domain;open;;;syn-ack;;3;

[Link];;;tcp;80;http;open;;;syn-ack;;3;

Code block

#!/usr/bin/python

import nmap

nm = [Link]()

print (nm.nmap_version())

[Link]('[Link]', '22-455', '-v --version-

all')

print(nm.all_hosts())
217

(6, 40)

{'tcp': {'services': '22-455', 'method':

'connect'}}

['[Link]']

#!/usr/bin/python

import nmap

nm = [Link]()

print (nm.nmap_version())

[Link]('[Link]', '22-455', '-v --version-all')

print(nm.all_hosts())

Code block
218

#!/usr/bin/python

import nmap

nm = [Link]()

print (nm.nmap_version())

[Link]('[Link]', '22-1024', '-v --version-

all')

print ([Link]())

print (nm['[Link]'].state())

print (nm['[Link]'].all_protocols())

print (nm['[Link]']['tcp'].keys())

(6, 40)

{'uphosts': '1', 'timestr': 'Mon Oct 3 [Link]

2016', 'downhosts': '0', 'totalhosts': '1',

'elapsed': '5.73'}
219

up

['tcp']

[80, 25, 53]

[Link];host3.x0x;PTR;tcp;22;ssh;open;;;syn-

ack;;3;

[Link];host3.x0x;PTR;tcp;25;smtp;open;;;syn-

ack;;3;

[Link];host3.x0x;PTR;tcp;53;domain;open;;;syn-

ack;;3;

[Link];host3.x0x;PTR;tcp;80;http;open;;;syn-

ack;;3;

[Link];host3.x0x;PTR;tcp;137;netbios-

ns;filtered;;;no-response;;3;

[Link];host3.x0x;PTR;tcp;138;netbios-

dgm;filtered;;;no-response;;3;
220

[Link];host3.x0x;PTR;tcp;139;netbios-

ssn;filtered;;;no-response;;3;

[Link];host3.x0x;PTR;tcp;445;microsoft-

ds;filtered;;;no-response;;3;

PART THREE

Chapter 27. - Proxy Chains

Code block

root@kali:~# nano /etc/[Link]

Code block

Code block

service tor start

Code block
221

Chapter 28. - Virtual Private

Network or VPN

Code block

cat /etc/[Link]

Code block

Code block

nano /etc/dhcp/[Link]

Code block

Code block

service network-manager restart

Code block
222

Code block

sanjib@kali:~$ cd Downloads/

sanjib@kali:~/Downloads$ ls

[Link]

[Link]

[Link]

[Link]

Code block

Code block

openvpn [Link]

Code block

Chapter 29. - MAC Address


223

Code block

ipconfig

Code block

Code block

root@kali:~# macchanger -s eth0

Current MAC: [Link] (CADMUS COMPUTER

SYSTEMS)

Permanent MAC: [Link] (CADMUS COMPUTER

SYSTEMS)

Code block

Code block

root@kali:~# macchanger –h

Code block

You might also like