Libraries

The Python Standard Libraries


Request library

Python requests is a library for making HTTP requests.

Request status

Discription

My example with requests library.
Enter the webside URL.
The HTTP 200 OK success status response code indicates that the request has succeeded.

Code
																
import requests
import tkinter as tk
import tkinter.ttk as ttk
import threading
import re


pattern="^(http|https):\/\/"

root = tk.Tk()
root.title("Server Status")
root.geometry('350x150')

urlLabel = tk.Label(root, text="Url")
urlLabel.grid(row=0, column=0)
url = tk.Entry(width=30)
url.grid(row=0, column=1)

progress = ttk.Progressbar(root, orient=tk.HORIZONTAL, length=120,
                           mode="indeterminate")
progress.grid(row=3, column=1, columnspan=3)


def step():
    progress.start(10)

def search():
    url_check = url.get()

    if (re.search(pattern, url_check)):
        print("Введен корректный URL")
        r = requests.get(url.get())
        code=r.status_code
        print('status_code = ', code)

        if code == 404:
            label = tk.Label(root, text="                        ")
            label.grid(row=1, column=4)
            label=tk.Label(root, text="Not found" + " "+str(code), fg='red')
            label.grid(row=1, column=1)

        elif code==200:
            label = tk.Label(root, text="                        ")
            label.grid(row=1, column=1)
            label = tk.Label(root, text="Running" + " " + str(code), fg='green')
            label.grid(row=1, column=4)

    else:
        print("Введен Не корректный URL")


status_Label = tk.Label(root, text="Status Code")
status_Label.grid(row=1, column=0)

threading.Thread(target=step()).start

submit_btn = tk.Button(root, text="Submit", command=search)
submit_btn.grid(row=5, column=1, columnspan=3)

tk.mainloop()


Get headers info with proxies.

Discription

This is an interesting example. You can get header information from inside the organization. The code uses a proxy.
I made a small dictionary with deciphering fields with header meanings.

Code
																

import requests
proxies = {'http': 'http://10.105.0.200:3128'}
s = requests.session()
s.proxies.update(proxies)
resp = s.get("http://example.com/")

k=resp.headers
Ks=list(k.keys())

description={
'A-IM':'Acceptable instance-manipulations for the request.',
'Accept':'Media type(s) that is/are acceptable for the response.',
'Accept-Charset':'Character sets that are acceptable.',
'Accept-Datetime':'Acceptable version in time.',
'Accept-Encoding':'List of acceptable encodings.',
'Accept-Language':'List of acceptable human languages for response.',
'Access-Control-Request-Method':'Initiates a request for cross-origin resource sharing with Origin (below).',
'Access-Control-Request-Headers':'Initiates a request for cross-origin resource sharing with Origin (below).',
'Authorization':'Authentication credentials for HTTP authentication.',
'Cache-Control':'Used to specify directives that must be obeyed by all caching mechanisms along the request-response chain.',
'Connection':'Control options for the current connection and list of hop-by-hop request fields. Must not be used with HTTP/2.',
'Content-Encoding':'The type of encoding used on the data. See HTTP compression.',
'Content-Length':'The length of the request body in octets (8-bit bytes).',
'Content-MD5': 'A Base64-encoded binary MD5 sum of the content of the request body.',
'Content-Type': 'The Media type of the body of the request (used with POST and PUT requests).',
'Cookie':'An HTTP cookie previously sent by the server with Set-Cookie (below).',
'Date':'The date and time at which the message was originated (in "HTTP-date" format as defined by RFC 9110: HTTP Semantics, section 5.6.7 "Date/Time Formats")',
'Expect':'Indicates that particular server behaviors are required by the client.',
'Forwarded':'Disclose original information of a client connecting to a web server through an HTTP proxy.',
'From':'The email address of the user making the request.',
'Host':'The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. The port number may be omitted if the port is the standard port for the service requested. Mandatory since HTTP/1.1. If the request is generated directly in HTTP/2, it should not be used',
'HTTP2-Settings':'A request that upgrades from HTTP/1.1 to HTTP/2 MUST include exactly one HTTP2-Setting header field. The HTTP2-Settings header field is a connection-specific header field that includes parameters that govern the HTTP/2 connection, provided in anticipation of the server accepting the request to upgrade.',
'If-Match':'Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource if it has not been modified since the user last updated it.',
'If-Modified-Since':'Allows a 304 Not Modified to be returned if content is unchanged.',
'If-None-Match':'Allows a 304 Not Modified to be returned if content is unchanged, see HTTP ETag.',
'If-Range':'If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity.',
'If-Unmodified-Since':'Only send the response if the entity has not been modified since a specific time.',
'Max-Forwards':'Limit the number of times the message can be forwarded through proxies or gateways.',
'Origin':'Initiates a request for cross-origin resource sharing (asks server for Access-Control-* response fields).',
'Pragma':'Implementation-specific fields that may have various effects anywhere along the request-response chain.',
'Prefer':'Allows client to request that certain behaviors be employed by a server while processing a request.',
'Proxy-Authorization':'Authorization credentials for connecting to a proxy.',
'Range':'Request only part of an entity. Bytes are numbered from 0. See Byte serving.',
'Referer':'This is the address of the previous web page from which a link to the currently requested page was followed. (The word "referrer" has been misspelled in the RFC as well as in most implementations to the point that it has become standard usage and is considered correct terminology).',
'TE':'	The transfer encodings the user agent is willing to accept: the same values as for the response header field Transfer-Encoding can be used, plus the "trailers" value (related to the "chunked" transfer method) to notify the server it expects to receive additional fields in the trailer after the last, zero-sized, chunk.Only trailers is supported in HTTP/2.',
'Trailer':'The Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer coding.',
'Transfer-Encoding':'The form of encoding used to safely transfer the entity to the user. Currently defined methods are: chunked, compress, deflate, gzip, identity. Must not be used with HTTP/2.',
'User-Agent':'The user agent string of the user agent.',
'Upgrade':'Ask the server to upgrade to another protocol. Must not be used in HTTP/2.',
'Via':'Informs the server of proxies through which the request was sent.',
'Warning':'A general warning about possible problems with the entity body.'}

print("HEADERS:")
print(120*"-")
for key in k:
	condition = key in description.keys()
	print(key, '=>', k[key].ljust(3), '|description|:'.center(7), description[key] if condition else "no description")




Authentication

Discription

For this practice I used this youtube example https://www.youtube.com/watch?v=cV21EOf5bbA&t=323s.
I tried authenticate to https://the-internet.herokuapp.com/login.
Additionally i used fake_useragent library for imitating other browsers.

Code
																
import requests
import fake_useragent

user=fake_useragent.UserAgent().random
header={'user-agent':user}

loginurl=('https://the-internet.herokuapp.com/authenticate')
payload={
    'username': 'tomsmith',
    'password':'SuperSecretPassword!'
}
r=requests.post(loginurl, data=payload, headers=header)
print(r.text)


Decorators

Discription

Simple example with decorators. I call src_target_threat twice with using a decorator.

Code
																
from tkinter import *
from tkinter import ttk


def do_twice(func):
    def wrapper_do_twice(*args, **kwargs):
        func(*args, **kwargs)
        func(*args, **kwargs)
    return wrapper_do_twice

@do_twice
def src_target_threat(lb):
    src_checked_list = list(lb.get(0, END))
    print(src_checked_list)

root = Tk()
root.geometry("230x200")
languages = ["Python", "Java", "Go"]
languages_var = Variable(value=languages)
languages_listbox = Listbox(listvariable=languages_var)
languages_listbox.pack(anchor=NW, fill=X, padx=5, pady=5)
btn = ttk.Button(text="Click", command=lambda: src_target_threat(languages_listbox))
btn.pack()
root.mainloop()