Rewrite done by openai
(PROMPT) rewrite this script in python3 and change the -s and -n args to be input from an input box , without argparse
#! /bin/bash
while getopts s:n: flag
do
case "${flag}" in
s) size=${OPTARG};;
n) name=${OPTARG};;
esac
done
gen ()
{ head -c "$size" -z </dev/urandom > /tmp/keyfile
}
hasher ()
{ cat /tmp/keyfile | while read -r line; do
printf %s "$line" | sha512sum | cut -f1 -d' '
done; }
gen && hasher keyfile | tee "$name" && truncate --size "$size" "$name"
exit
Here is the Python3 script that rewrites the original script without using the argparse module and prompts the user for input from an input box:
(PROMPT) fix this error in above script
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-12-56c15e9d00d0> in <module>
18
19 with open(name, 'w') as f:
---> 20 for h in hasher():
21 f.write(h)
22
<ipython-input-12-56c15e9d00d0> in hasher()
10
11 def hasher():
---> 12 with open('/tmp/keyfile', 'rb') as f:
13 while True:
14 chunk = f.read(8192)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/keyfile'
The error is occurring because the /tmp/keyfile file does not exist. To fix this error, the gen function should be called before the hasher function so that the /tmp/keyfile file is created and can be read by the hasher function.
Here is the updated script with the error fixed:
import os
import hashlib
size = int(input('Enter the size of the keyfile: '))
name = input('Enter the name of the keyfile: ')
def gen():
with open('/tmp/keyfile', 'wb') as f:
f.write(os.urandom(size))
def hasher():
with open('/tmp/keyfile', 'rb') as f:
while True:
chunk = f.read(8192)
if not chunk:
break
yield hashlib.sha512(chunk).hexdigest()
gen()
with open(name, 'w') as f:
for h in hasher():
f.write(h)
os.truncate(name, size)
In this updated script, the gen function is called before the hasher function so that the /tmp/keyfile file is created and can be read by the hasher function.