Skip to content

Instantly share code, notes, and snippets.

@isaacs
Created December 5, 2010 20:14
Show Gist options
  • Save isaacs/729422 to your computer and use it in GitHub Desktop.
Save isaacs/729422 to your computer and use it in GitHub Desktop.
Usage: sudo.js -u nobody whoami
#!/usr/bin/env node
var args = process.argv.slice(2)
, arg
, requestedUid = 0
, cmd = []
, cmdArgs
, tty = process.binding("stdio")
, path = require("path")
, usage = path.basename(__filename)
+ " [-u <user>]"
+ " <cmd>"
+ "\nRun <cmd> as <user>"
while (arg = args.shift()) {
switch (arg) {
case "--":
cmdArgs = true
break
case "-u": case "--uid": case "--user":
requestedUid = args.shift()
break
case "-h": case "--help": case "-?":
console.error(usage)
process.exit(0)
break
default:
cmdArgs = true
cmd.push(arg)
break
}
}
if (!cmd) {
console.error(usage)
process.exit(1)
}
var cp = require("child_process")
, opts = { env : process.env
, cwd : process.cwd()
, customFds : [ tty.stdinFD
, tty.stdoutFD
, tty.stderrFD ]}
var child
if (0 === process.getuid()) {
process.setuid(requestedUid)
child = cp.spawn(cmd.shift(), cmd, opts)
} else {
child = cp.spawn("sudo", process.argv, opts)
}
child.on("exit", function (code) { process.exit(code) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment