简体   繁体   中英

Linux command equivalent of hash() in python

In my program In have a log directory. Name of the log directory is very long so in my python script I used hash function to get the unique code and append it to fixed string ie:

LOG_DIR = "abcdefghijklmnopqrstuvwxyz"
 log_dir_hashed = hash(LOG_DIR)
 new_log_dir = "log_%s" %log_dir_hashed

Since I am new to python please tell me if anything can go wrong with above code? also How to do similar thing in shell script so that result of the python directory name and shell directory name obtained after hashing is same.

hash() is an implementation detail of python and __hash__ dunders can even override what it does, so you shouldn't be using it like that. It also has some possibly surprising properties , like:

# This is not a collision produced by the used hashing method, it is
# how hash() functions. The result though is a collision.
>>> hash(-2) == hash(-1)
True

Use a well known hash like MD5 or SHA1 etc. If you need cryptographically secure log dirs, choose a suitable hash based on that. Have a look at https://docs.python.org/3/library/hashlib.html . These have equivalent command line tools available.

For example:

from hashlib import md5

log_dir_hashed = md5('abcdefghijklmnopqrstuvwxyz'.encode('utf-8')).hexdigest()
new_log_dir = "log_%s" % log_dir_hashed

Comparing python:

>>> md5('abcdefghijklmnopqrstuvwxyz'.encode('utf-8')).hexdigest()
'c3fcd3d76192e4007dfb496cca67e13b'

and equivalent command line (one way to do it):

 % echo -n 'abcdefghijklmnopqrstuvwxyz' | md5sum - | awk '{print $1}'
c3fcd3d76192e4007dfb496cca67e13b

Hash is doing encryption to your directory, Basically converting your data to to MD5/SHA or other encryption.

You can use crypt(Data) in shell script to get the same results.

Eg.

log_dir_hashed=crypt(LOG_DIR)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM