├── README.md ├── python └── python_cheatsheet.md ├── mininet_cheatsheet.md └── flask_cheatsheet.md /README.md: -------------------------------------------------------------------------------- 1 | #Cheatsheet of my tools 2 | 3 | - [Flask](flask_cheatsheet.md) 4 | - [Python](python_cheatsheet.md) 5 | - [Mininet](mininet_cheatsheet.md) 6 | 7 | -------------------------------------------------------------------------------- /python/python_cheatsheet.md: -------------------------------------------------------------------------------- 1 | #Python Cheatsheet 2 | 3 | ##Installing python 4 | Linux comes with pre-installed python interpreter, no need to install, and default interpreter is python 2.7 in most of the 5 | linux distribution 6 | 7 | ```bash 8 | $ python #This will open python 2.7 interpreter 9 | ``` 10 | 11 | ```bash 12 | $ python3 #This will open python3 interpreter 13 | ``` 14 | > I recommend to use python3 as the community is much more focused on creating new libraries for python3, python2 has a supports 15 | only bux fixes and security patches. 16 | 17 | > This cheatsheet is much more focused on python3 18 | 19 | ```python 20 | from __future__ import python 21 | 3 / 2 equals to 1.5 22 | 3.0 / 2 equals 1.5 23 | 24 | $ python -Qnew 25 | >>> 3 / 2 => 1.5 26 | 27 | ##Difference between expression and statement 28 | 29 | 30 | ##Some important built in functions 31 | 32 | ```python 33 | abs(-10) 34 | round(12.3) => round to the nearest value 35 | round(12.5) => 13.0 36 | import math 37 | math.floor(33.9) => 33.0 38 | math.ceil(33.2) => 34.0 39 | math.sqrt(9) => 3.0 40 | ``` 41 | 42 | ##Some shortcuts methods in python 43 | 44 | ```python 45 | foo = math.sqrt 46 | foot(3) 47 | ``` 48 | 49 | ##importing the standard library 50 | 51 | ```python 52 | from math import floor 53 | from math import ceil as c 54 | from math import sqrt 55 | 56 | >>> sqrt(-1) # It will throw the ValueError, in some platfrom it show nan ie. not a number 57 | >>> c(33.2) # 34.0 58 | ``` 59 | 60 | ```python 61 | from math import floor 62 | f = floor 63 | f(33.9) #32 64 | ``` 65 | 66 | ##Cmath module 67 | 68 | ```python 69 | from cmath import sqrt 70 | sqrt(-1) #1j 71 | >>> (1 + 2j) * (1 - 3j) 72 | ``` 73 | 74 | > note: There are no seperate imaginary in python, they are treated as a complex number whose real component is zero 75 | 76 | ##Diffrence between repr and str 77 | ```python 78 | print(str("hello world")) 79 | print (repr("hello world")) 80 | ``` 81 | 82 | STR and REPR is used to print the values, the main difference is repr disply the value as a legal python expression. 83 | ```python 84 | x = 2 85 | repr(x) == `x` 86 | ``` 87 | ```python 88 | >>> print(" The value of x is " + str(x)) 89 | >>> print("The value of x is " + repr(x)) 90 | >>> print "The value of x is" + `x` 91 | ``` 92 | 93 | The statement 1 and 2 are same 94 | The backticks are removed in python 3 so used repr(x) method. 95 | 96 | -------------------------------------------------------------------------------- /mininet_cheatsheet.md: -------------------------------------------------------------------------------- 1 | #Mininet installation testing 2 | 3 | ```bash 4 | $ sudo mn --test pingall 5 | $ sudo mn --test pingpair 6 | ``` 7 | for the documentation help 8 | 9 | ```bash 10 | mn --help 11 | ``` 12 | 13 | ##some basic commands in mininet 14 | 15 | ```bash 16 | 17 | mn> help #Display some help commands 18 | mn> nodes #Display all the nodes controller, switch and hosts of the topology 19 | mn> h2 ping h1 #Ping h1 form h2 20 | mn> h2 ifconfig #Display the ip configuration of h2 host with h2-eth0 21 | mn> xterm h2 #Connect to the terminal of h2 host, where we can run all the commands 22 | mn> dump #Display all the information about the nodes 23 | mn> s1 ifconfig #This will display all the physical interface of host as well as the logical interface of the switch 24 | mn> s1 ping 8.8.8.8 #This will ping the Google public dns from the switch 25 | mn> c0 ping -c 2 8.8.4.4 26 | mn> pingall #This will ping two nodes in topology h1 and h2 27 | mn> net #Show the links connection. 28 | ``` 29 | 30 | In mininet switch by default run as the root namespace, so it can has access to all the network interface of the physical host system. 31 | 32 | In mininet it is possible to place all the hosts, switch, controller into their own namespace, using the flag `--innamespace` option. 33 | 34 | In mininet the network is only virtualize, all the nodes in the mininet network share the same process, this can be verify using ps the commands on all nodes 35 | ```bash 36 | mn> h1 ps -a 37 | mn> h2 ps -a 38 | mn> c0 ps -a 39 | mn> s1 ps -a 40 | ``` 41 | On running the above command, the output will be the same, even on listing the files on each nodes will result in same info. 42 | 43 | The real advantage of using mininet comes, each host on mininet can run any linux command that support by your hosts on which mininet is running. we can also run webserver in hosts. 44 | 45 | Let us run simple web server in host h2 inside mininet topology. 46 | 47 | ```bash 48 | $ h1 python -m SimpleHTTPServer 999 & 49 | ``` 50 | 51 | The above command will run the simple HTTP webserver available in our linux system to the host h1, you can get the ip address of the host h1 by running the command `dump` 52 | To connect to the webserver running in host 53 | 54 | ```bash 55 | $ h1 wget 10.0.0.1:999 -O data 56 | ``` 57 | 58 | If mininet crashes some reason, we need to clean up 59 | 60 | ```bash 61 | mn> exit 62 | $ sudo mn -c 63 | ``` 64 | 65 | ```bash 66 | sudo mn --test pingpair 67 | ``` 68 | The above test is called the regression test in mininet. 69 | 70 | ```bash 71 | $ sudo mn --test iperf 72 | ``` 73 | The above command create the same minimalist topology and run the iperf server on h1 and run iperf 74 | 75 | Ok, let us write some python code 76 | 77 | ```python 78 | from mininet.net import Mininet 79 | from mininet.topolib import TreeTopo 80 | 81 | tree4 = TreeTopo(depth=2, fanout=2) 82 | netwok = Mininet(topo=tree4) 83 | netwok.start() 84 | h1, h4 = netwok.hosts[0], network.hosts[3] 85 | print h1.cmd("pinging h1 from h4 %s" %h4.IP()) 86 | network.stop() 87 | ``` 88 | 89 | save the above code and run this as `python `. This method is to creating the topology from python file 90 | 91 | Ok, new let us create the topology from command line 92 | ```python 93 | $ sudo mn --topo linear,3 94 | 95 | ``` 96 | 97 | This above command will create the linear topology, 3 switches are connected with each other having single host. 98 | 99 | ```python 100 | $sudo mn --topo single,3 101 | ``` 102 | The above command will create a single switch with 3 hosts connected to the switch 103 | 104 | ##Setting up the link parameters in mininet. 105 | ```python 106 | $sudo mn --link tc,bw=10,delay=10ms 107 | 108 | ``` 109 | 110 | ##Vebosity in mininet for inspecting 111 | 112 | ```python 113 | 114 | $ sudo mn -v debug 115 | $ sudo mn -v output 116 | ``` 117 | 118 | ```bash 119 | $ tcpdump -n #Don't do the name resolution. 120 | 121 | ```bash 122 | mn> iperf 123 | ``` 124 | 125 | ```bash 126 | mn > iperfudp 127 | ``` 128 | 129 | ##Creating the customs topology in mininet. 130 | 131 | ```python 132 | 133 | """Custom topology example 134 | 135 | Two directly connected switches plus a host for each switch: 136 | 137 | host --- switch --- switch --- host 138 | 139 | Adding the 'topos' dict with a key/value pair to generate our newly defined 140 | topology enables one to pass in '--topo=mytopo' from the command line. 141 | """ 142 | 143 | from mininet.topo import Topo 144 | 145 | class MyTopo( Topo ): 146 | "Simple topology example." 147 | 148 | def __init__( self ): 149 | "Create custom topo." 150 | 151 | # Initialize topology 152 | Topo.__init__( self ) 153 | 154 | # Add hosts and switches 155 | leftHost = self.addHost( 'h1' ) 156 | rightHost = self.addHost( 'h2' ) 157 | leftSwitch = self.addSwitch( 's3' ) 158 | rightSwitch = self.addSwitch( 's4' ) 159 | 160 | # Add links 161 | self.addLink( leftHost, leftSwitch ) 162 | self.addLink( leftSwitch, rightSwitch ) 163 | self.addLink( rightSwitch, rightHost ) 164 | 165 | 166 | topos = { 'mytopo': ( lambda: MyTopo() ) } 167 | 168 | ``` 169 | 170 | By default, the hosts start with randomly assigned mac address, this make debugging tough. to set the mac address small and unique, mininet provide the special options 171 | 172 | ```bash 173 | sudo mn --mac 174 | ``` 175 | 176 | To open all the xterm windo for all nodes, just pass the -x flag to mn command as shown below 177 | 178 | ```bash 179 | $ sudo mn -x 180 | ``` 181 | 182 | To view the flow entries in the switch, we can use the dpctl commands in the xterm windows of the switches 183 | 184 | ```bash 185 | switch$ dpctl dump-flows tcp:127.0.0.1:6634 186 | ``` 187 | 188 | `dpctl` is the command line utility to get the information about the switch. we can query about other options that dpctl take using 189 | ```bash 190 | mn> dpctl --help 191 | ``` 192 | 193 | To check the time that take to setup and teardown the mininet topology is called mininet benchmarking, which can be done by using `test none` command 194 | 195 | ```bash 196 | $ sudo mn --test none 197 | ``` 198 | 199 | ###Namespace in Mininet 200 | By default in mininet `switch` and `Controller` are placed into the root name space, while hosts are kept into their own namespace. 201 | To change the namespace we can use the options --innamespace 202 | 203 | ```bash 204 | $ sudo mn --innamespace --switch user 205 | ``` 206 | 207 | ###Mininet CLI 208 | ####Running Python interpeter in mininet 209 | 210 | ```python 211 | $ sudo many 212 | mn> py 'hello' + 'world' 213 | mn> py h1.IP() 214 | mn> py locals #Print the local variables. 215 | ``` 216 | 217 | 218 | ##Link Managing in mininet. 219 | ###Link up and down 220 | 221 | ```bash 222 | mn> link s1 h1 down 223 | mn> h1 ping h2 #This won't ping h2 as the link from h1 to h2 is down. 224 | mn> link h1 s1 up #This command will bring the link up. 225 | mn> xterm h1 h2 #This will open the xterm of two host h1 and h2, 226 | ``` 227 | 228 | ##Using Remote Controller in Mininet. 229 | This will be useful if we are running the the controller in the remote machines, having customs controller, which can be floodlight, Opendaylight, Pox, Beacon, Ryu and many other controller of your choice. 230 | 231 | #Terms 232 | - **Table miss** 233 | - **Packet In ** Message send by the switch to the controller 234 | 235 | 236 | - ** Flow table ** 237 | 238 | - ** Packet out message ** This message tell the switch what to do with this packet. 239 | 240 | - ** flow modification message ** 241 | It instruct the switch to enter new entry flow table in the switch 242 | - **Flow entry** 243 | have match fields to match the incomming packets, 244 | and also have further instruction. 245 | flow intery given by the controller. 246 | flow entry have the priority, 247 | 248 | - ** Flow table ** 249 | 250 | - ** Group table ** 251 | special kind of flow table, consisit of the identifier and action buckets. 252 | Action Bucket --send out ALL Ports 2,3,4,5 253 | 254 | - ** Openflow channel ** 255 | To connect for one or more controller. 256 | it communication setup, perodic health checking and many other. -------------------------------------------------------------------------------- /flask_cheatsheet.md: -------------------------------------------------------------------------------- 1 | #Working with Flask 2 | 3 | ```python 4 | virtualenv flasky 5 | $ source bin activate 6 | (flasky)$ pip install flask 7 | ``` 8 | 9 | ##Basic Flask application Structure 10 | 11 | All flask application needs to create a *application instance*, 12 | The web server pass all the request it get pass to this application object using a protocol called WSGI 13 | The application instance is an object of class **Flask** , the application object is created using the following code 14 | 15 | ```python 16 | from flask import Flask 17 | app = Flask(__name__) 18 | ``` 19 | 20 | The only required parameter to the Flask class is the name of the module or file which is given by the magic variable name 21 | called **__name__** in python. 22 | 23 | 24 | ##Routes and View Functions 25 | 26 | The association between the url and the functions in flask that handle the request is called the route, 27 | Route mapping is done through the decoraters in python app.route 28 | 29 | ```python 30 | @app.route('/') 31 | def index(): 32 | return '

Hello world

' 33 | ``` 34 | 35 | 36 | > **note:** Decorators are the standard features of the python programming language, they can modify the behaviour of the functions. Here the function like index() are called the **View** functions. 37 | 38 | 39 | we can also create the dynamic url mapping, for instance 40 | 41 | ```python 42 | @app.route('/username/') 43 | def username(name): 44 | return "

welcome to your Dashboard %s

" % name 45 | ``` 46 | 47 | The portion enclosed in the angle bracket is the dynamic part. 48 | The dynamic components are string by defaults in url, but we can also specify the type in the url like the **Integer** type, `/user/`, this url 49 | will be match if the id equals to the integer value, the flask url supports **int float path** 50 | 51 | 52 | ##Starting up a Server 53 | ```python 54 | if __name__ == '__main__': 55 | app.run(debug=True) 56 | ``` 57 | 58 | Once the server startup it goes into the loop and only stop after hitting the control + C keystroke. 59 | 60 | Now we can run our app by invoking our python interpreter as, 61 | `python hello.py` 62 | 63 | ##Application and request Context 64 | 65 | Flask use the **Contexts** to make certain objects globally accessibles, 66 | Context enables flask to make access to the certain threads globally without intefering the other threads 67 | 68 | Multithreaded web server starts with a **pool** of thread and select the thread from the pool to serve the incomming thread. 69 | 70 | ##Context in Flask 71 | There are two context in flask 72 | 73 | - **Application Context** 74 | - **Request Context** 75 | 76 | ##Application Contexts 77 | 78 | variable_name | Description 79 | ------------- |------------- 80 | current_app | The application instance for the running application 81 | get | An object that can be used by the application for the temporary storage 82 | 83 | 84 | ##Request Context 85 | 86 | variable_name | Description 87 | ------------ | ------------ 88 | request | The request object which encapsulate the content carried by the http request 89 | session | It is the dictionary that is used to remember the users session 90 | 91 | Application context are only available when the flask application is running(pushes), at the time 92 | of flask application running, the variables **current_app** and **g** application context are available 93 | 94 | To demonstrate that the application context is only available in the app running, we can run the following commands 95 | 96 | ```python 97 | (flasky)$ python 98 | >>> from hello import app 99 | >>> from flask import current_app 100 | >>> current_app.name 101 | RuntimeError: working outside of application context 102 | ``` 103 | To fix this error we need to run our application, so that we can have access to our application context, 104 | we can push (activate) our app from command line as well. 105 | 106 | ```python 107 | >>>from hello import app 108 | >>>from flask import current_app 109 | >>> app_context = app.app_context() 110 | >>>app_context.push() 111 | >>>current_app.name 112 | 'hello' 113 | >>>app_context.pop() 114 | ``` 115 | The important things to remember is, we can get the our application context by running the app.app_context() method on the 116 | application instance 117 | 118 | 119 | ##Request Dispatching 120 | In the previous example we create our urls and its mapping to the methods using some decoraters and python functions. 121 | To see the maps we can use the url_map method on app 122 | 123 | ```python 124 | >>> from hello import app 125 | >>>app.url_map 126 | ``` 127 | On running this above command, Flask display the following output in our console 128 | ```python 129 | >>> app.url_map 130 | Map([ index>, 131 | ' (HEAD, OPTIONS, GET) -> static>, 132 | ' (HEAD, OPTIONS, GET) -> name>]) 133 | ``` 134 | The **/** and **/user/** are defined in our hello.py file, but **/static/** is the 135 | special route added by the flask to give access to the static route of our application. 136 | 137 | The **HEAD OPTIONS** and **GET** are the request method that are handled by the route, while HEAD and OPTIONS methods are 138 | automatically managed by the route. 139 | 140 | 141 | ##Request Hooks 142 | Sometimes it is useful to execute the code before or after the each request is processed, and these code are implemented 143 | as a function and these functions are called hooks. 144 | 145 | - **before_first_request:** Register a function to run before the first request get handled 146 | - **before_request:** Register a function to run before each request 147 | - **after_request** Register a function to run after each request if no unhandled exceptions occours 148 | - **teardown_request** Register a function to run after a request even if unhandled exceptions occours 149 | 150 | ##Response 151 | When flask invokes a view function through the request object, it expects a response object. when flask response, 152 | by default it return the http response object wit status code, and the default status code will be the 200 153 | if the request get replied successfully as **200** numeric code. 154 | 155 | we can also override the behaviour by appending the numeric code in the return statement as follows in view methods. 156 | 157 | ```python 158 | def index(): 159 | return "

Bad request

", 400 160 | ``` 161 | we can also append the dictionary on the response as a third argument. 162 | Instead of passing each value as a tuple in the return statement, It is benificial to use the response object provided 163 | by the flask calld `make_response`, 164 | 165 | ```python 166 | from flask import make_response 167 | 168 | @app.route('/') 169 | def index(): 170 | response = make_response("

This document carries a cookie") 171 | response.set_cookie('answer', 42) 172 | return response 173 | ``` 174 | 175 | we have also another special type of response called redirect 176 | ```python 177 | @app.route('/') 178 | def index(): 179 | return redirect('http://google.com') 180 | ``` 181 | > Redirect wil be identified by the status code of 302 in http protocol. 182 | 183 | In flask for error handling there a another special type of response called **abort** 184 | ```python 185 | from flask import abort 186 | @app.route(/user/) 187 | def get_user(id): 188 | user = load_user(id) 189 | if not user: 190 | abort(40r) 191 | return "

%s is not a valid user

" %user.name 192 | ``` 193 | 194 | ##Flask Extensions 195 | We can manage our flash application from the command line as well, to set up the configuration options to the 196 | web server we need to pass the options to app.run() instance, as flask is extendable, so, we will **flask-script** 197 | to mange and set the configuration options to our aplication. 198 | 199 | To install flask-script run the following command 200 | ```python 201 | $pip install flask-script 202 | ``` 203 | 204 | To use the installed script we need to insert the following line of code in our **hello.py** application 205 | 206 | ```python 207 | from flask.ext.script import Manager 208 | manager = Manager(app) 209 | ``` 210 | so the final code of **hello.py** looks like this after the extension of flask-script extension 211 | 212 | ```python 213 | from flask import Flask 214 | from flask import request 215 | from flask import redirect 216 | from flask.ext.script import Manager 217 | 218 | app = Flask(__name__) 219 | manager = Manager(app) 220 | 221 | @app.route('/') 222 | def index(): 223 | user_agent = request.headers.get('User-Agent') 224 | return "You are using %s browser" % user_agent 225 | 226 | @app.route('/user/') 227 | def name(name): 228 | return "You said your name is %s" % name 229 | 230 | @app.route('/google') 231 | def google(): 232 | return redirect("http://google.com.np") 233 | 234 | if __name__ == '__main__': 235 | manager.run() 236 | ``` 237 | 238 | so, with the flask-script extension, our **python hello.py** can provides the command line options 239 | ```python 240 | $ python hello.py runserver 241 | $ python hello.py shell 242 | $ python hello.py --help 243 | $ python hello.py runserver --helpm 244 | ``` 245 | 246 | ##App methods and attributes 247 | from flask import Flask 248 | from flask import make_response 249 | from flask import redirect 250 | 251 | response = make_response('

Hello world

') 252 | response.creae_cookie('answer', 42) 253 | 254 | from hello import app 255 | app.url_map 256 | context = app.app_context() 257 | app.add_url_rule() # Non decoraters version for url mapping in flask 258 | 259 | --------------------------------------------------------------------------------