有沒有辦法在使用java的Linux機器上獲取用戶的UID?我知道System.getProperty("user.name");
方法,但它返回的用戶名,我在尋找UID。有沒有辦法在使用java的Linux機器上獲取用戶的UID?
8
A
回答
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) {
}
2
如果你能夠影響Java虛擬機是如何啓動的,你可以切換的UID作爲用戶屬性:
java -Duserid=$(id -u) CoolApp
在你CoolApp,你可以簡單地取ID:
System.getProperty("userid");
問候,
馬丁。
1
只需打開/etc/passwd
文件並搜索用戶等於System.getProperty("user.name")
的行。
1
另一種選擇是使用JNI調用getuid()。
如果您執行「id -n」 – 2011-01-25 16:42:19
`id -u`將只會打印UID,解析起來會容易得多。 –
dogbane
2011-01-25 16:44:05