public static void execCmd(ExecTarget target, String cmd, ExecResultHandler handler,
String rsEncoding) throws IOException
{
AssertUtil.notNull(target, "SshTarget can not be null.");
AssertUtil.hasText(cmd, "ssh cmd must has text.");
String charset = StringTools.hasText(rsEncoding) ? rsEncoding : "UTF-8";
Session session = null;
Channel channel = null;
try
{
session = newSession(target);
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(cmd);
// æ¥æ¶é误信æ¯
PipedOutputStream errOut = new PipedOutputStream();
PipedInputStream errIn = new PipedInputStream(errOut);
((ChannelExec) channel).setErrStream(errOut);
// æ¥æ¶ç»æä¿¡æ¯
InputStream in = channel.getInputStream();
String uid = UUID.randomUUID().toString();
File file = new File(FileHelper.getTmpPath() + "/sshRs-" + uid + ".txt");
FileOutputStream fos = new FileOutputStream(file);
channel.connect();
FileCopyUtils.copy(in, fos);// å°ç»æåæ¾è³æ件
// å¤ææ¯å¦æ£å¸¸éåº
exitChannel(channel, errIn, charset);
errOut.close();
if (handler != null) handler.handle(file);
}
catch (JSchException e)
{
throw new IOException(e.getMessage());
}
catch (InterruptedException e)
{
logger.error(e.getMessage(), e);
}
finally
{
if (channel != null) channel.disconnect();
if (session != null) session.disconnect();
}
}
2011å¹´11æ28æ¥ 17:18
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yM3gzYklDZhJGZiJGZjdTY2E2YmhTZ3kjM3UGNjFTMi9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
1092
2