在java中获取登录用户名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/797549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get login username in java
提问by George Profenza
How can I get the username/login name in Java?
如何在 Java 中获取用户名/登录名?
This is the code I have tried...
这是我试过的代码...
try{
LoginContext lc = new LoginContext(appName,new TextCallbackHandler());
lc.login();
Subject subject = lc.getSubject();
Principal principals[] = (Principal[])subject.getPrincipals().toArray(new Principal[0]);
for (int i=0; i<principals.length; i++) {
if (principals[i] instanceof NTUserPrincipal || principals[i] instanceof UnixPrincipal) {
String loggedInUserName = principals[i].getName();
}
}
}
catch(SecurityException se){
System.out.println("SecurityException: " + se.getMessage());
}
I get a SecurityExceptionwhen I try to run this code. Could someone please tell me whether I'm heading in the right direction, and help me to understand the problem.
SecurityException当我尝试运行此代码时,我得到了一个。有人可以告诉我我是否朝着正确的方向前进,并帮助我理解问题。
采纳答案by dfa
System.getProperty("user.name")
回答by newacct
in Unix:
在Unix中:
new com.sun.security.auth.module.UnixSystem().getUsername()
in Windows:
在 Windows 中:
new com.sun.security.auth.module.NTSystem().getName()
in Solaris:
在 Solaris 中:
new com.sun.security.auth.module.SolarisSystem().getUsername()
回答by pdjota
System.getProperty("user.name") is not a good security option since that environment variable could be faked: C:\ set USERNAME="Joe Doe" java ... // will give you System.getProperty("user.name") You ought to do:
System.getProperty("user.name") 不是一个好的安全选项,因为该环境变量可能是伪造的: C:\ set USERNAME="Joe Doe" java ... // will give you System.getProperty("user.名称”)你应该这样做:
com.sun.security.auth.module.NTSystem NTSystem = new com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());
JDK 1.5 and greater.
JDK 1.5 及更高版本。
I use it within an applet, and it has to be signed. info source
我在小程序中使用它,并且必须对其进行签名。 信息来源
回答by celsowm
inspired by @newacct's answer, a code that can be compiled in any platform:
受到@newacct回答的启发,一个可以在任何平台上编译的代码:
String osName = System.getProperty( "os.name" ).toLowerCase();
String className = null;
String methodName = "getUsername";
if( osName.contains( "windows" ) ){
className = "com.sun.security.auth.module.NTSystem";
methodName = "getName";
}
else if( osName.contains( "linux" ) ){
className = "com.sun.security.auth.module.UnixSystem";
}
else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){
className = "com.sun.security.auth.module.SolarisSystem";
}
if( className != null ){
Class<?> c = Class.forName( className );
Method method = c.getDeclaredMethod( methodName );
Object o = c.newInstance();
System.out.println( method.invoke( o ) );
}
回答by Newtoxton
The 'set Username="Username" 'is a temporary override that only exists as long as the cmd windows is still up, once it is killed off, the variable loses value. So i think the
在“设置用户名=‘用户名’”是临时替代,只有作为CMD窗口仍上涨,一旦它被消灭后,变量失去值,只要存在。所以我认为
System.getProperty("user.name");
System.getProperty("用户名");
is still a short and precise code to use.
仍然是一个简短而精确的代码。
回答by Dragos Roban
System.getenv().get("USERNAME");- works on windows !
System.getenv().get("USERNAME");- 适用于窗户!
In environment properties you have the information you need about computer and host! I am saying again! Works on WINDOWS !
在环境属性中,您可以获得有关计算机和主机的信息!我再说一遍!适用于WINDOWS!
回答by ANTARA
Using JNA its simple:
使用 JNA 很简单:
String username = Advapi32Util.getUserName();
System.out.println(username);
Advapi32Util.Account account = Advapi32Util.getAccountByName(username);
System.out.println(account.accountType);
System.out.println(account.domain);
System.out.println(account.fqn);
System.out.println(account.name);
System.out.println(account.sidString);
回答by Deepak
Below is a solution for WINDOWS ONLY
以下是仅适用于 WINDOWS 的解决方案
In cases where the application (like Tomcat) is started as a windows service, the System.getProperty("user.name") or System.getenv().get("USERNAME") return the user who started the service and not the current logged in user name.
在应用程序(如 Tomcat)作为 Windows 服务启动的情况下, System.getProperty("user.name") 或 System.getenv().get("USERNAME") 返回启动服务的用户而不是当前登录的用户名。
Also in Java 9 the NTSystem etc classes will not be accessible
同样在 Java 9 中,将无法访问 NTSystem 等类
So workaround for windows: You can use wmic, so you have to run the below command
因此 Windows 的解决方法:您可以使用wmic,因此您必须运行以下命令
wmic ComputerSystem get UserName
If available, this will return output of the form:
如果可用,这将返回以下形式的输出:
UserName
{domain}\{logged-in-user-name}
Note: For windows you need to use cmd /c as a prefix, so below is a crude program as an example:
注意:windows 需要使用 cmd /c 作为前缀,下面以粗略的程序为例:
Process exec = Runtime.getRuntime().exec("cmd /c wmic ComputerSystem get UserName".split(" "));
System.out.println(exec.waitFor());
try (BufferedReader bw = new BufferedReader(new InputStreamReader(exec.getInputStream()))) {
System.out.println(bw.readLine() + "\n" + bw.readLine()+ "\n" + bw.readLine());
}

