簡體   English   中英

無法在服務器上使用Java程序執行簡單的“ whoami” unix命令

[英]Unable to execute a simple “whoami” unix command using java program on the server

我面臨着一個奇怪的問題,即無法在AIX服務器上執行簡單的“ whoami” unix命令。 我有一個部署在AIX服務器上的Web應用程序。 現在,我想查看我的Web應用程序當前正在哪個WAS用戶下運行。 所以我添加了以下代碼:

    public String whoami() throws Exception {
        Process p = Runtime.getRuntime().exec("whoami");
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        String output = "";

        while ((line = in.readLine()) != null) {
            //System.out.println(line);
            output += line;
        }
        in.close();
        p.destroy();
        return output;
    }
}

上面的代碼被添加到JSP引用的jar文件中。 JSP必須接收上面代碼的輸出,並顯示WAS用戶名。 但是當我在服務器上部署Web應用程序並嘗試觀察輸出時,我收到了類似的錯誤消息

錯誤500:訪問被拒絕(java.io.FilePermission <>執行)

但是,當我刪除上述代碼並運行Web應用程序時,一切運行正常。 我在這里做什么? 我想念什么嗎? 請幫忙。 這是我第一次在UNIX上工作

您的Web服務器似乎已配置了禁止執行外部應用程序的Java安全策略。

有關Java安全策略的信息以及Web服務器的文檔,請參見http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html

您將需要提供(或編輯)策略文件以包含以下內容:

grant {
  permission java.io.FilePermission 
    "/usr/bin/whoami", "execute";
};

出於好奇,您是否考慮過使用:

user.name 

Java中的系統屬性?

AFAIK whoami是一個shell命令,並且Runtime#exec()僅執行程序。

您可以嘗試Runtime.getRuntime().exec(new String[]{"sh","-c","whoami"})調用sh並使其執行whoami

另一件事:閱讀后是否需要銷毀流程?

您可以使用ProcessBuilder類代替getRuntime().exec("whoami")

這是示例代碼

import java.io.*;
import java.util.*;

public class DoProcessBuilder {

    public static void main(String args[]) throws IOException {
        if (args.length <= 0) {
            System.err.println("Need command to run");
            System.exit(-1);
        }
        Process process = new ProcessBuilder(args).start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        System.out.printf("Output of running &#37;s is:", Arrays.toString(args));
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM