我正在尝试使用jsch
登录远程服务器并执行回显Hello World
的脚本。直接运行java代码时,此文件的输出不会打印到控制台,但是当我在调试模式中单步执行时,会打印该文件的输出。我的代码如下所示:
1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.io.InputStreamReader;
5 import java.util.List;
6
7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory;
9
10 import com.jcraft.jsch.Channel;
11 import com.jcraft.jsch.ChannelExec;
12 import com.jcraft.jsch.ChannelSftp;
13 import com.jcraft.jsch.JSch;
14 import com.jcraft.jsch.Session;
15
16 public class SSHUtility {
17
18 public static void main(String[] args) {
19 executeScript("user", "password", "127.0.0.1", 22, "/opt/helloworld.sh");
20 println "done"
21 }
22
23 public static void executeScript(String pUser, String pPassword, String pServer, int pPort, String pCommand) {
24 System.out.println("Executing on ssh");
25 try {
26 JSch lJSCH = new JSch();
27 Session lSession = lJSCH.getSession(pUser, pServer, pPort);
28 lSession.setConfig("StrictHostKeyChecking", "no");
29 lSession.setPassword(pPassword);
30 lSession.connect();
31
32 ChannelExec lChannelExec = (ChannelExec)lSession.openChannel("exec");
33
34 lChannelExec.setCommand(pCommand);
35 lChannelExec.setInputStream(null);
36 InputStream stdout = lChannelExec.getInputStream();
37 InputStream stderr = lChannelExec.getErrStream();
38 lChannelExec.connect();
39
40 waitForChannelClosed(lChannelExec);
41
42 int lExitStatus = lChannelExec.getExitStatus();
43
44 BufferedReader brStdOut = new BufferedReader(new InputStreamReader(stdout));
45 BufferedReader brStdErr = new BufferedReader(new InputStreamReader(stderr));
46
47 int brValue = 0;
48 while((brValue=brStdOut.read()) != -1)
49 {
50 char brChar = (char)brValue;
51 System.out.print(brChar); /***This is printed only in debug mode ***/
52 }
53
54 while((brValue=brStdErr.read()) != -1)
55 {
56 char brChar = (char)brValue;
57 System.out.print(brChar); /***This is printed only in debug mode ***/
58 }
59
60 if(lExitStatus < 0) {
61 LOGGER.info("Done, but exit status not set!");
62 }
63 else if(lExitStatus > 0) {
64 LOGGER.info("Done, but with error, exitStatus : " + lExitStatus);
65 }
66 else {
67 LOGGER.info("Script successfully executed : " + pCommand);
68 }
69
70 lChannelExec.disconnect();
71 lSession.disconnect();
72
73 }
74 catch(Exception e) {
75 LOGGER.info("Error executing script : " + pCommand);
76 }
77 }
78
79 private static void waitForChannelClosed(ChannelExec pChannel) throws IOException
80 {
81 InputStream lStdOut = pChannel.getInputStream();
82 byte[] buffer = null;
83 while(true)
84 {
85 while(lStdOut.available() > 0)
86 {
87 int i = lStdOut.read(buffer, 0, 1024);
88 if (i < 0) { break; }
89 System.out.print(new String(buffer, 0, i));//print response to console
90 }
91
92 if (pChannel.isClosed()) {//It is never closed
93 System.out.println("exit-status: " + pChannel.getExitStatus());
94 break;
95 }
96 try{Thread.sleep(1000);}catch(Exception ee){}
97 }
98 }
99 }
具体地,第51行和第57行的输出仅在调试模式下出现。但是当我运行程序时,它不会出现在控制台中。为什么这么奇怪的行为?