소스 검색

runas elevated refactor for windows

production
Pradeep Bhaskaran 4 년 전
부모
커밋
3df27b76ae
4개의 변경된 파일146개의 추가작업 그리고 40개의 파일을 삭제
  1. 1
    0
      .gitignore
  2. 101
    39
      index.js
  3. 4
    1
      package.json
  4. 40
    0
      windowselevate.hta

+ 1
- 0
.gitignore 파일 보기

@@ -0,0 +1 @@
/node_modules

+ 101
- 39
index.js 파일 보기

@@ -84,18 +84,26 @@ function any(iterable, continueOnFailure) {
);
}

var __isElevated = null;
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);
}


@@ -130,7 +138,7 @@ var gitRepos = [
, 'elixir-client-unlinked'
, 'ember-searchable-select'
, 'loopback-component-jsonapi'
, 'elixir-config'
, 'elixir-config-development'
, 'cihsr-config'
, 'cihsr-data'
, 'elixir-data'
@@ -147,12 +155,16 @@ var elevatedRunasRepos = [
, 'chess-server'
]

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

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

var op = {
'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
, 'undefined' : ()=>{ return op.h(); }
, 'upgrade' : ()=>{
console.log('upgrade.......')
var tasks = [
@@ -229,19 +241,48 @@ var __runcmd = function(label){
}
, 'runas' : ()=>{
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(()=>{
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`
}
);
).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' : ()=>{
@@ -326,19 +367,21 @@ var __runcmd = function(label){
var performPull = repo => {
if(existsSync(repo)) {
console.log('pulling ' + repo)
nodeShellExec('git', ['pull'], {
return nodeShellExec('git', ['pull'], {
inherit : true, shell: true,
cwd : repo
// , env: process.env
, runas : processedArgs.runas
, title : `git pull ${repo}`
}).catch((e)=>{ console.error(e) })
}
else {
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,
env: process.env
, runas : processedArgs.runas
, title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
}).catch((e)=>{ console.error(e) })
}
@@ -346,11 +389,21 @@ var __runcmd = function(label){

if(!processedArgs.runas) gitRepos.forEach(performPull)
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' : ()=>{
var tasks = [];
@@ -569,7 +622,7 @@ var __runcmd = function(label){
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
@@ -578,34 +631,43 @@ var __runcmd = function(label){
var mysql = '../xampp/mysql/bin/mysql'
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() {

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);

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 succes = true;
// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
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.pipe(process.stderr);
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)
});
}

+ 4
- 1
package.json 파일 보기

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

+ 40
- 0
windowselevate.hta 파일 보기

@@ -0,0 +1,40 @@


<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…
취소
저장