import shlex shlex.quote(s)
s
- анализируемая строка.s
.Функция shlex.quote()
модуля shlex
возвращает экранированную версию строки s
. Возвращаемое значение является строкой, которую можно безопасно использовать как единую команду в терминальной оболочке.
Эта идиома была бы небезопасна:
>>> import shlex >>> filename = 'somefile; rm -rf ~' >>> command = f'ls -l {filename}' >>> print(command) # ls -l somefile; rm -rf ~
Функция shlex.quote()
позволяет закрыть дыру в безопасности:
>>> import shlex >>> filename = quote(filename) >>> command = f'ls -l {filename}' >>> print(command) # ls -l 'somefile; rm -rf ~' >>> cmd = quote(command) >>> remote_command = f'ssh home {cmd}' >>> print(remote_command) # ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''
Цитирование совместимо с оболочками UNIX и с функциейshlex.split()
:
>>> import shlex >>> remote_command =shlex.split(remote_command) >>> remote_command # ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"] >>> command = shlex.split(remote_command[-1]) >>> command ['ls', '-l', 'somefile; rm -rf ~']