Tutorialspoint

Display connection error in python

import socket
import sys
def main():
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "127.0.0.1"
    port = 8000
    try:
        soc.connect((host, port))
    except:
        print("Connection Error")
        sys.exit()
    print("Please enter 'quit' to exit")
    message = input(" -> ")
    while message != 'quit':
        soc.sendall(message.encode("utf8"))
        if soc.recv(5120).decode("utf8") == "-":
            pass        # null operation
        message = input(" -> ")
    soc.send(b'--quit--')
if __name__ == "__main__":
    main()

Website Blocker Using Python

#Import libraries
import time
from datetime import datetime as dt
#Windows host file path
hostsPath=r"C:\Windows\System32\drivers\etc\hosts"
redirect="127.0.0.1"
#Add the website you want to block, in this list
websites=["www.youtube.com","youtube.com", "www.facebook.com", "facebook.com"]
while True:
    #Duration during which, website blocker will work
    if dt(dt.now().year,dt.now().month,dt.now().day,9) < dt.now() < dt(dt.now().year,dt.now().month,dt.now().day,18):
        print ("Sorry Not Allowed...")
        with open(hostsPath,'r+') as file:
            content=file.read()
            for site in websites:
                if site in content:
                    pass
                else:
                    file.write(redirect+" "+site+"\n")
    else:
        with open(hostsPath,'r+') as file:
            content=file.readlines()
            file.seek(0)
            for line in content:
                if not any(site in line for site in websites):
                    file.write(line)
            file.truncate()
        print ("Allowed access!")
    time.sleep(5)

Python Random and Secrets Example

import secrets
import random
secNum = random.SystemRandom().random()
print("secure number is ", secNum)
print("Secure byte token", secrets.token_bytes(16))

string in a sequence of bytes in python

import hashlib
mystring = input('Enter string to hash: ')
hash_obj = hashlib.sha1(mystring.encode())
print(hash_obj.hexdigest())

string as hashing function in python

import hashlib
mystring = input('Enter string to hash: ')
hash_obj = hashlib.md5(mystring.encode())
print(hash_obj.hexdigest())

Socket Programming with Multi-threading in Python

import socket
import sys
import traceback
from threading import Thread


def main():
    start_server()


def start_server():
    host = "127.0.0.1"
    port = 8000        # arbitrary non-privileged port

    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)   
    print("Socket created")

    try:
        soc.bind((host, port))
    except:
        print("Bind failed. Error : " + str(sys.exc_info()))
        sys.exit()

    soc.listen(6)       # queue up to 6 requests
    print("Socket now listening")

    # infinite loop- do not reset for every requests
    while True:
        connection, address = soc.accept()
        ip, port = str(address[0]), str(address[1])
        print("Connected with " + ip + ":" + port)

        try:
            Thread(target=client_thread, args=(connection, ip, port)).start()
        except:
            print("Thread did not start.")
            traceback.print_exc()

    soc.close()


def clientThread(connection, ip, port, max_buffer_size = 5120):
    is_active = True

    while is_active:
        client_input = receive_input(connection, max_buffer_size)

        if "--QUIT--" in client_input:
            print("Client is requesting to quit")
            connection.close()
            print("Connection " + ip + ":" + port + " closed")
            is_active = False
        else:
            print("Processed result: {}".format(client_input))
            connection.sendall("-".encode("utf8"))


def receive_input(connection, max_buffer_size):
    client_input = connection.recv(max_buffer_size)
    client_input_size = sys.getsizeof(client_input)

    if client_input_size > max_buffer_size:
        print("The input size is greater than expected {}".format(client_input_size))

    decoded_input = client_input.decode("utf8").rstrip()
    result = process_input(decoded_input)

    return result


def process_input(input_str):
    print("Processing the input received from client")

    return "Hello " + str(input_str).upper()

if __name__ == "__main__":
    main()

Barrier Objects in Python

from random import randrange
from threading import Barrier, Thread
from time import ctime, sleep

num = 4
# 4 threads will need to pass this barrier to get released.
b = Barrier(num)
names = ['India', 'Japan', 'USA', 'China']


def player():
    name = names.pop()
    sleep(randrange(2, 5))
    print('%s reached the barrier at: %s \n' % (name, ctime()))
    b.wait()

threads = []
print("Race starts now…")

for i in range(num):
    threads.append(Thread(target=player))
    threads[-1].start()
"""
Below loop enables waiting for the threads to complete before moving on with the main script.
"""
for thread in threads:
    thread.join()

print("All Reached Barrier Point!")

Creating a hash, using the default MD5 hash algorithm in python

#Import libraries
import hashlib
import hmac

#data
update_bytes = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
                              Suspendisse tristique condimentum viverra. Nulla accumsan \
                              orci risus, non congue lacus feugiat id.'
#secret key
password = b'402xy5#'
#Generate cryptographic hash using md5
my_hmac = hmac.new(update_bytes, password, hashlib.md5) 

print("The first digest: " + str(my_hmac.digest()))
print("The Canonical Name: " + my_hmac.name)
print("Block size: " +  str (my_hmac.block_size) + "bytes")
print("Digest size: " + str(my_hmac.digest_size) + "bytes")

#Create a copy of the hmac object
my_hmac_cpy = my_hmac.copy() 
print("The Copied digest: " + str(my_hmac_cpy.digest()))

Generate cryptographically secure random numbers in python

import random
randGen = random.SystemRandom()
for x in range(0,10):
  secV = 10+ randGen.randint(0,499)
  print(secV)

Generate cryptographically secure random numbers in python

import secrets

#generate 10 secure random numbers between 10 and 500
for x in range(0,10):
  secV =10+ secrets.randbelow(500)
  print(secV)

1 2 3 4 5 6 7 ... 27 Next
Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.