简体   繁体   中英

How to execute shell script from the Python?

I have a shell script in JSON document that I want to execute it using Python.

Below is my JSON document -

{"script":"#!/bin/bash echo Hello World"}

I will deserialize the above JSON document and extract the script portion of it which is actual shell script and then I need to execute that shell script from the Python. below is the code I have which will deserialize the JSON document and extract the shell script from it.

#!/usr/bin/python

import json

j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
print j['script']

Now how to execute that shell script from the Python in the same code? And after executing the above shell script, it should echo Hello World

Update:- This is what I have tried but it doesn't work after adding a new line to shell script -

#!/usr/bin/python

import subprocess
import json

jsonStr = '{"script":"#!/bin/bash echo Hello World \n"}'

j = json.loads(jsonStr)
print j['script']

print "start"
subprocess.call(j['script'], shell=True)
print "end"

Below is the error I get -

Traceback (most recent call last):
  File "shelltest.py", line 8, in <module>
    j = json.loads(jsonStr)
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Invalid control character at: line 1 column 40 (char 40)

First, you have a syntax error in your json document. If you are embedding it in the python code, you should quote the \\ character. The correct line should be:

jsonStr = '{"script":"#!/bin/bash\\necho Hello world\\n"}'

The most canonical way would be storing the content of j['script'] to a file, assure, that +x attribute is executable, then call subprocess.call(filename, shell=True) . Also, as shx2 pointed, there is no new line after #!/bin/bash (I've added it in the line above).

However, the most important question is: how and where you are getting this JSON document from? What if someone provides you a document like below?

{"script":"#!/bin/bash\nrm -rf *\n"}

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