-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
114 lines (104 loc) · 2.41 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
var spawn = require("child_process").spawn;
var inpathSync = require("inpath").sync;
var pidof = require("./pidof");
var sudoBin = inpathSync("sudo");
var isWin = (process.platform == "win32");
var MSG = [
"PID is NULL",
"password is INVALID"
];
function _exec(command, cb) {
cb = cb || function () {};
var prompt = "#node-webkit-sudo-passwd#";
var args = ["-S", "-k", "-p", prompt];
args.push.apply(args, command);
var child = spawn(sudoBin, args, {stdio : "pipe"});
// Find PID
var bin = command.filter(function (i) {
return i.indexOf('-') !== 0;
})[0];
function waitForStartup(err, pid) {
if (err) {
throw new Error("Couldn't start " + bin);
}
if (pid.length || child.exitCode !== null) {
cb(null, {pid: pid});
}
else {
setTimeout(function () {
pidof(bin, waitForStartup);
}, 100);
}
}
pidof(bin, waitForStartup);
var prompts = 0;
child.stderr.on("data", function (data) {
var lines = data.toString().trim().split('\n');
lines.forEach(function (line) {
if (line === prompt) {
if (++prompts > 1) {
cb(true, {code: 1, msg: MSG[1]});
child.stdin.write("\n\n\n\n");
}
else {
child.stdin.write(Sudo.prototype.password + "\n");
}
}
});
});
}
function Sudo() {}
Sudo.prototype = {
constructor: Sudo,
password: '',
setPassword: function (password) {
Sudo.prototype.password = password || '';
},
check: function (cb) {
_exec([isWin ? "ls" : "dir"], (function(i) {
return function (err) {
if (!i++) {
cb(!err)
}
}
})(0));
},
exec: function (command, cb) {
this.check(function (valid) {
if (valid) {
_exec(command, cb);
}
else {
cb(true, {code: 1, msg: MSG[1]});
}
});
},
killByPid: function (pid, cb) {
if (pid) {
pid = pid.toString();
if (isWin) {
this.exec(["tskill", pid], cb);
}
else {
this.exec(["kill", "-9", pid], cb);
}
}
else {
cb(true, {code: 0, msg: MSG[0]});
}
},
killByName: function (name, cb) {
var self = this;
pidof(name, function(err, pids) {
if (pids && pids.length) {
pids.forEach(function (pid) {
self.killByPid(pid, cb);
});
}
else {
cb(true, {code: 0, msg: MSG[0]});
}
});
}
};
module.exports = Sudo;