Python run bash command gets bad result

Hi, I am trying to run this bash cmd on python 3.2. Here is the python code:

message = '\\x61'
shell_command = "echo -n -e '" + message + "' | md5"
print(shell_command)
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print(event.communicate())

this gave me the following result:
echo -n -e '\ x61' | md5
(b'713b2a82dc713ef273502c00787f9417 \ n ', None)

But when I run this printed cmd in bash, I get a different result:
0cc175b9c0f1b6a831c399e269772661

Where am I wrong?

+3
source share
4 answers

The key to this problem is when you say:

But when I ran this printed cmd in bash ...

Popen bash, , ​​ /bin/sh, echo bash. , bash, , :

$ echo -n -e '\x61' | md5sum
0cc175b9c0f1b6a831c399e269772661  -

/bin/sh, :

$ echo -n -e '\x61' | md5sum
20b5b5ca564e98e1fadc00ebdc82ed63  -

, /bin/sh -e escape- \x.

python, , /bin/sh:

>>> cmd = "echo -n -e '\\x61' | md5sum"
>>> event = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
>>> print event.communicate()
('20b5b5ca564e98e1fadc00ebdc82ed63  -\n', None)
+3

. python, ..:

Popen('/usr/bin/md5sum', shell=False, stdin=PIPE).communicate('\x61')
+1

:

communicate() (stdoutdata, stderrdata).

, :

(b'713b2a82dc713ef273502c00787f9417\n', None)

(stdoutdata), , 0 :

print(event.communicate()[0])
0

This would do the trick:

>>> p=Popen('echo -n \x61 |md5sum',shell=True,stdout=PIPE)
>>> p.communicate()
(b'0cc175b9c0f1b6a831c399e269772661  -\n', None)
0
source

All Articles