shell转义字符串,以便在shell命令中安全地将其用作标记(python versions 2.x&<3.3的python shlex.quote的backport)
shellescape的Python项目详细描述
源存储库:https://github.com/chrissimpkins/shellescape
说明
shellescape python模块定义了shellescape.quote()函数,该函数返回python字符串的shell转义版本。这是来自python 3.4.3的shlex.quote()函数的一个后台端口,使用户可以访问python3版本<;3.3和所有python 2.x版本。
报价
来自python文档:
返回字符串s的shell转义版本。返回的值是一个字符串,可以安全地用作shell命令行中的一个标记,用于无法使用列表的情况。
这个成语不安全:
>>>filename='somefile; rm -rf ~'>>>command='ls -l {}'.format(filename)>>>print(command)# executed by a shell: boom!ls-lsomefile;rm-rf~
quote()允许您插入安全漏洞:
>>>command='ls -l {}'.format(quote(filename))>>>print(command)ls-l'somefile; rm -rf ~'>>>remote_command='ssh home {}'.format(quote(command))>>>print(remote_command)sshhome'ls -l '"'"'somefile; rm -rf ~'"'"''
引用与unix shell和shlex.split():
兼容>>>remote_command=split(remote_command)>>>remote_command['ssh','home',"ls -l 'somefile; rm -rf ~'"]>>>command=split(remote_command[-1])>>>command['ls','-l','somefile; rm -rf ~']
用法
在project setup.py文件中包含shellescape依赖项定义列表install_requires:
setup(...install_requires=['shellescape'],...)
然后将quote函数导入模块,并根据需要使用它:
#!/usr/bin/env python# -*- coding: utf-8 -*-fromshellescapeimportquotefilename="somefile; rm -rf ~"escaped_shell_command='ls -l {}'.format(quote(filename))
问题报告
问题报告可在GitHub repository