Let's say I was selling a software and I didn't want it to be leaked (of course using Python wouldn't be the greatest as all code is open but let's just go with it), I would want to get a unique ID that only the user's PC has and store it within a list in my script. Now every time someone executed the script it would iterate through the list and check to see if that unique ID matches with one from the list.
Would this even be possible and if so how would one implement it in Python?
Python has a unique id library uuid. https://docs.python.org/3.5/library/uuid.html
import uuid
# Create a uuid
customer_id = str(uuid.uuid4())
software_ids = [customer_id] # Store in a safe secure place
can_run = customer_id in software_ids
print(can_run)
Related
I have a function written in nodejs and another in python. They both do the same thing in different scripts.
I currently have a function that creates a firestore collection called profile, then insert a document, which has as a name, the document id created by firestore
The document itself contains an object, representing the user, first name, last name, email, and phone.
the phone is a list, or array [], it always contains just one phone number, later on we'll add multiple phone numbers per user but for now, you can assume that there is just one element in a list. Phone can never be null, email can be null sometimes.
What I want to do, is if the phone doesn't exist already then insert a new user, otherwise update the existing user. So there should be no duplication.
Can this be done via merge in firestore or update or should I do a where query? I know that a query is always possible, but I want to know if I can use a merge on a list field in firestore.
If you don't have any document reference to update to and need to query the field phone_number then you need to use the where() method with the array_contains operator. Use the array_contains operator to filter based on array values. If a document is found you can use arrayUnion() to add elements to an array but only elements are not already present. See sample snippets below:
Python:
# Collection Reference
col_ref = db.collection(u'profile')
# Check collection if there's any array in documents that contains the `phone_number`
admin_ref = col_ref.where(u'phone_number', u'array_contains', 12345).get()
# Checks if there's a result.
if admin_ref:
# Iterate the result
for item in admin_ref:
doc = col_ref.document(item.id)
doc.update(
# Adds multiple phone numbers to the field, but only adds new ones.
{u'phone_number': firestore.ArrayUnion([12345,54321])})
# If there's no result, then add a document with the field name `phone_number`
else:
col_ref.add({'phone_number': [123456]})
For more information, you can check these documentations:
Array membership
Update elements in an array
I am trying to write a simple python script to collect certain command outputs from mongodb, as part of validating the database before and after backup.
Below is the script.
import pymongo
import json
client = pymongo.MongoClient('localhost',username='admin',password='admin')
db = client['mydb']
collections = list(db.list_collection_names())
for i in collections:
print(db.$i.estimated_document_count())
All the collections are stored in the list called collections and I want to run it in for loop so that I can get document count in each collection. I know the last print statement here is wrong. How to get it right? I want $i to substitute the collection name during each iteration so that I can get the document count of that collection.
When I run "print(db.audit.estimated_document_count())" it gives me the document count in audit collection. But how to iterate through the list in for loop and substitute the value of i in the command?
Also, for validating backup/restore is there any other commands that I should run against database to verify backup/restore?
You cannot use a computed value as an identifier in at "dot" expression, at least not without resorting to dirty tricks.
What you can do, is to find some other mechanism for getting a collection given its name. According to the tutorial and API reference, you can use db['foo'] instead of db.foo.
I log in to Active Directory, then I want to list my own group memberships with Python ldap3 library.
server = Server('server.company.local', get_info=ALL)
conn = Connection(server, user="company\\user", password="password", authentication=NTLM, auto_bind=True)
print(conn.extend.standard.who_am_i())
This code only shows user name (like whoami cmd command), but i want to list my groups (like whoami /groups command).
Unfortunately I dont have the rights to make different searches on the Domain controller, thats why (perhaps) the following code returns empty string:
conn.search("dc=name,dc=company,dc=local","(&(sAMAccountName={}))".format("company\\myusername")
,attributes=['memberOf'])
How can i list my own group membership, like whoami /groups does?
Active Directory generally allows all authenticated users to read a lot of attributes, including memberOf. Check the number of records returned for your search. I expect you are finding zero records with that search. sAMAccountName values do not generally contain the "company\" component but are just "myusername".
The problem was the search base in my search: I replaced "dc=name,dc=company,dc=local" to "dc=company,dc=local" It works fine.
I need to generate unique account ID for each user.(only numeric)
UUID can't solve this problem, pls help me!
Here you go
import random
import string
''.join(random.choice(string.digits) for _ in range(8))
Even shorter with python 3.6 using random.choices()
import random
import string
''.join(random.choices(string.digits, k=8))
Avoid Possible Collision:
Try creating a new object with generated id except integrity error, create id again.
eg. -
def create_obj():
id = ''.join(random.choices(string.digits, k=8))
try:
MyModel.objects.create(id=id)
except IntegrityError:
create_obj()
OR
def create_unique_id():
return ''.join(random.choices(string.digits, k=8))
def create_object():
id = create_unique_id()
unique = False
while not unique:
if not MyModel.objects.get(pk=id):
unique = True
else:
id = create_unique_id()
MyModel.objects.create(id=id)
Thanks to #WillemVanOnsem for pointing out the chances of generating duplicate id, the two examples I provided will create a new id as many times as required to get an unique id, but as the number of rows in your database increase the time to get a unique id will grow more and more and a time will come when there are so many records in your database(10^8) when creation of new record is not possible with a 8-digit uid as all possible combination already exists then you will be stuck in an infinite loop while trying to create a new object.
If the stats provided my Willem is correct, I say the changes are too high of a collision. So I would recommend not to create id's yourself, go with django's default auto field or uuid which guarantees uniqueness through space and time.
Assuming you are using MYSQL and your comment said you didn't use database PK because they start with 1, 2...
Why not just make PK starts with your range?
eg.
ALTER TABLE user AUTO_INCREMENT = 10000000;
And you can put this into your custom migration, see manage.py makemigrations --empty
I presume other databases have the similar approach as well
For django app I would suggest using get_random_string from django.utils.crypto package. Internally python secrets.choice is used. This way you will not have to change code, if secrets interface changes.
from django.utils.crypto import get_random_string
def generate_account_id():
return get_random_string(8, allowed_chars='0123456789')
django.utils.crypto
If you work with python >= 3.6 , the alternative is secrets.token_hex(nbytes) which returns string of hex value, then convert the string to number. To further detect collision you can also check whether any instance with the ID already exists in your Django model (as shown in the accepted answer)
code example :
import secrets
hexstr = secrets.token_hex(4)
your_id = int(hexstr, 16)
I've created a program to take a users predetermined unique identifier, hash it, and store it in a dictionary mapping to the user's name. I later receive the unique identifier, rehash it, and can look up the user's name.
I've come to a problem where an individual's 9 digit unique ID hash()'s to the same number as somebody else. This has occurred after gathering data for about 40 users.
Is there a common work around to this? I believe this is different than just using a hashmap, because if I create a bucket for the hashed ID, I won't be able to tell who the user was (whether it be the first item in the bucket or second).
Edit:
id = raw_input()
hashed_id = hash(id)
if not dictionary.has_key(hashed_id):
name = raw_input()
dictionary[hashed_id] = name
check_in_user(dictionary[hashed_id])
I have never seen hash() used for this. hash() should be used for data structures as a shorthand for the entire object, such as keys in the internal implementation of dictionaries.
I would suggest using a UUID (universally unique identifier) for your users instead.
import uuid
uuid.uuid4()
# UUID('d36b850c-2433-42c6-9252-6371ea3d33c2')
You'll be very hard pressed to get a collision out of UUIDs.