Anand Vyas
Anand Vyas

Reputation: 103

Preventing my script from os command injection python

i am using python 2.7.x I automating my stuffs and in there i need run to another python program from my python script for that i am using the system function from the 'os' library.

for e.g:

import os 
os.system("python anotherscript.py --data <USER_INPUT_FROM_MY_SCRIPT_HERE>")

so i know if any user inputs some other command in place of expected user input that will be converting to os command injection and that's what i want prevent in this case.

Thank you.

Upvotes: 0

Views: 2249

Answers (2)

user7813790
user7813790

Reputation: 557

@Tenchi2xh's answer is the better way to do it, but if that doesn't work (e.g. your script only works on Python 2.x and the other one only works on Python 3.x) then you should use the subprocess module, passing the arguments as a list:

import subprocess
subprocess.call(['python', 'anotherscript.py', '--data', '<USER INPUT>'])

Also take a look at subprocess.check_call and subprocess.check_output to see if they are closer to what you need.

https://docs.python.org/2/library/subprocess.html#subprocess.call

Upvotes: 1

Tenchi2xh
Tenchi2xh

Reputation: 300

Since you need to run a Python script from Python, just import it the Python way and invoke the needed function normally

import anotherscript

anotherscript.<function>("<user_input>")

Upvotes: 2

Related Questions