简体   繁体   English

如何以编程方式检查是否使用Java在ubuntu上安装了软件实用程序

[英]How to programatically check if a software utility is installed on ubuntu using Java

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); 我正在为自己的学习而研究Java项目,我所制作的是一个类,该类可以使用Runtime.getRuntime().exec(cmd);读取和写入外部进程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. 就像我使用sshpass实用程序远程登录到其他计算机一样,如果尚不存在,我想使用我的程序进行安装。 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, 像在Windows上一样,我认为有cmdline实用程序,例如ftype,assoc等,谢谢,

In Ubuntu/Debian you can use : 在Ubuntu / Debian中,您可以使用:

dpkg -s packagname

to see if a package is installed. 查看是否已安装软件包。 Then you can parse the output of the command in your app. 然后,您可以在应用程序中解析命令的输出。

If you already know the name of the software binary (which is usually the same to process name) you can use which command. 如果您已经知道软件二进制文件的名称(通常与进程名称相同),则可以使用which命令。

You can test it in bash/shell which firefox /usr/bin/firefox 您可以在bash / shell中测试它,Firefox是/ usr / bin / firefox

Also I can supply you an example written in C# of bash output reading: 我还可以提供一个用C#编写的bash输出示例:

string output = string.Empty; 字符串输出= string.Empty;

string output = string.Empty;

try
{
    // Sets up our process, the first argument is the command
    // and the second holds the arguments passed to the command
    ProcessStartInfo ps = new ProcessStartInfo("bash");
    ps.Arguments = "-c 'firefox'";
    ps.UseShellExecute = false;

    // Redirects the standard output so it reads internally in out program
    ps.RedirectStandardOutput = true;

    // Starts the process
    using (Process p = Process.Start(ps))
    {
        // Reads the output to a string
        output = p.StandardOutput.ReadToEnd();

        // Waits for the process to exit must come *after* StandardOutput is "empty"
        // so that we don't deadlock because the intermediate kernel pipe is full.
        p.WaitForExit();
    }
}
catch
{
    // TODO manage errors
}

If the bash output is multi-line you can pre-filter it by piping to the grep command: 如果bash输出为多行,则可以通过管道传输到grep命令对其进行预过滤:

ps.Arguments = "-c 'cpuid | grep MySearchTerm'";

EDIT 1: Reply to comments 编辑1:回复评论

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: 我试图创建一种解决方法,但是以下行中断了所有代码:

process = Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","'echo RIadminXsrv1 | sudo -S apt-get install telnet -qy'"});

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). 在终端中时,以下命令实际上将尝试安装telnet(您可能必须将用户插入/ etc / sudoers才能在PC上重现它)。

/bin/echo myUserPass | /usr/bin/sudo -S /usr/bin/apt-get install telnet -qy

In java it will simply print ( echo output) the remaining part of the command: 在Java中,它将仅打印( echo输出)命令的其余部分:

myUserPass | /usr/bin/sudo -S /usr/bin/apt-get install telnet -qy

This happens because we are simply executing /bin/echo command with a lot of parameters. 发生这种情况是因为我们只是在执行带有很多参数的/bin/echo命令。 I thought that it is possible to actually run the entire set of commands using bash: 我认为可以使用bash实际运行整个命令集:

bash -c '/bin/echo myUserPass | /usr/bin/sudo -S /usr/bin/apt-get install telnet -qy'

..but it's not, because bash -c '..' in Java doesn't work like it should. bash -c '..'但是不是,因为Java中的bash -c '..'无法正常工作。 It says that -c 'echo ...' script file can not be found, so I suppose that it misinterprets -c option. 它说找不到-c'echo ...'脚本文件,所以我想它会误解-c选项。 BTW I have never had this kind of problem in Mono C#. 顺便说一句,我从未在Mono C#中遇到过此类问题。

Here is the entire snippet: 这是整个代码段:

package javaapplication1;

import java.io.*;

public class JavaApplication1 {

    public static void main(String[] args) {

        Process process;
        String softwareToCheck = "telnet"; // Change here

        try
        {       
            if(!_softwareExists(softwareToCheck))
            {
                System.out.println("Installing missing software..");
                process = Runtime.getRuntime().exec(new String[]{"/bin/bash","-c","'echo RIadminXsrv1 | sudo -S apt-get install telnet -qy'"});

                try
                {
                    process.waitFor();
                }
                catch(InterruptedException e)
                {
                    System.out.println(e.getMessage());
                }

                if(!_softwareExists(softwareToCheck))
                {
                    System.out.println("Software is still missing!");
                }

            }
            else
            {
                System.out.println("Software is installed!");
            }
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }        
    }

    private static boolean _softwareExists(String binaryName) throws IOException
    {
        String line;
        ProcessBuilder builder;
        BufferedReader reader;
        Process process;

        builder = new ProcessBuilder("/usr/bin/which", binaryName);
        builder.redirectErrorStream(true);
        process = builder.start();
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        try
        {
            process.waitFor();
        }
        catch(InterruptedException e) {
            System.out.println(e.getMessage());
        }

        while ((line = reader.readLine ()) != null)
        {
            break; // Reads only the first line
        }

        return (line != null && !line.isEmpty());

    }
}

I am not aware of any tool that could help if package management tool does not report installation correctly. 如果软件包管理工具未正确报告安装,我不知道有任何工具可以提供帮助。 It could be that the some tools are installed but not updated the database. 可能是某些工具已安装但未更新数据库。

It may be useful to check if your target executable exists in any directories in $PATH and standard location. 检查目标可执行文件是否在$ PATH和标准位置的任何目录中可能很有用。

  String pathString = System.getenv("PATH");
   String[]  dirs= pathString.split(':');
   String[]  exes= { "name1", "name2" ....};

   for ( String exename : exes) {
     for ( String dirname : dirs) {
             File exeFile=new File( dirname, exename);
             //do some checks if file exists etc.
     }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Java以编程方式处理软件 - Handle a software programatically using java 如果在Ubuntu上安装了多个Java版本,如何检查Oracle Java版本 - How to check Oracle Java version if multiple versions of Java installed on Ubuntu 如何使用 Chef 检查 Java 是否安装在 Windows 上 - How to check if Java is installed on Windows using Chef 如何在ubuntu中安装Java软件的依赖关系? - how to install the dependencies for a java software in ubuntu.? 如何以编程方式使用Java安装所有Java JVM(不是默认值)? - How to programatically get all Java JVM installed (Not default one) using Java? 如何使用 C++ 语言以编程方式安装所有 Java JRE(JVM)及其路径? - How to programatically get all Java JRE(JVM) installed and its path using C++ language? 如何使用 java 程序在我的电脑中打开任何已安装的软件? - How do I open any installed software in my pc using a java program? 如何查看使用Java应用程序在Mac OS中安装的软件? - How can I see the software installed in a Mac OS using a java application? 我们可以列出使用JAVA操作系统中安装的软件吗 - can we list the software installed in the OS using JAVA 如何使用Code在浏览器中检查是否安装了Java插件。 - How to check whether Java plugins are installed or not in a browser using Code .?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM