繁体   English   中英

操作系统使用Java登录和注销时间

[英]Operating System Log in and log out time using java

谁能帮助我知道如何使用java api检测系统登录和注销时间? 仅登录时的登录时间和系统关闭时的注销时间。 如果可能,der也可用于linux机器。

看看这个:

public static long getSystemUptime() throws Exception {
long uptime = -1;
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
    Process uptimeProc = Runtime.getRuntime().exec("net stats srv");
    BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
        if (line.startsWith("Statistics since")) {
            SimpleDateFormat format = new SimpleDateFormat("'Statistics since' MM/dd/yyyy hh:mm:ss a");
            Date boottime = format.parse(line);
            uptime = System.currentTimeMillis() - boottime.getTime();
            break;
        }
    }
} else if (os.contains("mac") || os.contains("nix") || os.contains("nux") || os.contains("aix")) {
    Process uptimeProc = Runtime.getRuntime().exec("uptime");
    BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
    String line = in.readLine();
    if (line != null) {
        Pattern parse = Pattern.compile("((\\d+) days,)? (\\d+):(\\d+)");
        Matcher matcher = parse.matcher(line);
        if (matcher.find()) {
            String _days = matcher.group(2);
            String _hours = matcher.group(3);
            String _minutes = matcher.group(4);
            int days = _days != null ? Integer.parseInt(_days) : 0;
            int hours = _hours != null ? Integer.parseInt(_hours) : 0;
            int minutes = _minutes != null ? Integer.parseInt(_minutes) : 0;
            uptime = (minutes * 60000) + (hours * 60000 * 60) + (days * 6000 * 60 * 24);
        }
    }
}
return uptime;
}

这将为您提供正常运行时间,因此请从当前时间中减去它。

如果系统是指操作系统,那么我建议您为此使用脚本,尤其是Linux。 例如,您可以使用文件〜/ .bashrc来检测登录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM