如何在node.js中检查文件是否可执行?
可能像这样:
fs.isExecutable(function (isExecutable) {
})
如何在node.js中检查文件是否可执行?
可能像这样:
fs.isExecutable(function (isExecutable) {
})
仅依赖于内置fs
模块的另一种选择是使用 fs.access 或 fs.accessSync。这种方法比获取和解析文件模式更容易。例如:
const fs = require('fs');
fs.access('./foobar.sh', fs.constants.X_OK, (err) => {
console.log(err ? 'cannot execute' : 'can execute');
});
fs.constants.S_IXUSR
。顺便说一句:https://dev59.com/KmQo5IYBdhLWcg3wKs1r#69897809 - Ciro Santilli OurBigBook.comfs.stat
命名的按位掩码模式检查与fs.constants.S_IXUSR
自https://dev59.com/KmQo5IYBdhLWcg3wKs1r#16258627编写以来,Node.js似乎已添加了这些内容,现在可以执行以下操作:
const fs = require('fs');
function isExec(p) {
return !!(fs.statSync(p).mode & fs.constants.S_IXUSR)
}
console.log(isExec('/usr/bin/ls'))
console.log(isExec('/dev/random'))
fs.constants.S_IXUSR
:用户fs.constants.S_IXGRP
:组fs.constants.S_IXOTH
:其他人man 2 chmod
因此,使用stat
进行完整检查需要检查是否与文件所有者匹配或是否属于组。
因此,也许最好只使用fs.accessSync
的繁琐API,如https://dev59.com/KmQo5IYBdhLWcg3wKs1r#41929624中所述:
const fs = require('fs');
function isExec(p) {
try {
fs.accessSync(p, fs.constants.X_OK)
return true
} catch (e) {
return false
}
}
console.log(isExec('/usr/bin/ls'))
console.log(isExec('/dev/random'))
这些检查应该由它自己来完成。
看一下https://www.npmjs.com/package/executable,它甚至有一个.sync()方法。
executable('bash').then(exec => {
console.log(exec);
//=> true
});
which
或where
命令。它支持Windows和Posix(Mac、Linux、Unix、如果Posix层暴露或安装了Posix工具,则也支持Windows)。const fs = require('fs');
const path = require('path');
const child = require("child_process");
function getExecPath(exec) {
let result;
try {
result = child.execSync("which " + exec).toString().trim();
} catch(ex) {
try {
result = child.execSync("where " + exec).toString().trim();
} catch(ex2) {
return;
}
}
if (result.toLowerCase().indexOf("command not found") !== -1 ||
result.toLowerCase().indexOf("could not find files") !== -1) {
return;
}
return result;
}
function isExec(exec) {
if (process.platform === "win32") {
switch(Path.GetExtension(exec).toLowerCase()) {
case "exe": case "bat": case "cmd": case "vbs": case "ps1": {
return true;
}
}
}
try {
// Check if linux has execution rights
fs.accessSync(exec, fs.constants.X_OK);
return true;
} catch(ex) {
}
// Exists on the system path
return typeof(getExecPath(exec)) !== 'undefined';
}
child.execSync
调用对我来说看起来不安全,攻击者肯定可以提供一个值给 exec
,从而允许它在你的电脑上执行任意代码。这是不可取的。还有其他检查方法吗? - Fabio Spampinato