Run Linux command from Angular 4 component - linux

Requirement is to fetch the output of a shell script's after running it from the Angular 4 component at the beginning during compilation i.e. just before the website is launched. I have already gone through the threads in stackoverflow i.e. 49700941 and 41637166.
From the first thread i tried to use the below code, but getting error:
Module not found: Error: Can't resolve 'child_process' in 'app/component ...'
const exec = require('child_process').exec; // Can't resolve 'child_process' error coming from this line
exec('/home/myDir/init_setup.sh', (err, stdout, stderr) => {
if (err){
console.error(err);
return;
};
console.log(stdout);
console.log(stderr);
/**
remaining logics
*/
});
Please let me know if I need to import some library explicitly or not to avoid this error.

The modern browsers opens the webpage in isolated sandbox so they have have no access to clients' computers.
Imagine the damage that could be done if a black hat could run batch script on computer that opens his webpage.
The only way to run the script is to run the desktop application on client's machine.
The example code you provided is Node.js code, the desktop framework that user have to install on his machine and run the code intentionally. There's (fortunately!) no way to run it remotely via webpage.

Related

Github Cli Command does not work with express js

In my backend express server , I am trying to execute a github cli command using execSync. But it hungs up there. The command is following:
`
execSsnc("gh auth login --web")
`
In the same machine, when I use terminal to execute the same command, it works fine. In fact, I have tried a executing this line of code in a simple nodejs project and this too works fine. But whenever I use this in my express server, it hungs up there. I have tried using spawn, exec, spawnSync too but no luck so far.
Also when I use execSync("gh auth status") this gives error saying there is no github hosts currently. But in the machine, when I run this command from the terminal, it says that I am already logged it using Personal Access Token. Thus I found that running the login command from the express server is the main issue. Is there any way out?
First, check if setting GH_DEBUG to 1 or api generates any verbose log which might shed some light to the issue.
const env = {
'env': {
'GH_DEBUG': 'api',
...process.env
}
}
exec('gh auth login --web', env, function (error, stdout, stderr){
console.log(stdout, stderr, error);
});
Second, check with another exec who you are when executed from Express.js, and compare it to your command-line environment (where it does work)
Using gh auth login --token < aTokenFile (passing the token as stdin to your execSync call) might be a better alternative than --web.
Note that execSync create a new shell and executes gh command in this shell.
Depending on the OS, the shell used by execSync might be different than the shell used in your terminal (bash/sh) or miss some env variables that are available in your terminal. This might explain why "gh auth status" execution shows different results.
Try to verify if the environment variables is your Express app are different than environment variables in your terminal

nodejs child_process spawn silently fails on windows

I'm wondering if anyone has had a similar problem with nodejs child_process spawn on windows.
I can no longer execute a nodejs script that calls child_proces.spawn. (This was working fine until yesterday, when suddenly node stopped working properly. No new software installed or anything that I am aware of that could have triggered this.) The call to spawn simply exits the process and fails with no error code, no error message, just exits silently.
My testcase script looks like this:
const { spawn } = require('child_process');
console.log('test 1');
try {
spawn('c:\\windows\\system32\\cmd.exe', ['/d', '/c', 'dir'], { stdio: 'inherit' });
console.log('test 2');
} catch (err) {
console.log('err', err);
}
The output looks like this:
PS C:\test> node .\index.js
test 1
PS C:\test>
Running nodejs v14.17.1 on Windows 10. (I've also tried with nodejs v10, v12, v14.15.1 and v16, both x86 and x64 varieties - there is no difference in behavior.) I've tried uninstalling nodejs and re-installing multiple times. I've tried with Powershell and with the windows Command Prompt.
I had this problem intermittently about 6 months ago and previously just rebooting windows seemed to clear this up. I'm guessing that something has been corrupted in the OS somehow.
Tracing through nodejs through the nodejs debug inspect shows it hits this line and then just quits silently when stepping into this line of code:
https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/child_process.js#L390
const err = this._handle.spawn(options);
I don't see anything odd/wrong in the options object and I've tried with various different environment variable settings for PATH, etc.
UPDATE:
Looks like things work fine if windows is started in safe mode or started with early launch anti-malware protection disabled. Now, I'm suspecting something with anti-virus software is interfering here.
Turns out some new anti-virus rules were blocking all processes attempting to spawn a new cmd.exe child process.

Node's spawn/exec not working when called from a scheduled Windows task

I'm facing a very odd issue where I have a Node script which invokes a process, it looks like this:
// wslPath declared here (it's a shell file)
const proc = cp.spawn('ubuntu.exe', ['run', wslPath]);
let stdout = '';
proc.stdout.on('data', data => stdout += data.toString());
let stderr = '';
proc.stderr.on('data', data => stderr += data.toString());
return await new Promise((resolve, reject) => {
proc.on('exit', async code => {
await fs.remove(winPath);
if (code) {
reject({ code, stdout, stderr });
}
resolve({ stdout, stderr });
});
});
As you can see, the script invokes WSL. WSL is enabled on the computer. When I run this script manually, it works fine. When I log in to the computer the script is at using RDP from another computer and run it with the same credentials, it works fine as well. But when the script is invoked from a scheduled task which also runs with the same credentials, the spawn call returns:
(node:4684) UnhandledPromiseRejectionWarning: Error: spawn UNKNOWN
at ChildProcess.spawn (internal/child_process.js:394:11)
at Object.spawn (child_process.js:540:9)
I verified the user is the same by logging require('os').userInfo() and require('child_process').spawnSync('whoami', { encoding: 'utf8' }) and it returns the same in all three cases.
I assume it is because ubuntu.exe is not being found, but I don't know why that would be as the user is the same in all three cases.
What could be the reason for this and how can I debug this further?
The Windows Task Scheduler allows you to specify a user to run as (for privilege reasons), but does not give you the environment (PATH and other environment variables) that are configured for that user.
So, when running programs from the Windows Task Scheduler, it's important to not make any assumptions about what's in the environment (particularly the PATH). If my program depends on certain things in the environment, I will sometimes change my Task to be a .BAT file that first sets up the environment as needed and then launch my program from there.
Among other things, the simplest way to not rely on the path is to specify the full path to the executable you are running rather than assuming it will be found in the path somewhere. But, you also need to make sure that your executable can find any other resources it might need without any environment variables or you need to configure those environment variables for it before running.

NativeScript: require('child_process') gives an error when running "tns run ios --emulator"

I have a experiment code like this just to test calling a child process from NativeScript app (myapp/app/views/login/login.js):
var exec = require('child_process').exec;
exec('ls', function (error, stdout, stderr) {
if(stdout){
console.log('stdout: ' + stdout);
}
if(stderr){
console.log('stderr: ' + stderr);
}
if (error !== null) {
console.log('Exec error: ' + error);
}
});
when I test this app with "tns run ios --emulator", it gives an error like this:
file:///app/views/login/login.js:1:89: JS ERROR Error: Could not find module 'child_process'. Computed path '/Volumes/xxxx/Users/xxxx/Library/Developer/CoreSimulator/Devices/392A8058-694B-4A5D-B194-DF935815ED21/data/Containers/Bundle/Application/2822CD65-4E4D-443C-8272-135DB09353FC/sampleGroceries.app/app/tns_modules/child_process'.
My question is: how can I resolve this? Should I do "npm install child_process" on the app's directory? But while I was searching for solutions on Google, I read that it should be naturally included from node_modules...
I find a child_process module in:
/usr/local/lib/node_modules/nativescript/lib/common
but as the error message says, it isn't included when I execute the app with tns command. Could someone tell me what I'm missing?
version info:
npm: 3.10.10
node: 7.2.1
tns: 2.4.2
The child_process that you are seeing is a wrapper in the NativeScript CLI for Node's child_process.
There is no child_process in NativeScript as the concept is not relevant in mobile environments (Android/iOS).
The reason Node JS works cross-platform for example, is because its engine has analogous feature implementation (file-system, http, child process) for each of the supported platforms.
Using node's child_process (installing it explicitly and requiring it) will likely not work, as there is no in-house implementation for mobile devices.
If you would like to perform something in the background, consider using NativeScript's Workers.
http://docs.nativescript.org/angular/core-concepts/multithreading-model.html
Edit:
If there isn't a plugin already that is readily available, you could use the underlying native API to call to the device's shell.
Android: execute shell command from android
iOS (Objective C): Cocoa Objective-C shell script from application?
Docs on the nativescript site are available that should help you in 'translating' objC/Java code to JavaScript, though it is pretty straightforward.
http://docs.nativescript.org/runtimes/android/marshalling/java-to-js
http://docs.nativescript.org/runtimes/ios/marshalling/Marshalling-Overview

Assistance with Node.js functions integration in Apache Linux

Here is a short overview to help you experts understand the situation I am in - sorry that its too verbose, but it might help resolving this issue:
So I have a Linux machine, and it runs Apache properly.
Under '/var/www/html', I put my project files which are HTML (index.html) , and a javaScript file with utility functions.
httpd runs and everyone can view the content when 'http:///index.html' from their PC's.
I want to run a bash script from my Linux machine by letting the users provide the parameters from the front end user interface.
Reading how to do that, I saw tons of examples of how node.js can do that, so I downloaded Node.JS to my Linux machine, and it can be run from:
"
~/Desktop/node-v4.2.1-linux-x64/bin/node --version
v4.2.1
~/Desktop/node-v4.2.1-linux-x64/bin/npm --version
2.14.7
"
So it seems like its properly installed...
Note: I did not put anything in my Linux path after extracting the node.js tar.gz file.
Now, from my Linux machine, under '/var/www/html' , I have an HTML file, and I created an 'onclick' event to invoke a javascript function, in which I wrote a call to run this bash script which is located in my Linux machine under "/" - here it is:
function start_run(pTopoFile, pEmailAddress) {
var childProcess = require('child_process');
var run_command;
run_command = childProcess.exec('/run.sh ' + pTopoFile + ' ' + pEmailAddress, function (error, stdout, stderr) {
if (error) {
console.log(error.stack);
console.log('Error code: '+error.code);
console.log('Signal received: '+error.signal);
}
console.log('Child Process STDOUT: '+stdout);
console.log('Child Process STDERR: '+stderr);
});
ls.on('exit', function (code) {
console.log('Child process exited with exit code '+code);
});
}
When I run the above I get this error:
"ReferenceError: require is not defined"
Which means that even though Node.js was installed properly (as I showed you above), I cannot access its methods from /var/www/html on my Linux machine ...
Can anyone let me know how to link between the great features that node.js has to my scripts?
I hope that I was clear enough with the info I provided...
Thanks,
Tom

Resources