用法:
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 shlex.join用法及代碼示例
- Python shutil.copyfile()用法及代碼示例
- Python shutil.unregister_unpack_format()用法及代碼示例
- Python shutil.get_terminal_size()用法及代碼示例
- Python shutil.get_archive_formats()用法及代碼示例
- Python shutil.which()用法及代碼示例
- Python shutil.copytree()用法及代碼示例
- Python shutil.copymode()用法及代碼示例
- Python shutil.unpack_archive()用法及代碼示例
- Python shutil.move()用法及代碼示例
- Python shutil.copy2()用法及代碼示例
- Python shutil.unregister_archive_format()用法及代碼示例
- Python Wand sharpen()用法及代碼示例
- Python shutil.chown()用法及代碼示例
- Python shutil.copyfileobj()用法及代碼示例
- Python shutil.copystat()用法及代碼示例
- Python Wand shade()用法及代碼示例
- Python shutil.copy()用法及代碼示例
- Python shutil.get_unpack_formats()用法及代碼示例
- Python shutil.disk_usage()用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 shlex.quote。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。