从Java运行linux suu命令-运行suu命令后无法运行任何其他命令

时间:2020-05-04 07:11:18

标签: java linux jsch

我从Java-

运行以下脚本后
suu -t -r "reason" <user_name>

它提示我输入密码,然后我输入了密码。 之后,程序正在运行,但没有执行任何其他命令。

我想通过Java(Jsch库)在Linux计算机上模拟。我没有收到任何错误,但是在输入密码后,成功登录,然后没有任何命令被执行。

这是我用来编写代码的链接- https://linuxconfig.org/executing-commands-on-a-remote-machine-from-java-with-jsch

运行suu命令后,我想读取一个文件。如果不运行suu,我将无法访问该路径。此问题的任何帮助将不胜感激:)

这是我的摘录- [![在此处输入图片描述] [1]] [1]

谢谢!

下面是我使用的代码-

public class SSHConn {

static Session session;
static String suCmds = "suu -t -u \"reason\" simba";
static String[] commands = {"whoami", suCmds};

public static void main(String[] args) throws Exception {
    open();
    runCmd(commands);
    close();
}

public static void runCmd(String[] commands) throws JSchException, IOException {
    for (String cmd : commands) {
        System.out.println("\nExecuting command: " + cmd);
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(cmd);
        InputStream in = channel.getInputStream();
        OutputStream out = channel.getOutputStream();
        channel.connect();
        //passing creds only when you switch user
        if (cmd.startsWith("suu -")) {
            System.out.println("Setting suPasswd now....");
            out.write((Constants.suPasswd + "\n").getBytes());
            out.flush();
            System.out.println("Flushed suPasswd to cli...");
        }
        captureCmdOutput(in, channel);
        channel.setInputStream(null);
        channel.disconnect();
    }
}

public static void captureCmdOutput(InputStream in, Channel channel) throws IOException {
    System.out.println("Capturing cmdOutput now...");
    byte[] tmp = new byte[1024];
    while (true) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0) {
                break;
            }
            System.out.print(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
            System.out.println(ee.getMessage());
        }
    }
}

public static void open() throws JSchException {
    JSch jSch = new JSch();
    session = jSch.getSession(Constants.userId, Constants.host, 22);
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.setPassword(Constants.userPasswd);
    System.out.println("Connecting SSH to " + Constants.host + " - Please wait for few seconds... ");
    session.connect();
    System.out.println("Connected!\n");
}

public static void close() {
    session.disconnect();
    System.out.println("\nDisconnected channel and session");
}}

0 个答案:

没有答案