在java中使用不同的用户调用外部进程 [英] Invoking an external process with a different user in java

查看:105
本文介绍了在java中使用不同的用户调用外部进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个作为Windows服务运行的java应用程序。一个特定的功能需要执行一个二进制文件,但是有一个不同的用户然后启动了应用程序。

We have a java application running as a windows service. A particular functionality needs to execute a binary but with a different user then which started the application.

我们有什么办法可以通过'Run as a不同的用户风格。

Is there any way by which we can invoke an exe with 'Run as a different user' style.

我检查了ProcessBuilder的API,但没有找到任何与用户相关的内容。是否有任何第三方工具来实现此目的。

I checked API of ProcessBuilder but didn't found anything related to user. Is there any 3rd party tool to achieve this.

推荐答案

您可以使用 PSExec 以不同的用户身份执行进程。命令行如下所示:

You can use PSExec to execute processes as a different user. The command line looks like:

psexec.exe -u username -p password mybinary.exe

然后你可以使用ProcessBuilder围绕此建立命令。

You can then use ProcessBuilder to build the command around this.

编辑:以下是如何执行此操作的示例:

here is an example of how you can do it:

public int startProcess(String username, String password, 
        String executable, String... args) throws IOException {

    final String psexec = "C:\\PsTools\\psexec.exe"; //psexec location

    //Build the command line
    List<String> command = new LinkedList<String>();
    command.add(psexec);

    if(username != null) {
        command.add("-u");
        command.add(username);
        command.add("-p");
        command.add(password);
    }

    command.add(executable);
    command.addAll(Arrays.asList(args));

    ProcessBuilder builder = new ProcessBuilder(command);
    Process process = builder.start();

    int returnCode;

    try {
        returnCode = process.waitFor();
    } catch (InterruptedException e) {
        returnCode = 1;
    }

    return returnCode;
}

然后您可以像这样使用它:

You can then use it like this:

startProcess("Bob", "Password", "Notepad.exe", "C:\\myfile.txt");

这篇关于在java中使用不同的用户调用外部进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆