可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have the following code:
JSch jsch = new JSch(); jsch.setKnownHosts(dotSshDir + "/known_hosts"); jsch.addIdentity(dotSshDir + "/id_rsa"); Session session = jsch.getSession(userName, hostname, 22); session.connect(); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(System.err); Reader reader = new InputStreamReader(channel.getInputStream()); char[] buf = new char[1024]; int numRead; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); result.append(readData); buf = new char[1024]; }
It's hanging trying to read from the reader. How do I fix this? How do I go about hunting down what's happening?
回答1:
The hanging was actually due to some unbalanced quotes in the command.
For posterity, the final code (after dealing with some other issues) is:
public String call(String hostname, String[] argv) throws SubprocessException { StringBuffer result = new StringBuffer(); Session session = null; ChannelExec channel = null; try { // TODO: Emit friendly error if ~/.ssh doesn't exist. String dotSshDir = System.getProperty("user.home") + "/.ssh"; String userName = System.getProperty("user.name"); // TODO: Emit friendly error if ~/.ssh/known_hosts doesn't exist. jSch.setKnownHosts(dotSshDir + "/known_hosts"); // TODO: Emit friendly error if ~/.ssh/id_rsa doesn't exist. jSch.addIdentity(dotSshDir + "/id_rsa"); session = jSch.getSession(userName, hostname, 22); session.connect(); channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(Joiner.on(" ").join(argv)); channel.setInputStream(null); InputStream stdout = channel.getInputStream(); InputStream stderr = channel.getErrStream(); channel.connect(); waitForChannelClosed(channel); if (channel.getExitStatus() != 0) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stderr)); readAll(bufferedReader, result); throw new Exception(result.toString()); } else { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stdout)); readAll(bufferedReader, result); } } catch (Exception e) { throw new SubprocessException(e); } finally