JSch shell通道 - 断开连接后不会关闭

时间:2018-05-07 18:58:13

标签: java shell jsch

我正在使用JSch连接到远程计算机。为了重新启动服务,我需要拥有su权限,所以我使用的是shell通道而不是exec。我能够正常运行这些命令,但是一旦我断开了通道和会话,应用程序就会卡住并且执行不会继续。我需要Ctrl-C来杀死应用程序。

我的方法有什么不对吗?

public static void sendCommandWithSudo(String user, String pass, String ip, String command) {

    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, ip, 22);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        config.put("PreferredAuthentications", "password");
        session.setConfig(config);
        session.setPassword(pass);

        System.out.println("IP Address: " + ip);
        System.out.println("Username: " + user);
        System.out.println("Password: " + pass);
        System.out.println("Command issued: " + command);

        UserInfo ui = new MyUserInfo();
        session.setUserInfo(ui);

        session.connect();

        Channel channel = session.openChannel("shell");
        channel.setInputStream(System.in);
        channel.setOutputStream(System.out);
        PrintStream shellStream = new PrintStream(channel.getOutputStream());

        channel.connect(3*1000);

        List<String> commands = new ArrayList<String>();
        commands.add("sudo su - sudouser");
        commands.add(command);


        for(String cmd: commands) {
            shellStream.println(cmd);
            shellStream.flush();
        }

        Thread.sleep(5000);

        channel.disconnect();
        session.disconnect();

        shellStream.close();

    } catch (Exception e) {
        System.out.println("Exception caught: " + e.getMessage());
    }

}

1 个答案:

答案 0 :(得分:0)

回复自己: 两次添加退出命令似乎解决了这个问题:

commands.add("sudo su - sudouser");
commands.add(command);
commands.add("exit");
commands.add("exit");