Java JSch壳牌频道-韩元';断开后不要关闭

Java JSch壳牌频道-韩元';断开后不要关闭,java,shell,jsch,Java,Shell,Jsch,我正在使用JSch连接到远程机器。为了重新启动服务,我需要有su权限,所以我使用shell通道而不是exec。我可以很好地运行这些命令,但一旦我断开通道和会话,应用程序就会陷入困境,执行也不会向前推进。我需要按住Ctrl-C键才能终止该应用程序 我的方法有没有做错什么 public static void sendCommandWithSudo(String user, String pass, String ip, String command) { try { JS

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

}
公共静态void sendCommandWithSudo(字符串用户、字符串传递、字符串ip、字符串命令){
试一试{
JSch JSch=新的JSch();
Session Session=jsch.getSession(用户,ip,22);
属性配置=新属性();
配置放置(“检查”、“否”);
config.put(“首选身份验证”、“密码”);
session.setConfig(config);
session.setPassword(pass);
System.out.println(“IP地址:+IP”);
System.out.println(“用户名:“+用户”);
System.out.println(“密码:“+pass”);
System.out.println(“发出的命令:“+命令”);
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
Channel=session.openChannel(“shell”);
channel.setInputStream(System.in);
channel.setOutputStream(系统输出);
PrintStream shellStream=新的PrintStream(channel.getOutputStream());
通道连接(3*1000);
List命令=new ArrayList();
添加(“sudo su-sudouser”);
命令。添加(命令);
for(字符串cmd:commands){
shellStream.println(cmd);
shellStream.flush();
}
睡眠(5000);
通道断开();
session.disconnect();
shellStream.close();
}捕获(例外e){
System.out.println(“捕获异常:+e.getMessage());
}
}
回复我自己: 添加两次exit命令似乎可以解决此问题:

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