Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

when ssh with a low-privileged user, how to switch user with "su root" and execute command? #67

Open
1780spark opened this issue Feb 21, 2020 · 0 comments

Comments

@1780spark
Copy link

hi !
I want to use ExpectIt to achieve the following functions:
When using ssh remote linux service, log in with a low-privileged user, and then switch to a high-privileged user to execute related commands.

But the following code does not return relevant results:
JSch jSch = new JSch();
Session session = jSch.getSession("u1", "h1");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword("u1pdw");
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();

    Expect expect = new ExpectBuilder()
            .withOutput(channel.getOutputStream())
            .withInputs(channel.getInputStream(), channel.getExtInputStream())
            .build();
    try {
        expect.expect(contains("$"));
        System.out.println("login in with u1 and execute pwd command..");
        expect.sendLine("pwd");
        System.out.println(
                "pwd1:" + expect.expect(times(2, contains("\n")))
                        .getResults()
                        .get(1)
                        .getBefore());
        System.out.println("su to root.");
        expect.sendLine("su - root");
        System.out.println("su root:" + expect.expect(contains("(.+:)|(.+:)")).group(1));
        System.out.println("send password:");
        expect.sendLine("rootpwd");
        System.out.println(expect.expect(times(2, contains("#"))).getResults().get(1).getBefore());
        System.out.println("execute pwd wtih root...");
        expect.sendLine("pwd");
        // a regexp which captures the output of pwd
        System.out.println("pwd2:" + expect.expect(regexp("(?m)\\n([^\\n]*)\\n")).group(1));
        System.out.println("ls...");
        expect.expect(contains("$"));
        expect.sendLine("ls -l");
        // skipping the echo command
        expect.expect(times(2, contains("\n")));
        // getting the output of ls
        System.out.println("list ===== "+expect.expect(regexp(".*\\$")).getBefore().trim());
        expect.sendLine("exit");
    } finally {
        expect.close();
        channel.disconnect();
        session.disconnect();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant