![](/img/trans.png)
[英]How to grant full permission to a folder to all users of a windows machine using java program?
[英]Using Java, How can I get a list of all local users on a windows machine
如何使用java列出在Windows機器(Win2000+)上配置的所有本地用戶。
如果可能的話,我更願意使用任何 java 2 com 橋接器或任何其他第三方庫來執行此操作。
最好使用 Java 的一些本機方法。
使用 Java-COM Bridge ,例如Jacob 。 然后選擇合適的 COM 庫,例如用於 WMI 的 COM API以列出本地用戶或任何其他 Windows 管理信息。
Win32_SystemUsers關聯 WMI 類將計算機系統和該系統上的用戶帳戶關聯起來。
Win32_Account抽象 WMI 類包含有關運行 Windows 的計算機系統已知的用戶帳戶和組帳戶的信息。 Windows NT 域識別的用戶名或組名是此類的后代(或成員)。
工作示例(jacob 1.17-M2,javaSE-1.6):
import java.util.Enumeration;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;
public class ComTst {
public static void main(String[] args) {
ComThread.InitMTA();
try {
ActiveXComponent wmi = new ActiveXComponent("winmgmts:\\\\.");
Variant instances = wmi.invoke("InstancesOf", "Win32_SystemUsers");
Enumeration<Variant> en = new EnumVariant(instances.getDispatch());
while (en.hasMoreElements())
{
ActiveXComponent bb = new ActiveXComponent(en.nextElement().getDispatch());
System.out.println(bb.getPropertyAsString("PartComponent"));
}
} finally {
ComThread.Release();
}
}
}
使用 Java COM 對象,即 Jacob:
public static void EnumerateUsers() {
String query = "SELECT * FROM Win32_UserAccount";
ActiveXComponent axWMI = new ActiveXComponent("winmgmts:\\");
Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));
EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
Dispatch item = null;
StringBuilder sb = new StringBuilder();
while (enumVariant.hasMoreElements()) {
item = enumVariant.nextElement().toDispatch();
sb.append("User: " + Dispatch.call(item, "Name")).toString();
System.out.println(sb);
sb.setLength(0);
}
}
我需要一個更簡單的解決方案。
這個實現將使用“ net user ”命令來獲取機器上所有用戶的列表。 這個命令有一些格式,在我的情況下我不關心,我只關心我的用戶是否在列表中。 如果有人需要實際的用戶列表,他可以解析“net user”的輸出格式來提取列表,而沒有“net use”生成的垃圾頁眉和頁腳
private boolean isUserPresent() {
//Load user list
ProcessBuilder processBuilder = new ProcessBuilder("net","user");
processBuilder.redirectErrorStream(true);
String output = runProcessAndReturnOutput(processBuilder);
//Check if user is in list
//We assume the output to be a list of users with the net user
//Remove long space sequences
output = output.replaceAll("\\s+", " ").toLowerCase();
//Locate user name in resulting list
String[] tokens = output.split(" ");
Arrays.sort(tokens);
if (Arrays.binarySearch(tokens, "SomeUserName".toLowerCase()) >= 0){
//We found the user name
return true;
}
return false;
}
方法 runProcessAndReturnOutput 運行進程,收集進程的 stdout 和 stderr 並將其返回給調用者。
import com.sun.jna.platform.win32.Netapi32Util;
Netapi32Util.User[] users = Netapi32Util.getUsers();
for(Netapi32Util.User user : users) {
System.out.println(user.name);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.