Node.js 从NodeJS执行bash/shell脚本时如何传递参数

Node.js 从NodeJS执行bash/shell脚本时如何传递参数,node.js,bash,shell,parameters,arguments,Node.js,Bash,Shell,Parameters,Arguments,我有以下代码: exec('sh cert-check-script-delete.sh', req.body.deletedCert); console.log(req.body.deletedCert); 控制台日志正确显示请求正文。deletedCert为非空 在证书检查脚本delete.sh中,我有: #!/bin/sh certs.json="./" # Name of JSON file and directory location echo -e $1 >> ce

我有以下代码:

exec('sh cert-check-script-delete.sh', req.body.deletedCert);
console.log(req.body.deletedCert);
控制台日志正确显示请求正文。deletedCert为非空

证书检查脚本delete.sh中,我有:

#!/bin/sh

certs.json="./"  # Name of JSON file and directory location
echo -e $1 >> certs.json
但它只是在
certs.json

我也试过:

exec('sh cert-check-script-delete.sh' + req.body.deletedCert)
但是这两种格式都不起作用

使用
execFile()
,并将参数传递到带外:

child_process.execFile('./cert-check-script-delete.sh', [req.body.deletedCert])
child_process.execFile('/bin/sh', ['./check-cert-script-delete.sh', req.body.deletedCert])
这样,字符串(来自
req.body.deletedCert
)将作为文本参数传递,而不是作为代码解析。请注意,这要求您的脚本成功标记为可执行(
chmod+x check cert script delete.sh
),并以有效的shebang开头


如果无法修复文件权限以使其成为可执行文件,请至少将参数传递到带外:

child_process.execFile('./cert-check-script-delete.sh', [req.body.deletedCert])
child_process.execFile('/bin/sh', ['./check-cert-script-delete.sh', req.body.deletedCert])

顺便说一句,你有没有理由不给你的文件一个正确的shebang(
#!/bin/bash
,因为
echo-e
使用
sh
是不安全的),设置+x位,并在没有显式解释器的情况下直接执行它?尝试在.sh,exec('sh cert-check-script-delete.sh'+req.body.deletedCert)@davecarrothers,这是一个巨大的安全风险。假设有人提交代码说他们想删除证书
$(rm-rf~)
。您永远不应该将传入请求中的文本替换为作为shell命令一部分解析的文本。感谢您的建议,但以这种格式编写它现在甚至不需要将空行写入
certs.json
。同样关于shebang,我不知道有不同类型的shebang,我一定是从中复制并粘贴了shebangonline@DaveCarruthers谢谢你,这很有效!谢谢你的回答,但是
child\u进程
来自哪里?我定义了以下变量
const exec=require('child_process')。exec,child
,这就足够了,还是我还需要导入其他内容?
const child\u process=require('child\u process')
将为您提供整个模块,而不仅仅是其中的一个函数。感谢您的建议,但这仍然不起作用,我使用了涉及空间的解决方案now@tnoel999888,re:“不起作用”--细节值得深入研究。安全性很重要,如果这不起作用,那是因为其他东西被破坏了(你的文件权限错误,或者你的shebang无效,等等)。@tnoel999888,…也就是说,如果你真的必须使用shell,至少要这样做:
child\u process.execFile('/bin/sh',['./check-cert-script delete.sh',req.body.deletedCert])