天天看點

java中調用shell_怎樣在java代碼中調用執行shell腳本呀

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

java中調用shell_怎樣在java代碼中調用執行shell腳本呀

1092

2