---
description: >-
  Python 3 guide with just enough basics to begin hacking, note taking from
  TCM's course
---

# Guide to Python 3&#x20;

{% embed url="https://www.youtube.com/watch?index=3&list=PLLKT__MCUeiwBa7d7F_vN1GUwz_2TmVQj&v=3GriwyvJzio" %}

### How to read inputs from console

Reading input from STDIN, print output to STDOUT

Sample input&#x20;

```python
## Input
9
29
7
27

## STDIN
a = int(input())
b = int(input())
c = int(input())
d = int(input())

print(a**b + c**d) ## print to STDOUT
```

## Basic Python 101

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FOqS1dsN7OiDNXgM51UgG%2Fimage.png?alt=media\&token=bfc5ec06-7712-4e4f-a7d6-8dc9d8d46170)

Note in the last line than the method "int" ONLY TAKES THE WHOLE NUMBER of a float (etc. returns 29 from 29.9)

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2Fnknzvqp6UsqH13OyBqI7%2Fimage.png?alt=media\&token=c551728d-fb85-4363-9e3d-25aba826c2ae)

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F6V4qukFGKPQ1EH4afpnp%2Fimage.png?alt=media\&token=e9826966-69e5-4a04-a1a5-98dae673d628)

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FERPFvIKwjcga80HCVPKx%2Fimage.png?alt=media\&token=2d858697-786c-47c2-b885-61082cea6f72)

### Practice Reading Python scripts

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F2n7em2DLJumpoqmHg0oR%2Fimage.png?alt=media\&token=bd14babe-cd1d-400f-ba6a-7deb1b03cff9)

## Advanced Python 102

Importing, Advanced Strings, Dictionaries

```python
!#/bin/python3
### 1. IMPORTING
import sys # system functions and parameters
from datetime import datetime
print(datetime.now())

from datetime import datetime as dt #import as alias
print(dt.now())

### 2. ADVANCED STRINGS
## SPLIT & JOIN
my_name = 'Davin'
print(my_name[0]) # first letter
print(my_name[:3]) # Dav (excludes the last)
print(my_name[-3:-1]) # vin
test = "hello there I am Davin"
print(test.split(" ")) # split by delimiter space
splitliaolor = test.split()
print(' '.join(splitliaolor))

print("A" in "Apple") # returns true
letter = "A", word = "Apple"
print(letter in word)
```

| String manipulation                                                  |
| -------------------------------------------------------------------- |
| string.split(\<insert delimiter>)                                    |
| \<delimiter>.join(string)                                            |
| string.replace(\<strin&#x67;_&#x74;&#x6F;_&#x72;eplace> , newstring) |
| string.find(\<string to find>)                                       |

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FFtSQSPFqiEQIhuoLjAUs%2Fimage.png?alt=media\&token=3246858f-82ea-4ade-97d4-beb9448c8304)

### Combining List to Dictionary

The Python zip() function accepts iterable items and merges them into a single tuple. The resultant value is a **zip object that stores pairs of iterables**. You can pass lists, tuples, sets, or dictionaries through the zip() function.

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F4RoMonQSVEll4OUB8oIu%2Fimage.png?alt=media\&token=bed1851a-de7c-4161-9773-f7bad73c2b76)

### Hosting a web server

For example u might wanna do file transfer to a target machine for download

```python
# go to the folder u want to host (let ur files be available)
### python 2 method
>>> python -m SimpleHTTPServer 80 #port
### python 3 method
>>> python3 -m http.server 80
```

![Navigate to your IP address](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FpPPkQYR7cRNKHeS8cUcZ%2Fimage.png?alt=media\&token=aba96c35-39ee-43d8-9fdc-29332068e9c6)

```
# file transfer
pip3 install pyftpdlib
python3 -m pyftpdlib -p 21 w
```

![Add ftp:// to the front of the IP address](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FrOlwMGTsXfXAIU8GH9NY%2Fimage.png?alt=media\&token=5a32cfde-0c5d-4317-afbb-90a0302390ef)

### Shitty Port Scanner Script

A good ol homemade nmap scanner to scan for open ports, for this script we are scanning only 50 to 85 as it takes too long!

```python
# program name is scanner.py
#!/usr/bin/env python3
import sys #allow us to use command line arguments etc.
from datetime import datetime as dt
import socket

#Define our targets, make sure theres ip address input
if len(sys.argv) == 2: # this is as python3 scanner.py <ip>, <ip> is argument 1, 2 arguments to python 3      
    target = socket.gethostbyname(sys.argv[1]) #[1] selects ip, translates hostname to IP4   
else:
    print('Invalid amounts of arguments')
    print('Syntax error: Follow python3 scanner.py <ip> la')
    sys.exit()

#Add a pretty banner
print('-' *50)
print('Firing up, Scanning target ' + target )
print('Time started: ' + str(dt.now()))
print('-' * 50)

try:
    for port in range(50,85): # runs port from 50 - 85 cos its shitty
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #AF_INET is IPV4, SOCK_STREAM is your port   
        socket.setdefaulttimeout(1) #input is a float, detects port not open, then move on after 1s, if not it will hang forever!   
        result = s.connect_ex((target,port)) #if error connection, return error/if no error, returns 0
        print("Checking port {} right now".format(port))
        if result == 0:    # no error
            print("Port {} is open, noice.".format(port))
        s.close()
        
except KeyboardInterrupt: # use ctrl + c to exit program 
    print("\nExiting Program sua")
    sys.exit()
except socket.gaierror:
    print("Hostname cannot be resolved la")
    sys.exit()
    
except socket.error:
    print("Couldnt connect to server walau")
    sys.exit()
```

results:

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2FyxalnAOqur7ff2gBH8mB%2Fimage.png?alt=media\&token=8c712507-d9f3-4616-bb44-b81a7700a0e1)

## Sockets

[https://realpython.com/python-sockets/#background](https://realpython.com/python-sockets/#background)

Explanation for the Echo Server example shown below

* TCP sockets are defined as `socket.SOCK_STREAM`
* UDP sockets are defined as `socket.SOCK-DGRAM`
* `AF_INET` is the Internet address family for [IPv4](https://en.wikipedia.org/wiki/IPv4). `SOCK_STREAM` is the socket type for [TCP](https://realpython.com/python-sockets/#tcp-sockets), the protocol that will be used to transport our messages in the network.
* `s.bind()` is used to associate the socket with a specific network interface and port number
* `HOST` can be a hostname, [IP address](https://realpython.com/python-ipaddress-module/), or empty string. If an IP address is used, `host` should be an IPv4-formatted address string. The IP address `127.0.0.1` is the standard IPv4 address for the [loopback](https://en.wikipedia.org/wiki/Localhost) interface, so only processes on the host will be able to connect to the server. If you pass an empty string, the server will accept connections on all available IPv4 interfaces.
* `listen()` enables a server to `accept()` connections. It makes it a “listening” socket
* we now have a new socket object from `accept()`. This is important since it’s the socket that you’ll use to communicate with the client. It’s distinct from the listening socket that the server is using to accept new connections
*   This reads whatever data the client sends and echoes it back using `conn.sendall()`.

    If `conn.recv()` returns an empty [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes-objects) object, `b''`, then the client closed the connection and the loop is terminated. The [`with` statement](https://realpython.com/python-with-statement/) is used with `conn` to automatically close the socket at the end of the block.

{% hint style="info" %}
127.0.0.1 : localhost is **a hostname that refers to the current device used to access it**. It is used to access the network services that are running on the host via the loopback network interface.&#x20;
{% endhint %}

#### Example of a sample implementation : an Echo Server (echo whatever received back to client)

the API calls the server makes to setup a “listening” socket:

* `socket()`
* `bind()`
* `listen()`
* `accept()`

A listening socket does just what it sounds like. It listens for connections from clients. When a client connects, the server calls `accept()` to accept, or complete, the connection.

```python
#!/usr/bin/env python3

import socket
HOST = '127.0.0.1' # standard loopback interface address 'localhost'
PORT = 65432 #port to listen on

#same as s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)
            
```

#### Echo Client

It creates a socket object, connects to the server and calls `s.sendall()` to send its message. Lastly, it calls `s.recv()` to read the server’s reply and then [prints it](https://realpython.com/python-print/).

```python
#!/usr/bin/env python3

import socket

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 65432        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))
```

{% tabs %}
{% tab title="sys.argv()" %}
sys.argv() : [Command line arguments](https://www.geeksforgeeks.org/python-set-6-arguments/) are those values that are passed during calling of program along with the calling statement. Thus, the first element of the array `sys.argv()` is the name of the program itself. `sys.argv()` is an array for [command line arguments](https://www.geeksforgeeks.org/python-set-6-arguments/) in Python. To employ this module named “`sys`” is used. `sys.argv` is similar to an array and the values are also retrieved like Python array.

For example,&#x20;

![](https://2068334946-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fow1iM27u7disHeJiSlBC%2Fuploads%2F24WHFOnWpFUq0zHltjRE%2Fimage.png?alt=media\&token=56c0348e-1cfd-46e1-8def-0ce7d3b560ff)
{% endtab %}

{% tab title="s.connect_ex() VS s.connect()" %}
* **socket.connect(address)** -> Connect to a remote socket at address. (The format of address depends on the address family — see above.)

If the connection is interrupted by a signal, the method waits until the connection completes, or raise a socket.timeout on timeout, if the signal handler doesn’t raise an exception and the socket is blocking or has a timeout. For non-blocking sockets, the method raises an InterruptedError exception if the connection is interrupted by a signal (or the exception raised by the signal handler).

Raises an auditing event socket.connect with arguments self, address.

Changed in version 3.5: The method now waits until the connection completes instead of raising an InterruptedError exception if the connection is interrupted by a signal, the signal handler doesn’t raise an exception and the socket is blocking or has a timeout (see the PEP 475 for the rationale).

* **socket.connect\_ex(address)** -> Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects.

Raises an auditing event socket.connect with arguments self, address.
{% endtab %}

{% tab title="socket.error VS socket.gaierror" %}
socket.gaierror : reIt means that **your given host name ' ' is invalid** (gai stands for getaddrinfo() ). A subclass of [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError), this exception is raised for address-related errors by [`getaddrinfo()`](https://docs.python.org/3/library/socket.html#socket.getaddrinfo) and [`getnameinfo()`](https://docs.python.org/3/library/socket.html#socket.getnameinfo). The accompanying value is a pair `(error, string)` representing an error returned by a library call. _string_ represents the description of _error_, as returned by the `gai_strerror()` C function.

socket.error : just unable to connect
{% endtab %}

{% tab title="KeyboardInterrupt" %}
Without `KeyboardInterrupt`, ctrl + c will cancel only one loop for \<try> and move on to next loop and so on. In python, interpreter throws KeyboardInterrupt exception when the user/programmer presses ctrl – c or del key either accidentally or intentionally. KeyboardInterrupt exception inherits the BaseException and similar to the general exceptions in python, it is handled by try except statement in order to stop abrupt exiting of program by interpreter.

```python
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)
```
{% endtab %}
{% endtabs %}

### Modules (HTTP & FTP Server)
