thekube/gen_ports.py

42 lines
1.3 KiB
Python
Raw Permalink Normal View History

2023-12-30 00:10:44 +00:00
#!/usr/bin/python3
2023-12-26 17:48:13 +00:00
import sqlite3
import random
import uuid
# Create the SQLite database if it doesn't exist
conn = sqlite3.connect("numbers_db.sqlite")
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS numbers (id text, number integer)''')
def generate_unique_random():
# Generate a random number between 32768 and 65535
rand_num = random.randint(32768, 65535)
# Generate a unique ID using UUID
new_id = str(uuid.uuid4())
# Check if the number is already in the database
c.execute("SELECT * FROM numbers WHERE number = ?", (rand_num,))
results = c.fetchall()
# If the number doesn't exist in the database, add it to the table
if not results:
c.execute("INSERT INTO numbers VALUES (?, ?)", (new_id, rand_num))
conn.commit()
else:
# If the number already exists, keep generating new random numbers until a unique one is found
while True:
rand_num = random.randint(32768, 65535)
c.execute("SELECT * FROM numbers WHERE number = ?", (rand_num,))
results = c.fetchall()
if not results:
new_id = str(uuid.uuid4())
c.execute("INSERT INTO numbers VALUES (?, ?)", (new_id, rand_num))
conn.commit()
break
return rand_num
if __name__ == "__main__":
2023-12-29 23:15:44 +00:00
print(str(generate_unique_random()))