Check if file exists using bash inside Java program? - linux

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

Related

NodeJS - How do I detect other copies of my program?

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

Haxe Run System Commands as an adminstrator

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

creating a password protected zip file using child process in nodejs

I have a very funny issue. I am spawning a child process in nodejs to create a zip password protected file. It is supposed to emulate the following command.
zip -P password -rf finalFileName.zip filePath
here is the code I wrote
function(password, zipName) {
let zip = spawn('zip', ['-P rolemodel','-rj', zipName, this.folderPath ]);
return this;
}
On unzipping the final zip file, I get an invalid password error.
Anything wrong that I am doing here ? I am however able to execute the command on the terminal and get the whole thing to work.
Maybe you can try to put every argument in quotes like following:
zip = spawn('zip',['-P', 'password' , '-rj', 'archive.zip', 'complete path to archive file']);
zip .on('exit', function(code) {
...// Do something with zipfile archive.zip
...// which will be in same location as file/folder given
});

Write to file via jenkins post-groovy script on slave

I'd like to do something very simple: Create/write to a file located in the remote workspace of a slave via the jenkins groovy post-build script plug-in
def props_file = new File(manager.build.workspace.getRemote() + "/temp/module.properties")
def build_num = manager.build.buildVariables.get("MODULE_BUILD_NUMBER").toInteger()
def build_props = new Properties()
build_props["build.number"] = build_num
props_file.withOutputStream { p ->
build_props.store(p, null)
}
The last line fails, as the file doesn't exist. I'm thinking it has something to do with the output stream pointing to the master executor, rather than the remote workspace, but I'm not sure:
Groovy script failed:
java.io.FileNotFoundException: /views/build_view/temp/module.properties (No such file or directory)
Am I not writing to the file correctly?
While writing onto slave you need to check the channel first and then you can successfully create a file handle and start reading or writing to that file:
if(manager.build.workspace.isRemote())
{
channel = manager.build.workspace.channel;
}
fp = new hudson.FilePath(channel, manager.build.workspace.toString() + "\\test.properties")
if(fp != null)
{
String str = "test";
fp.write(str, null); //writing to file
versionString = fp.readToString(); //reading from file
}
hope this helps!
Search for words The post build plugin runs on the manager and doing it as you say will fail if you are working with slaves! on the plugin page (the link to which you've provided) and see if the workaround there helps.
Does the folder /views/build_view/temp exist?
If not, you will need to do new File( "${manager.build.workspace.remote}/temp" ).mkdirs()

How to call C .exe file from C#?

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.

Resources