當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。