栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Windows上安全地转义cmd.exe Shell的命令行参数?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Windows上安全地转义cmd.exe Shell的命令行参数?

引用Windows命令行的问题在于,有两个受引用影响的分层解析引擎。首先,有

cmd.exe
解释某些特殊字符的Shell(例如)。然后,有一个调用程序解析命令行。
CommandLineToArgvW
Windows提供的功能经常会发生这种情况,但并非总是如此。

就是说,对于一般情况,例如,使用

cmd.exe
与程序一起解析其命令行的程序
CommandLineToArgvW
,您可以使用Daniel
Colascione在《每个人都用错误的方式引号命令行参数》中描述的技术。我最初尝试将其适应Ruby,现在尝试将其转换为python。

import redef escape_argument(arg):    # Escape the argument for the cmd.exe shell.    # See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx    #    # First we escape the quote chars to produce a argument suitable for    # CommandLineToArgvW. We don't need to do this for simple arguments.    if not arg or re.search(r'(["s])', arg):        arg = '"' + arg.replace('"', r'"') + '"'    return escape_for_cmd_exe(arg)def escape_for_cmd_exe(arg):    # Escape an argument string to be suitable to be passed to    # cmd.exe on Windows    #    # This method takes an argument that is expected to already be properly    # escaped for the receiving program to be properly parsed. This argument    # will be further escaped to pass the interpolation performed by cmd.exe    # unchanged.    #    # Any meta-characters will be escaped, removing the ability to e.g. use    # redirects or variables.    #    # @param arg [String] a single command line argument to escape for cmd.exe    # @return [String] an escaped string suitable to be passed as a program    #   argument to cmd.exe    meta_chars = '()%!^"<>&|'    meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')    meta_map = { char: "^%s" % char for char in meta_chars }    def escape_meta_chars(m):        char = m.group(1)        return meta_map[char]    return meta_re.sub(escape_meta_chars, arg)

应用此代码,您应该能够成功转义cmd.exe Shell的参数。

print escape_argument('''some arg with spaces''')# ^"some arg with spaces^"

请注意,该方法应引用单个完整参数。如果要从多个来源收集参数,例如,通过构建一串python代码以传递给python命令,则必须在将其传递给之前对其进行汇编

escape_argument

import osCMD = '''string with spaces and &weird^ charcters!'''os.system('python -c "import sys; print(sys.argv[1])" {0}'.format(escape_argument(CMD)))# string with spaces and &weird^ charcters!


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653420.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号