escape string for command line

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat Jan 8 15:48:25 EST 2005


In <mailman.321.1105127978.22381.python-list at python.org>, Ksenia
Marasanova wrote:

> I have a simple ecard creation script on a website, where user can add
> text to a graphic. I use ImageMagick for it:
> 
> # template_file => path to image template file
> # new_file => path to generated file
> # text => user input
> command = '''convert %s -font OfficinaSanITC-BookOS -pointsize 12
> -fill "#8C2F48" -draw "gravity north text 0,26 '%s'" %s''' % (
>     template_file, text, new_file)
> system(command)
> 
> I was wondering, is there a general way to escape the string entered
> by the user, to prevent code injection into command line?

Take a look at the "string-escape" encoding:

>>> evil = "'; rm -rf /;"
>>> command = "echo '%s'"
>>> print command % evil.encode('string-escape')
echo '\'; rm -rf /;'

> Will it
> always be safe, even when binary data is submitted through POST?

Don't know if it's always safe.  Unprintable bytes like 0x00 will be
escaped as '\x00'.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list