mag72

Python Cheat Sheet

Python Cheat Sheet

Hitesh J

Python is an open-source and versatile programming language used by thousands of web developers, data scientists, and software engineers. It is very trendy because it has extensive support libraries, user-friendly data structures, and a great support community.

This Python cheat sheet can serve as a quick reference for system administrators and network administrators.

We will include all essential categories and items including, network programming libraries, keywords, variables and data types, strings, lists, and more.

Basic Python Libraries for Network Admin

Here is the list of basic Python libraries with a brief explanation.

Name Explanation
PIP Package manager for Python.
pypcap Python interface to pcap a packet capture library.
PyPI Repository of open-source Python packages.
Paramiko It is a Python interface around SSH networking concepts.
EDDIE Tool Python agent used for system and network monitoring, security, and performance analysis.
pycos It provides an Asynchronous Socket class to convert Python's blocking socket to a non-blocking socket.
Diesel Framework to write reliable and scalable network applications in Python.
NAPALM A Python.
Celery It is a task queue implementation for Python web applications to asynchronously execute work outside the HTTP request-response cycle.

Python Keywords

Python has a set of keywords or reserved words used to define the syntax of the coding. You can not use it as an identifier, function, and variable name. Here is a list of some keywords with example usage.

Keyword Explanation Example
False, True Boolean value, result of comparison operations False == (1 > 2), True == (1 < 2)
and, or, not Logical operators x, y = True, False
(x or y) == True # True
(x and y) == False # True
(not y) == True # True
break Ends loop prematurely while(True):
break
print (“Hi How R U?”)
continue Finishes current loop while(True):
continue
print (“200”)
class

def

Defines a new class

Defines a new function

class Bear
def __init__(self):
self.content = 1.0
def drink(self):
self.content = 0.0backs = Bear()
backs.drink()
if, elif, else Used for a conditional program that starts with if, tries the elif, and finishes with else. x = int(input(“type your value: “))
if x > 4: print(“Big”)
elif x == 4: print(“Medium”)
else: print(Small”)
for, while for a in [0,1,2,3]:
print(a)b = 1
while b < 4:
print(b)
b = b + 1
in Checks whether element is in sequence. 30 in [10, 30, 40, 70]     # True
is Checks whether both elements point to the same object. a = b = 5
a is b # True
[5] is [5] # False
None Empty value constant def f():
a = 3
f() in None # True
lamda Function with no name (lamda a: a + 4)(4)      # returns 8
return Terminates execution of the function and passes the flow of performance to the caller. def incrementor(a):
return a + 1
incrementor(3)               # return 4

Data Types

In Python programming, everything is an object. Every value in Python is called an “object,” and every object has a specific data type.

There are various data types in Python. Some of the essential types are listed below.

  • int It is an integer number that representing an object or number such as 3, 4, 5, etc.
  • float It is floating-point numbers that representing floating-point numbers such as 0.5, 1.25, 2.0, etc.
  • Strings A string is a collection of one or more characters put in a single quote, double-quote, or triple quote.
Data Types
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview

Math Operators

Math operators in Python perform mathematical operations like addition, subtraction, multiplication, and division. Here is the list of all math operators with explanations and examples.

Keyword Explanation Example
** Exponent 3 ** 2 = 9
% Modulus/Remainder 22 % 8 = 6
// Integer division 20 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 2 * 3 = 6
Subtraction 8 – 2 = 6
+ Addition 2 + 8 = 10
== Equal to
!= Not equal to
< Less than
> Greater than
>= Greater than or Equal to
<= Less than or Equal to

Network Services in Python

There are two levels of network services in Python.

  • High-level access: This service helps programmers to access the application-level network protocols.
  • Low-level access: This service allows you to access the socket support for the operating systems by using Python libraries. You can use it to implement connection-less and connection-oriented protocols for performing network programming.

There are several methods available that help network administrators manage the connections. Some of them are listed below.

Method Explanation
listen() Used to establish and start TCP listeners.
bind() Used to bind-address to the socket.
connect() Used to make a connection with the TCP server.
accept() Used to accept TCP client connection, waiting until a connection arrives.
recv() Used to receives TCP messages.
close() Used to close a socket.
Send() Used to send messages.
socket.gethostname() Used to retrieve the hostname.
mysocket.accept() Returns a tuple with the remote address that has connected.
mysocket.bind( address ) Used to attach the specified address to the socket.
mysocket.getpeername() Used to get the remote address where the socket is connected.
mysocket.connect( address ) Used to assigns the data sent through the socket to the given remote address.
mysocket.getsockname() Used to retrieve the address of the socket’s local endpoint.
import socket
socket.getservbyname(‘domain name')
Used to obtain port number using the domain name.
import socket
socket.has_ipv6
Used to check support for IPV6.
ipaddress.ip_address(‘192.168.0.1') Used to assign an IP address.
ipaddress.ip_network(‘192.168.0.1/24') Used to determine the IPv4 or IPv6 version.
host4=ipaddress.ip_interface(‘192.168.0.1/24')
host4.network
Used to obtain the network from an interface.
net4=ipaddress.ip_network(‘192.168.0.1/24')
net4.num_addresses
Used to find the number of IP addresses in the specified network.
net4=ipaddress.ip_network(‘192.168.0.1/24')
net4.netmask
Used to find the netmask of the specified IP address.

Python Internet Modules

Here is the list of all Python internet modules with a brief explanation.

Protocol Explanation Port Python Module
Gopher Used to transfer documents. 70 Gopherlib, urllib
Telnet Used to open a command line on a remote computer. 23 telnetlib
IMAP4 Used for fetching emails from the mail server. 143 impalib
POP3 Used for fetching emails from the mail server. 110 poplib
SMTP Used for sending emails. 25 smtlib
FTP Used for file transfers. 20 Ftblib, urllib
MNTP Usenet news 119 mntplib
HTTP Used to access web pages over the internet. 80 Httplib, urllib

Conclusion

I have included all useful Python commands, libraries, and code that you can use as a quick reference in the above guide. Feel free to send comments if you have any questions.