Python Notes
some of this is taken from Learning Python Networking (2nd edition) by Jose Manual Ortega , Dr. M.O. Faruque Sarker, and Sam Washington
Table of Contents
places where python install touches
- Remove it automatically on the settings page. Under Apps and Features, there are application execution aliases.
Disable the ones that are relevant.
- C:\Users\Username\AppData\Local\Microsoft\WindowsApps\ (aliases/directories - delete those that you don't want)
- echo %PATH% ... remove entries that you don't want
pdb
- l - list file and place and breakpoints
- n - Step over next line in code
- step - step into next line in code
- print(a) - print a (or any other variable )
- dir(a) - (built-in Python function) Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
dragonfly related
window titles
using methods in dragonfly's Window class. E.g. Window.get_foreground() or Window.get_all_windows().
window.classname should give the app name and
window.title for the title.
PIP
sudo apt-get install python-pip
pip install <to install>
pip install virtualenv
virtualenv Python37
- virtualenv (choose env variables including version of Python)
- documentation
python networking
a lot of these notes were taken from Learning Python Networking
Socket types
https://docs.python.org/3/library/socket.html
Currently, there are several types of sockets, and each one is usually associated with a type
of protocol, for example:
- SOCK_STREAM - TCP
- SOCK_DGRAM - UDP datagram/async communication.
Sockets can also be classified according to their family.
- socket.AF_UNIX - Unix sockets - created before the concept of networks and are based on files
- socket.AF_INET - IPv4
- socket.AF_INET6 - IPv6
- socket.AF_BLUETOOTH - bluetooth
- socket.AF_VSOCK - virt machines to hosts, Availability: Linux >= 4.8 QEMU >= 2.8 ESX >= 4.0 ESX Workstation >= 6.5.
- socket.AF_PACKET - low-level interface directly to net devices. Packets represented by the tuple (ifname, proto[, pkttype[, hatype[, addr]]]) :
- ifname - device name.
- ifname - String specifying the device name.
- proto - An in network-byte-order integer specifying Ethernet protocol number.
- pkttype - Optional integer specifying packet type:
- PACKET_HOST (the default) - Packet addressed to the local host.
- PACKET_BROADCAST - Physical-layer broadcast packet.
- PACKET_MULTIHOST - sent to a phys-layer multicast addr
- PACKET_OTHERHOST - Packet to other host that has been caught by device driver in promiscuous mode.
- PACKET_OUTGOING - Packet originating from the local host that is looped back to a packet socket.
- hatype - Optional integer specifying the ARP hardware address type.
- addr - Optional bytes-like object specifying the hardware physical address, whose interpretation depends on the device.
Server socket methods
https://docs.python.org/3/library/socket.html
The following are some server socket methods
- bind(): With this method, we can define in which port our server will be
listening to connections
- listen(backlog): This method makes the socket accept connections and accept
to start listening to connections
- accept(): This method is used for accepting the following connection:
other socket flags
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind the socket to localhost on port 80
serversocket.bind((‘localhost', 80))
#become a server socket and listen a maximum of 10 connections
serversocket.listen(10)
Getting information about ports, protocols, and domains
#!/usr/bin/env python3
import socket
def find_service_name():
protocolname = 'tcp'
for port in [80, 25]:
print ("Port: %s => service name: %s" %(port, socket.getservbyport(port, protocolname)))
print ("Port: %s => service name: %s" %(53, socket.getservbyport(53, 'udp')))
if __name__ == '__main__':
find_service_name()
#!/usr/bin/env python3
import socket
try:
infolist = socket.getaddrinfo('www.packtpub.com', 'www', 0, socket.SOCK_STREAM, 0, socket.AI_ADDRCONFIG | socket.AI_V4MAPPED | socket.AI_CANONNAME,)
except socket.gaierror as e:
print('Name service failure:', e.args[1])
sys.exit(1)
info = infolist[0]
print(infolist)
socket_args = info[0:3]
address = info[4]
s = socket.socket(*socket_args)
try:
s.connect(address)
except socket.error as e:
print('Network failure:', e.args[1])
else:
print('Success: host', info[3], 'is listening on port 80')
#!/usr/bin/env python3
import socket
try:
infolist = socket.getaddrinfo('www.packtpub.com', 'www', 0, socket.SOCK_STREAM, 0, socket.AI_ADDRCONFIG | socket.AI_V4MAPPED | socket.AI_CANONNAME,)
except socket.gaierror as e:
print('Name service failure:', e.args[1])
sys.exit(1)
info = infolist[0]
print(infolist)
socket_args = info[0:3]
address = info[4]
s = socket.socket(*socket_args)
try:
s.connect(address)
except socket.error as e:
print('Network failure:', e.args[1])
else:
print('Success: host', info[3], 'is listening on port 80')
TCP sockets
#!/usr/bin/env python3
import socket
def get_remote_info():
remote_host = 'www.packtpub.com'
try:
print ("IP address of %s: %s" %(remote_host, socket.gethostbyname(remote_host)))
except socket.error as err_msg:
print ("%s: %s" %(remote_host, err_msg))
if __name__ == '__main__':
get_remote_info()
TCP client template
#!/usr/bin/env python3
import socket
# The client must have the same server specifications
host = '127.0.0.1'
port = 12345
BUFFER_SIZE = 1024
MESSAGE = 'Hello world,this is my first message'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_tcp:
socket_tcp.connect((host, port))
# We convert str to bytes
socket_tcp.send(MESSAGE.encode('utf-8'))
data = socket_tcp.recv(BUFFER_SIZE)
TCP server template
#!/usr/bin/env python3
import socket
host = '127.0.0.1'
port = 12345
BUFFER_SIZE = 1024
#The socket objects support the context manager type
#so we can use it with a with statement, there's no need to call socket_close ()
# We create a TCP type socket object
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_tcp:
socket_tcp.bind((host, port))
# We wait for the client connection
socket_tcp.listen(5)
# We establish the connection with the client
connection, addr = socket_tcp.accept()
with connection:
print('[*] Established connection')
while True:
# We receive bytes, we convert into str
data = connection.recv(BUFFER_SIZE)
# We verify that we have received data
if not data:
break
else:
print('[*] Data received: {}'.format(data.decode('utf-8')))
connection.send(data)