Browse Source

runas elevated refactor for windows

master
Pradeep Bhaskaran 4 years ago
parent
commit
3df27b76ae
4 changed files with 146 additions and 40 deletions
  1. 1
    0
      .gitignore
  2. 101
    39
      index.js
  3. 4
    1
      package.json
  4. 40
    0
      windowselevate.hta

+ 1
- 0
.gitignore View File

/node_modules

+ 101
- 39
index.js View File

); );
} }


var __isElevated = null;
var isRunningElevated = ()=>{ var isRunningElevated = ()=>{
return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
inherit : true, shell: true
, env: process.env
, title : `check privileged execution mode using fsutil dirty query C:`
}).then((exitcode)=>{
console.log('Elevated')
return true;
}).catch(()=>{
console.log('Not Elevated');
throw false;
});
if(__isElevated === null) {
return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
inherit : true
// , shell: true
// , stdio: 'ignore'
, env: process.env
, title : `check privileged execution mode using "fsutil dirty query C:"`
}).then((exitcode)=>{
console.log('Elevated')
__isElevated = true;
return true;
}).catch(()=>{
__isElevated = false;
console.log('Not Elevated');
throw false;
});
}
else return Promise.resolve(__isElevated);
} }




, 'elixir-client-unlinked' , 'elixir-client-unlinked'
, 'ember-searchable-select' , 'ember-searchable-select'
, 'loopback-component-jsonapi' , 'loopback-component-jsonapi'
, 'elixir-config'
, 'elixir-config-development'
, 'cihsr-config' , 'cihsr-config'
, 'cihsr-data' , 'cihsr-data'
, 'elixir-data' , 'elixir-data'
, 'chess-server' , 'chess-server'
] ]


var productionRepos = [
'elixir-config-production'
]


var env = Object.assign({}, process.env); // Shallow clone it. var env = Object.assign({}, process.env); // Shallow clone it.
var __runcmd = function(label){ var __runcmd = function(label){


var op = { var op = {
'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' } 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
, 'undefined' : ()=>{ return op.h(); }
, 'upgrade' : ()=>{ , 'upgrade' : ()=>{
console.log('upgrade.......') console.log('upgrade.......')
var tasks = [ var tasks = [
} }
, 'runas' : ()=>{ , 'runas' : ()=>{
return isRunningElevated().then( return isRunningElevated().then(
() => op[ processedArgs.label || processedArgs._[0] || 'h']()
(isElevated) => {
if(isElevated) {
try {
op[ processedArgs.label || processedArgs._[0] || 'h']()
}
catch(e){
console.error('Error Invalid command : ' + e)
fs.writeFileSync('run.done', 'success')
}
finally {
}
} else throw false;
}
) )
.catch(()=>{ .catch(()=>{
console.log('Not Elevated');
console.log('Requesting Elevated Privileges')
nodeShellExec('MSHTA', [`javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('node', 'elxr ${processedArgs._[0]} ${processedArgs._[1]} ${processedArgs._[2]} --runas=true', '', 'runas', 1);close();`]
console.log('Not Elevated Requesting Elevated Privileges');
// Wait for the runas to complete before we read it.
try {
fs.unlinkSync('run.done')
fs.unlinkSync('run.log')
}
catch(e) { } //Ignore
var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._); args.push('--runas')
nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
, { , {
// inherit : true
// , shell: true
env: process.env
inherit : true
,
shell: true
// ,
, env: process.env
, runas : true
, title : `runas` , title : `runas`
} }
);
).then(()=>{
// runas returned.
var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
runaslog.forEach((logEntry)=>{
logEntry.succes ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' '))
})
})
.catch(err => console.error('Elevation failed : ' + err));
}) })
} }
, 'push' : ()=>{ , 'push' : ()=>{
var performPull = repo => { var performPull = repo => {
if(existsSync(repo)) { if(existsSync(repo)) {
console.log('pulling ' + repo) console.log('pulling ' + repo)
nodeShellExec('git', ['pull'], {
return nodeShellExec('git', ['pull'], {
inherit : true, shell: true, inherit : true, shell: true,
cwd : repo cwd : repo
// , env: process.env // , env: process.env
, runas : processedArgs.runas
, title : `git pull ${repo}` , title : `git pull ${repo}`
}).catch((e)=>{ console.error(e) }) }).catch((e)=>{ console.error(e) })
} }
else { else {
console.log('cloning ' + repo) console.log('cloning ' + repo)
nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
return nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
{ {
inherit : true, shell: true, inherit : true, shell: true,
env: process.env env: process.env
, runas : processedArgs.runas
, title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}` , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
}).catch((e)=>{ console.error(e) }) }).catch((e)=>{ console.error(e) })
} }


if(!processedArgs.runas) gitRepos.forEach(performPull) if(!processedArgs.runas) gitRepos.forEach(performPull)
return isRunningElevated().then( return isRunningElevated().then(
()=> elevatedRunasRepos.forEach(performPull))
.catch(
() => op['runas']()
(isElevated) => {
if(isElevated) {
any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
fs.writeFileSync('run.done', 'success')
}).catch(()=>{
fs.writeFileSync('run.done', 'error')
})
}
else throw false;
}
).catch(
() => {
op['runas']()
}
) )
} }
, 'npmi' : ()=>{ , 'npmi' : ()=>{
var tasks = []; var tasks = [];
g[processedArgs._[1]](); g[processedArgs._[1]]();
} }
} }
return op[label] ? op[label]() : op['start'](label);
return op[label] ? op[label]() : null;
} }


// mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
var mysql = '../xampp/mysql/bin/mysql' var mysql = '../xampp/mysql/bin/mysql'
var mysqldump = '../xampp/mysql/bin/mysqldump' var mysqldump = '../xampp/mysql/bin/mysqldump'


__runcmd(processedArgs.label || processedArgs._[0] || 'h');
// nodeShellExec('git', ['status']);
// --runas
if(processedArgs.runas) {
// Weve been asked to run in priviledged mode. Check if we already are privileged.
__runcmd('runas')
}
else __runcmd(processedArgs.label || processedArgs._[0] || 'h');


function nodeShellExec() { function nodeShellExec() {


var args = Array.from(arguments); var args = Array.from(arguments);
args[2] ? null : args[2] = {}
args[2].title ? null : args[2].title = `${args[0]} ${args[1]}`
var opts = args[2] = args[2] || {}
opts.title ? null : opts.title = `${args[0]} ${args[1] }`
const child = spawn(...arguments); const child = spawn(...arguments);


var p = new Promise(function(resolve, reject){ var p = new Promise(function(resolve, reject){
if(!args[2].detached) {
if(!opts.detached) {
var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks... var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
var succes = true;
// use child.stdout.setEncoding('utf8'); if you want text chunks // use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.setEncoding('utf8'); child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8'); child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/}); child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
child.on('error', (chunk) => { messages.push(chunk); /*console.error(chunk)*/ });
child.on('error', (chunk) => { succes = false; messages.push(chunk); /*console.error(chunk)*/ });
child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/}); child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
// child.stderr.pipe(process.stderr); // child.stderr.pipe(process.stderr);
child.on('close', (code) => { child.on('close', (code) => {
console.log([` ${args[2].title} exited with code ${code}`])
// console.log([ messages.join('') ])
process.stdout.write( messages.join('') )
if(code !== 0 ) return reject(code)
if(code !== 0) succes = false;
if(opts.runas){
fs.writeFileSync('run.log', ', ' + JSON.stringify({ result: ` ${opts.title} exited with code ${code}`, messages : messages }), {'flag':'a+'} )
}
else {
succes ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
// console.log( messages.join('') )
process.stdout.write( messages.join('') )
}
if(code !== 0) return reject(code)
resolve(true) resolve(true)
}); });
} }

+ 4
- 1
package.json View File

}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
"license": "ISC"
"license": "ISC",
"dependencies": {
"tree-kill": "^1.2.2"
}
} }

+ 40
- 0
windowselevate.hta View File



<html><HTA:APPLICATION ID="windowselevate" icon="#"/>
<script>
//WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
// alert(windowselevate.commandLine)
var args = windowselevate.commandLine.split('"').slice(3);
// alert(args)
var processedargs = { _ : [] }
for(var item in args){
// alert(args[item].charAt(0))
args[item] ? args[item].charAt(0) === '-' ? processedargs[args[item].slice(2)] = args[item].split('=')[1] || true : processedargs._.push(args[item]) : null
}
// args = args.forEach(function(item){ })
// alert('processedargs._ : ' + processedargs._);
// alert(processedargs.runas);
var shell = new ActiveXObject('shell.application');
shell.ShellExecute('node', 'elxr ' + processedargs._.join(' ') + ' --runas=true', '', 'runas', 1);
var fso = new ActiveXObject('Scripting.FileSystemObject');
window.onload = function() {
document.body.style.backgroundColor = 'black';
document.body.style.fontFamily = 'arial';
var log = document.createElement('div');
function l(msg){ log.innerHTML+= msg; };
log.style.color = 'blue';
log.id = 'log';
document.body.appendChild(log);
log.innerHTML='Please Wait ';
var timer = function(){
l('.');
if(fso.FileExists("run.done")) close();
else window.setTimeout(timer, 1000);
};
window.setTimeout(timer, 3000);
};
</script>
</html>

Loading…
Cancel
Save