我正在尝试使用 Jsch 编写 Java 程序,其中我想使用该程序开始执行 shell 脚本,并在 shell 脚本的执行完成后退出程序。
String userName = "";
String hostName = "";
String password = "";
JSch javaSecureChannel = new JSch();
Session jschSession = null;
Channel jschChannel = null;
try {
jschSession = javaSecureChannel.getSession(userName, hostName, 22);
Properties configurationProperties = new Properties();
configurationProperties.put("StrictHostKeyChecking", "no");
jschSession.setConfig(configurationProperties);
jschSession.setPassword(password);
jschSession.connect();
jschChannel = null;
jschChannel = jschSession.openChannel("shell");
jschChannel.setOutputStream(System.out);
File shellScript = createShellScript();
FileInputStream fin = new FileInputStream(shellScript);
byte fileContent[] = new byte[(int) shellScript.length()];
fin.read(fileContent);
InputStream in = new ByteArrayInputStream(fileContent);
jschChannel.setInputStream(in);
jschChannel.connect();
while(true){
//if(jschChannel.isClosed)
if(jschChannel.getExitStatus() == 0){
System.out.println("exit-status: " + jschChannel.getExitStatus());
break;
}
try{
Thread.sleep(1000);
}catch(Exception ee){
ee.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
jschChannel.disconnect();
jschSession.disconnect();
System.out.println("Done...!!!");
createShellScript 方法如下。
String temporaryShellFileName = "shellscript.sh";
File fileStream = new File(temporaryShellFileName);
try {
PrintStream outStream = new PrintStream(new FileOutputStream(fileStream));
outStream.println("#!/bin/bash");
outStream.println("cd /u01/app/java/gids4x/Test");
outStream.println("Test_with_NULL.sh");
outStream.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
使用上面的代码,我可以开始执行 shell 脚本。但是,即使在程序执行完成之后,即在脚本执行完成之后,我也不能终止程序执行。
你能建议具体需要做什么吗?