首页 > 技术文章 > 用Java修改Linux密码

WestContinent 2021-12-29 17:43 原文

最近因为测试服务器(Linux)的密码被某测试人员修改(安全管理不到位,痛苦)。导致这个测试服务器无法Login。

本来准备放弃了,格式化,重装,但是想到在这个环境上的诸多设置,什么NAS,FTP,语言环境,Websphere啥的,都要重新安装,还是稍微冷静了一下。

发现虽然root密码丢掉了,但是Webphere的管理Console依然可以正常访问,包括发布应用都可以正常执行,因此准备利用WebSphere发布一段执行Linux命令的Java程序修改密码。

首先,准备确认WebSphere的运行用户是什么。

这里使用了如下代码:

Process p = null;
        String s;
        try {
            p = Runtime.getRuntime().exec("whoami");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null) {
                System.out.println("line: " + s);
            }
            p.waitFor(10, TimeUnit.SECONDS);
            System.out.println("exit: " + p.exitValue());
        } catch (Exception e) {
            log.error("Error when running linux process.", e);
        } finally {
            if (p != null) {
                p.destroy();
            }
        }

结果很赞,在日志里输出了 “root”。(因为密码丢了,所以日志实在WebSphere的Console里看的。)

既然Websphere是root用户在执行,那就好办了,只要弄清楚如何在Java中执行linux修改密码的命令就可以了。

于是我运行了如下代码准备看看效果。

Process p = null;
        String s;
        try {
            p = Runtime.getRuntime().exec("passwd");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null) {
                System.out.println("line: " + s);
            }
            p.waitFor(10, TimeUnit.SECONDS);
            System.out.println("exit: " + p.exitValue());
        } catch (Exception e) {
            log.error("Error when running linux process.", e);
        } finally {
            if (p != null) {
                p.destroy();
            }
        }

结果是,process超时,标准输出没有任何内容,原因也在预料中,因为passwd命令会从pty读输入的新密码,所以,命令会卡住等待输入。

所以,执行如下语句可以完成对密码的修改。

Process p = null;
        String s;
        try {
            String[] cmd = {
                "/bin/sh",
                "-c",
                "echo \"newpassword\" | passwd \"root\" --stdin"
                };
            p = Runtime.getRuntime().exec(cmd);
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null) {
                System.out.println("line: " + s);
            }
            p.waitFor(10, TimeUnit.SECONDS);
            System.out.println("exit: " + p.exitValue());
        } catch (Exception e) {
            log.error("Error when running linux process.", e);
        } finally {
            if (p != null) {
                p.destroy();
            }
        }

将密码修改成 newpassword, 秘密在于  passwd 命令的 --stdin option 可以将密码输入重定向到标准输入。终于,root又可以Login进去了,这次要管好用户和密码!

 

推荐阅读