[go: up one dir, main page]

0% found this document useful (0 votes)
40 views23 pages

Curs 8

The document discusses sockets and networking in Python. It explains how to build simple client-server applications using sockets in Python. It also covers modules for working with URLs, FTP, and SMTP for sending emails.

Uploaded by

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

Curs 8

The document discusses sockets and networking in Python. It explains how to build simple client-server applications using sockets in Python. It also covers modules for working with URLs, FTP, and SMTP for sending emails.

Uploaded by

Sudesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

PROGRAMMING IN PYTHON Gavrilut Dragos

Course 8
SOCKETS
Sockets are implemented through socket module in Python.
A socket object in Python has the same functions as a normal socket from C/C++:
accept, bind, close, connect, listen, recv, send, …
Besides this several other functions are available for domain translation, time outs, etc
Documentation for Python socket module can be found on:
o Python 3: https://docs.python.org/3/library/socket.html
SOCKETS
How to build a simple server/client in Python:
Python 3.x (Server)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1",1234))
s.listen(1)
(connection, address) = s.accept()
print ("Connectd address:",address);
while True:
data = connection.recv(100).decode("UTF-8")
if not data: break
print("Received: ",data)
if "exit" in data: break
connection.close()
print ("Server closed")
SOCKETS
How to build a simple server/client in Python:
Python 3.x (Server)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1",1234))
s.listen(1)
(connection, address) = s.accept()
print ("Connectd address:",address); Address and port
while True:
data = connection.recv(100).decode("UTF-8")
if not data: break
print("Received: ",data)
if "exit" in data: break
connection.close()
print ("Server closed")
SOCKETS
How to build a simple server/client in Python:
Python 3.x (Server)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1",1234))
s.listen(1)
(connection, address) = s.accept()
maximum number of
print ("Connectd address:",address);
queued connections
while True:
data = connection.recv(100).decode("UTF-8")
if not data: break
print("Received: ",data)
if "exit" in data: break
connection.close()
print ("Server closed")
SOCKETS
How to build a simple server/client in Python:
Python 3.x (Server)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1",1234))
s.listen(1)
(connection, address) = s.accept()
print ("Connectd address:",address); Number of bytes to read
while True:
data = connection.recv(100).decode("UTF-8")
if not data: break
print("Received: ",data)
if "exit" in data: break
connection.close()
print ("Server closed")
SOCKETS
How to build a simple server/client in Python:
Python 3.x (Server)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1",1234))
s.listen(1)
Use .decode(“UTF-8”) to
(connection, address) = s.accept()
convert a byte array to a
print ("Connectd address:",address);
string. Encoding in this case
while True:
is done with UTF-8
data = connection.recv(100).decode("UTF-8")
if not data: break
print("Received: ",data)
if "exit" in data: break
connection.close()
print ("Server closed")
SOCKETS
How to build a simple server/client in Python:
Python 3.x (Client)
import socket,time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1",1234))
s.send(b"Mesaj 1")
time.sleep(1)
Output from the server
s.send(b"Mesaj 2")
Connectd address: ('127.0.0.1', 61266)
time.sleep(1) Received: Mesaj 1
s.send(b"exit") Received: Mesaj 2
s.close() Received: exit
Server closed
SOCKETS
Getting current system IP
Python 3.x
import socket
print (socket.gethostbyname(socket.gethostname()))

Convert a host to an IP:


Python 3.x
Output
import socket
85.122.16.23
print (socket.gethostbyname('uaic.ro'))

Getting the name associated with an IP:


Python 3.x Output
import socket ('jad.uaic.ro', [],
print (socket.gethostbyaddr("85.122.16.7")) ['85.122.16.7'])
SOCKETS
Checking if a port is open:
Python 3.x (Client)
import socket

ip = "127.0.0.1"
ports = [20, 21, 23, 25, 80, 443, 530, 8080]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect_ex returns
s.settimeout(3) #3 seconds timeout
an error code if the
for port in ports:
connection is not
if s.connect_ex((ip, port)) == 0:
possible. 0 means
print("Port ",port," is open")
no error.
else:
print("Port ",port," is closed")
URL MODULES
Python has several implementation for accessing the content of a URL.
These modules work in a similar way as wget or curl utilities (allowing one to
download the content of a web page).
These are very useful for creating crawlers or scrappers.

o Python 3: https://docs.python.org/3/library/urllib.html#module-urllib
URLLIB MODULE
The following code extracts the name of the dean of our faculty.
Python 3.x
import urllib
from urllib import request
urlManagement = 'http://www.info.uaic.ro/bin/Structure/Management'

try:
response = urllib.request.urlopen(urlManagement).read()
text = response.decode("utf-8")
dn = text.split("class=strong>Decan</strong>:",1)[1].split("</span>",1)[0]
dean_name = dn.split("wikilink>",1)[1]
print ("Our dean is : ",dean_name)
except Exception as e:
print ("Error -> ",e)
FTP MODULE
Python has a module (ftplib) develop to enable working with FTP servers:
o Retrieve and store files
o Enumerate files from an FTP server
o Create folder on the FTP Server
o Support for password protected servers
o Support for custom FTP commands

Documentation
o Python 3: https://docs.python.org/3/library/ftplib.html
FTP MODULE
The following snippet lists all directories from ftp.debian.org from folder debian.
Python 3.x
from ftplib import FTP
#drwxr-sr-x 18 1176 1176 4096 Sep 17 09:55 dists
def parse_line(line): Output
if line.startswith("d"): 230 Login successful.
print (line.rsplit(" ",1)[1]) dists
try: doc
client = FTP("ftp.debian.org") indices
pool
res = client.login() project
print (res) tools
client.retrlines("LIST /debian/",parse_line) zzz-dists
client.quit()
except Exception as e:
print (e)
FTP MODULE
The following snippet downloads a file from a FTS server.
Python 3.x
from ftplib import FTP

cmdToDownload = "RETR /debian/extrafiles"


try:
client = FTP("ftp.debian.org")
res = client.login()
f = open("debian_extrafiles","wb")
client.retrbinary(cmdToDownload ,lambda buf: f.write(buf))
f.close()
client.quit()
except Exception as e:
print (e)
FTP MODULE
List of all supported FTP commands:
Command Description
FTP.connect Connect to a specified host on a specified port (default is 21)
FTP.login Specifies the user name and password for ftp login
FTP.retrlines Send a command to the FTP server and retrieves the results. The result is send line by line
to a callback function
FTP.storbinary Stores a file in a binary mode on the FTP server
FTP.retrbinary Retrieves a binary file from the server. A callback must be provided to write the binary
content.
FTP.rename Rename a file/folder from the server
FTP.delete Deletes a file from the server
FTP.rmd Deletes a folder from the server.
SMTP MODULE
Python has a module (smtp) develop to enable working with emails.
While for simple emails (a subject and a text) the smtp module is enough, for more
complex emails (attachment, etc) there is also another module (email.mime) that can
be use to create an email.
Documentation
o Python 3: https://docs.python.org/3/library/smtplib.html
o Python 3: https://docs.python.org/3/library/email.mime.html
SMTP MODULE
The following can be used to send an email.
Python 3.x
import smtplib
from email.mime.text import MIMEText
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login("<user_name>@gmail.com", "<Password>")
msg = MIMEText("My first email")
msg['Subject'] = "First email"
msg['From'] = "<user_name>@gmail.com"
msg['To'] = "<recipient email address>"
mail.sendmail("<from>", "<to>", msg.as_string())
mail.quit()
SMTP MODULE
For the previous snippet to work with gmail servers you need to activate “Access for
less secure apps” from you google account (
https://www.google.com/settings/security/lesssecureapps )
SMTP MODULE
Sending multiple attachments.
Python 3.x
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login("<user_name>@gmail.com", "<Password>")
msg = MIMEMultipart ()
msg['Subject'] = "First email"
msg['From'] = "<user_name>@gmail.com"
msg['To'] = "<recipient email address>"
msg.attach(MIMEImage(open("image.png","rb").read()))
msg.attach(MIMEImage(open("image2.png","rb").read()))
mail.send_message(msg)
mail.quit()
SMTP MODULE (ATTACHMENTS + BODY)
Python 3.x
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login("<user_name>@gmail.com", "<Password>")
msg = MIMEMultipart ("mixed")
msg['Subject'] = "First email"
msg['From'] = "<user_name>@gmail.com"
msg['To'] = "<recipient email address>“
msg.attach(MIMEText("The body of the email", 'plain'))
msg.attach(MIMEImage(open("image.png","rb").read()))
mail.send_message(msg)
mail.quit()
BUILDING A SIMPLE HTTP SERVER
Python has some build in modules that can simulate a http server.
Python 3.x
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler

httpd = HTTPServer(('127.0.0.1', 8000), SimpleHTTPRequestHandler)


httpd.serve_forever()

This script will create a HTTP server that listens on port 8000. If a file named
“index.html” exists near the python script, it’s content will be server when
127.0.0.1:8000 is accessed from the browser.
We will discuss more about these servers after we learn about classes.
BUILDING A SIMPLE HTTP SERVER
The default behavior for such a server is to produce a directory listing for the root
where the script is.
However, if within the root a index.html file is found, that file will be loaded and send to
the client.
These modules can also be executed automatically from the command line as follows:
o Python 3: python -m http.server 9000

The last parameter from the command line is the port number.

You might also like