【问题标题】:JSch shell channel - Won't close after disconnectingJSch shell 通道 - 断开连接后不会关闭
【发布时间】:2018-05-07 18:58:12
【问题描述】:

我正在使用 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());
    }

}

【问题讨论】:

    标签: java shell jsch


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2015-08-04
      • 1970-01-01
      相关资源
      最近更新 更多