2011-01-25 109 views

回答

11

您可以執行id命令並讀取結果。

例如:

$ id -u jigar

輸出:

可以執行命令通過

try { 
    String userName = System.getProperty("user.name"); 
    String command = "id -u "+userName; 
    Process child = Runtime.getRuntime().exec(command); 

    // Get the input stream and read from it 
    InputStream in = child.getInputStream(); 
    int c; 
    while ((c = in.read()) != -1) { 
     process((char)c); 
    } 
    in.close(); 
} catch (IOException e) { 
} 

source

+0

如果您執行「id -n」 – 2011-01-25 16:42:19

+1

`id -u `將只會打印UID,解析起來會容易得多。 – dogbane 2011-01-25 16:44:05

2

如果你能夠影響Java虛擬機是如何啓動的,你可以切換的UID作爲用戶屬性:

java -Duserid=$(id -u) CoolApp 

在你CoolApp,你可以簡單地取ID:

System.getProperty("userid"); 

問候,

馬丁。

1

只需打開/etc/passwd文件並搜索用戶等於System.getProperty("user.name")的行。

1

另一種選擇是使用JNI調用getuid()。