当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python shlex.quote用法及代码示例


用法:

shlex.quote(s)

返回字符串 s 的 shell-escaped 版本。返回值是一个字符串,可以安全地用作 shell 命令行中的一个标记,用于无法使用列表的情况。

警告

shlex模块是只为 Unix shell 设计.

quote() 函数不能保证在非 POSIX 兼容 shell 或来自其他操作系统(如 Windows)的 shell 上正确。在此类 shell 上执行此模块引用的命令可能会导致命令注入漏洞。

考虑使用通过列表传递命令参数的函数,例如 subprocess.run()shell=False

这个成语是不安全的:

>>> filename = 'somefile; rm -rf ~'
>>> command = 'ls -l {}'.format(filename)
>>> print(command)  # executed by a shell: boom!
ls -l somefile; rm -rf ~

quote() 让您堵住安全漏洞:

>>> from shlex import quote
>>> command = 'ls -l {}'.format(quote(filename))
>>> print(command)
ls -l 'somefile; rm -rf ~'
>>> remote_command = 'ssh home {}'.format(quote(command))
>>> print(remote_command)
ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''

引用与 UNIX shell 和 split() 兼容:

>>> from shlex import 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 ~']

3.3 版中的新函数。

相关用法


注:本文由纯净天空筛选整理自python.org大神的英文原创作品 shlex.quote。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。