Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and Tar command shell=True

Tags:

python

tar

popen

I wrote this script to tar some backups :

date = str(now.year)+str(now.month)+str(now.day)
tar="tar -pczf "+date+"backup_lucas.tar.gz /home/lucas/backup/"
subprocess.Popen(tar)

But then I get :

  File "test.py", line 21, in <module>
    subprocess.Popen(tar)
  File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
    errread, errwrite)
  File "/usr/lib/python2.6/subprocess.py", line 1141, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

When I add add shell=True to the Popen command it works :

subprocess.Popen(tar,shell=True)

However I heard the shell=True is to be avoided as it is insecure sometimes (?).

How can I successfully issue the command without using shell=True ?

like image 530
Lucas Kauffman Avatar asked Oct 15 '25 13:10

Lucas Kauffman


1 Answers

When shell=False you need to pass your command via a list:

date = str(now.year)+str(now.month)+str(now.day)
filename = date + "backup_lucas.tar.gz"
subprocess.Popen(['tar', '-pczf', filename, '/home/lucas/backup/'])

Edit: the important part from the docs:

"On Unix, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. If a string is specified for args, it will be used as the name or path of the program to execute; this will only work if the program is being given no arguments." - http://docs.python.org/library/subprocess.html#popen-constructor

like image 171
sgallen Avatar answered Oct 18 '25 02:10

sgallen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!