I am working on a Java Project for my own learning, what i have made is a class which can both read and write to external process using Runtime.getRuntime().exec(cmd);
Now i was wondering is there any special way of checking if a particular software/tool is installed on the system.
Like i use sshpass utility to remotely login to other machines, and if it is not there already i would like to install it using my program. But for this how should i go about checking if it exists there or not?
The idea i have in my mind is to run the command and see the response, if the returned string matches particular expression based on that i would decide it’s existence or non-existence.
Do you think it is the right approach or is there any other way to find out this?
Like on windows, i think there are cmdline utilities like ftype, assoc etc,
thank you,
If you already know the name of the software binary (which is usually the same to process name) you can use
whichcommand.You can test it in bash/shell
which firefox
/usr/bin/firefox
Also I can supply you an example written in C# of bash output reading:
string output = string.Empty;
If the bash output is multi-line you can pre-filter it by piping to the grep command:
EDIT 1: Reply to comments
The major problem is the software installation, which requires “administrative” rights.
I’ve tried to create a workaround, but the following line breaks all code:
While in terminal the following command will actually attempt to install telnet (you might have to insert your user into /etc/sudoers to reproduce it on your PC).
/bin/echo myUserPass | /usr/bin/sudo -S /usr/bin/apt-get install telnet -qyIn java it will simply print (
echooutput) the remaining part of the command:myUserPass | /usr/bin/sudo -S /usr/bin/apt-get install telnet -qyThis happens because we are simply executing
/bin/echocommand with a lot of parameters.I thought that it is possible to actually run the entire set of commands using bash:
..but it’s not, because
bash -c '..'in Java doesn’t work like it should. It says that -c ‘echo …’ script file can not be found, so I suppose that it misinterprets -c option.BTW I have never had this kind of problem in Mono C#.
Here is the entire snippet: