I am trying to get some error handling for the following code.
In the line subprocess.Popen...... if the shell=True the script will encrypt if a correct file name is given, however there is no file with that name the error code is not printed, but it does show on terminal as no existing file/directory.
if I run the shell=False then I am not able to encrypt files but the error message does print.
Would it be possible for anyone to explain what I am doing wrong? As I have looked at different posts on here but I still do not understand why it won't work. My guess is that it has something to do with the shell=True portion of the script.
SrcDIR ="/home/test/testsource/"
DstDIR ="/home/test/testdest/"
try:
subprocess.Popen(["openssl aes-128-cbc -salt -in " + SrcDIR + str(var1) + " -out " + DstDIR + "enc." + str() + " -k " + str(var2)], shell=True)
output3 = ("file " + str(var1) + "created")
print(output3)
except IOError as reason2:
errormsg = ("Error encrypting file due to: \n" + str(reason2))
print(errormsg)
If you set the shell
arg to False
, then the args
argument becomes a sequence of strings, not a single string: the first args
element is the name of the program to run, and subsequent elements are the arguments to that program, e.g. (if I understand your code correctly):
subprocess.Popen \
(
[
"openssl", "aes-128-cbc", "-salt",
"-in", os.path.join(SrcDIR, var1),
"-out", os.path.join(DstDIR, "enc." + var1),
"-k", var2
]
)
This is also better than trying to pass a single command string with shell
= True
, because this way you don’t have to beware of characters with special meaning to the shell.