在 lua 中执行外部程序,而不需要用户输入作为参数的 lua
2018-11-10 23:30:11
收藏:0
阅读:135
评论:1
我想在 lua 中执行外部程序。通常可以这样做:
os.execute("run '"..arg0.."' 'arg1' arg2")
这种方法的问题在于,如果我要将用户输入作为字符串传递给外部程序,用户输入可能是 '; evil 'h4ck teh system' ',那么上面的脚本将像这样执行:
/bin/bash -c "run ''; evil 'h4ck teh system' '' 'arg1' arg2"
另一个问题是当我将 '$var' 作为参数时,shell 会用环境变量来替换它。在我的特殊情况下,我有类似 [[program 'set title "$My Title$"']] 的东西——嵌套的字符串——和 program 解析 "$My Title$"(具有转义序列)与 '$My Title$'(它就是它)的方式不同。因为我想要按原样设置标题,所以最好的方法是像这样设置参数:'My Title'。但现在命令必须是这样的:
os.execute([[run "set title '$My Title$'"]])
但现在——正如我所说的——$My 将被替换为空字符串,因为环境并不知道任何名为 $My 的变量,也因为我从未希望它被替换。
因此,我正在寻找通常的方法:
execv("run", {"set title '"..arg0.."'", arg1, arg2})
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

local safe_unquoted = "^[-~_/.%w%%+,:@^]*$" local function q(text, expand) -- quoting under *nix shells -- "expand" -- false/nil: $var and `cmd` must NOT be expanded (use single quotes) -- true: $var and `cmd` must be expanded (use double quotes) if text == "" then text = '""' elseif not text:match(safe_unquoted) then if expand then text = '"'..text:gsub('["\\]', '\\%0')..'"' else local new_text = {} for s in (text.."'"):gmatch"(.-)'" do new_text[#new_text + 1] = s:match(safe_unquoted) or "'"..s.."'" end text = table.concat(new_text, "\\'") end end return text end function execute_commands(...) local all_commands = {} for k, command in ipairs{...} do for j = 1, #command do if not command[j]:match"^[-~_%w/%.]+$" then command[j] = q(command[j], command.expand) end end all_commands[k] = table.concat(command, " ") -- space is arguments delimiter end all_commands = table.concat(all_commands, ";") -- semicolon is commands delimiter return os.execute("/bin/bash -c "..q(all_commands)) end使用示例:
-- 使用示例#1: execute_commands( {"your/program", "arg 1", "$arg2", "arg-3", "~/arg4.txt"}, {expand=true, "echo", "Your program finished with exit code $?"}, {"ls", "-l"} ) -- 下面的命令将会被执行: -- /bin/bash -c 'your/program '\''arg 1'\'' '\''$arg2'\'' arg-3 ~/arg4.txt;echo "Your program finished with exit code $?";ls -l'由于你要求在
$arg2周围单引号,因此$arg2不会扩展为值。不幸的是,
"Your program finished with exit code $?"也不会被扩展,除非你显式设置expand = true。-- 使用示例#2: execute_commands{"run", "set title '$My Title$'", "arg1", "arg2"} -- 生成的命令并不简单,但它确实做到了你需要的 :-) -- /bin/bash -c 'run '\''set title '\''\'\'\''$My Title$'\''\'\'' arg1 arg2'