As I am very new to haxe.
The following is my program in haxe where I am trying to retrieve the list of files opened in windows client. Openfiles is the command which gives the list of files opened in windows machine , which needs to be executed as an administrator. I am failing to execute the program which is giving no output.
class Hello {
public static function main() {
trace("Hello World!");
if(Sys.systemName()=="Windows"){
//var x = Sys.command("Openfiles",[]);
var output = new sys.io.Process("ipconfig", []).stdout.readAll().toString();
trace("output:::"+output);
}
if(Sys.systemName()=="Linux"){
//var x = Sys.command("Openfiles",[]);
var output = new sys.io.Process("ifconfig", []).stdout.readAll().toString();
trace("output:::"+output);
}
}
}
How to execute Openfiles system command as an administrator ?
for Linux you can do this:
var output = new Process("bash", ["-c 'echo rootS_PASswoRd | sudo -S ifconfig'"]).stdout.readAll().toString();
trace("output:::"+output);
Related
I have written a NodeJS command-line program with two modes:
mode foo: runs forever until the user presses Ctrl+C
mode bar: runs once
If the user is already running the program in mode foo, then running it again in mode bar will cause errors. Thus, when the user invokes mode bar, I want to search for all other existing copies of my command-line program that are running and kill them (as a mechanism to prevent the errors before they happen).
Getting a list of processes in NodeJS is easy, but that doesn't help me much. If I simply kill all other node processes, then I might be killing other programs that are not mine. So, I need to know which specific node processes are the ones running my app. Is it even possible to interrogate a process to determine that information?
Another option is to have my program write a temporary file to disk, or write a value to the Windows registry, or something along those lines. And then, before my program exists, I could clean up the temporary value. However, this feels like a precarious solution, because if my program crashes, then the flag will never be unset and will remain orphaned forever.
What is the correct solution to this problem? How can I kill my own application?
I was able to solve this problem using PowerShell:
import { execSync } from "child_process";
const CWD = process.cwd();
function validateOtherCopiesNotRunning(verbose: boolean) {
if (process.platform !== "win32") {
return;
}
// From: https://securityboulevard.com/2020/01/get-process-list-with-command-line-arguments/
const stdout = execPowershell(
"Get-WmiObject Win32_Process -Filter \"name = 'node.exe'\" | Select-Object -ExpandProperty CommandLine",
verbose,
);
const lines = stdout.split("\r\n");
const otherCopiesOfMyProgram= lines.filter(
(line) =>
line.includes("node.exe") &&
line.includes("myProgram") &&
// Exclude the current invocation that is doing a 1-time publish
!line.includes("myProgram publish"),
);
if (otherCopiesOfMyProgram.length > 0) {
throw new Error("You must close other copies of this program before publishing.");
}
}
function execPowershell(
command: string,
verbose = false,
cwd = CWD,
): string {
if (verbose) {
console.log(`Executing PowerShell command: ${command}`);
}
let stdout: string;
try {
const buffer = execSync(command, {
shell: "powershell.exe",
cwd,
});
stdout = buffer.toString().trim();
} catch (err) {
throw new Error(`Failed to run PowerShell command "${command}":`, err);
}
if (verbose) {
console.log(`Executed PowerShell command: ${command}`);
}
return stdout;
}
So I am witting a java program for interacting with filesystem.
Java program itself cannot run as super user. I created a special user for this program and gave it some special privileges to run some commands without password (via visudo file).
So I I'd like to check if a file exist. I used:
if(f.exists() && !f.isDirectory()) but the problem is this fails if I am checking if files exist that is read/write protected or if it belongs to another user.
That is why I need to use bash. for example, when I am retrieving information about file I use the following:
String[] command = new String[] { "sudo", "stat", filepath, "-c", "%F##%s##%U##%G##%X##%Y##%Z" };
process = runtime.exec(command); and then just parse the output.
For example moving a file I use this:
String[] command = new String[] {
"sudo",
"-u",
user,
"mv",
source,
target
};
So now I am looking for a way to get simple true/false response when checking if file exist.
I think I could use find command or something similar?
I've solved my issue by using the following command:
String[] command = new String[] { "sudo", "-u", user, "test", "-f", path };
Where user is user who I am running command as. And path is the path-to-file we are testing.
I then read the execute and read command's output in the code below.
I hope it helps someone someday...
process = runtime.exec(command);
errbr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((messageLine = errbr.readLine()) != null) {
message += messageLine + ";";
}
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((messageLine = br.readLine()) != null) {
message += messageLine;
}
Question
Is it possible to do the following?
open a new cmd.exe or terminal (on MacOS / Linux) window
pass / run a command, e.g. cd <path>
Problem
I can open cmd by running this command:
"$electron.shell.openItem('cmd.exe')"
But shell.openItem doesn't allow to pass the arguments / commands.
I tried using child_process but I couldn't make it work at all, it doesn't open a new terminal window:
const { spawn, exec } = require('child_process');
spawn('C:/Windows/System32/cmd.exe');
I also tried running the following command, but still nothing:
spawn( 'cmd.exe', [ '/c', 'echo ASDASD' ], { stdio: [0, 1, 2] } )
The only possible solution that I see is to create a command.bat:
start cmd.exe /K "cd /D C:\test"
And then use openItem:
"$electron.shell.openItem('command.bat')"
But that would only work on Windows
Solution
I finally found a way to do it on Windows:
var child_process = require('child_process');
child_process.exec("start cmd.exe /K cd /D C:/test");
Notes
You have to add the word start to open a new command window
Instead of cd /D C:/test you can specify any other command, e.g. python
/D is to make sure it will change the current drive automatically, depending on the path specified
/K removes the initial message
Don't use execSync it will lock the app until the terminal (command
prompt) window is closed
As for MacOS, looks like it's possible to do with osascript
osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down'
Here is a working example showing how to open a Terminal window at a specific path (~/Desktop for instance) on macOS, from a renderer script:
const { app } = require ('electron').remote;
const atPath = app.getPath ('desktop');
const { spawn } = require ('child_process');
let openTerminalAtPath = spawn ('open', [ '-a', 'Terminal', atPath ]);
openTerminalAtPath.on ('error', (err) => { console.log (err); });
It should be easy to adapt it to any selected atPath...
As for running other commands, I haven't found a way yet...
And here is the equivalent working code for Linux Mint Cinnamon or Ubuntu:
const { app } = require ('electron').remote;
const terminal = 'gnome-terminal';
const atPath = app.getPath ('desktop');
const { spawn } = require ('child_process');
let openTerminalAtPath = spawn (terminal, { cwd: atPath });
openTerminalAtPath.on ('error', (err) => { console.log (err); });
Please note that the name of the terminal application may be different, depending on the Linux flavor (for instance 'mate-terminal' on Linux Mint MATE), and also that the full path to the application can be explicitly defined, to be on the safe side:
const terminal = '/usr/bin/gnome-terminal';
HTH...
I have written a console application in mono for linux.
i have to start it with
"sudo mono app.exe"
Is there some posibility to restart the app when something happens.
For examlpe I run this app on the raspberry Pi, and when the app
detects some voltage on a special IO pin the app should restart automatically.
Please help me.
You can launch a new application instance using methods in the Process class and later exit.
http://www.dotnetperls.com/process-start
On Windows you can use cmd.exe to execute the script. In this blog post the author asks cmd to wait for a while, and then delete the executable,
http://blog.pedroliska.com/2010/05/20/c-self-destruct-windows-app/
You can use the same trick to restart the executable if on Windows.
var startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
var process = new Process();
process.StartInfo = startInfo;
process.Start();
// The delay is just making sure the exe to delete is done
// running.
var delayPings = 2;
var exeName = AppDomain.CurrentDomain.FriendlyName;
process.StandardInput.WriteLine("(ping -n " + delayPings + " 127.0.0.1) && (CALL " + exeName + ")");
Now for Linux, you just need to use bash (or another Shell) to replace cmd and also modify the command passed to it.
I have an .exe file which was written in C. It is a command line application. I want give command line and also get correspond output in this application through a C# application.
How do I invoke the command and get the output from C#?
You could use the Process.Start method:
class Program
{
static void Main()
{
var psi = new ProcessStartInfo
{
FileName = #"c:\work\test.exe",
Arguments = #"param1 param2",
UseShellExecute = false,
RedirectStandardOutput = true,
};
var process = Process.Start(psi);
if (process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
{
var result = process.StandardOutput.ReadToEnd();
Console.WriteLine(result);
}
}
}
You need to use the Process.Start method.
You supply it with the name of your process and any command line arguments and it will run the executable.
You can capture any output which you can then process in your C# application.