java SSH 远程操作

public class RmtShellExecutor {
private static Logger logger = Logger.getLogger(RmtShellExecutor.class);
private static Connection conn;
private static String ip;
private static String usr;

private static boolean connection() throws IOException, URISyntaxException {
try {
conn = new Connection(ip);
conn.connect();
} catch (IOException e) {
logger.error("Login remote machine failed" + ip, e);
throw new IOException("Login remote machine failed" + ip, e);
}
return conn.authenticateWithPublicKey(usr, new File(RmtShellExecutor.class.getClassLoader().getResource("id_rsa").toURI())
, null);
}

public static Map<String, Object> exec(String ipStr, String userNameStr, String cmds) throws Exception {
ip = ipStr;
usr = userNameStr;
Map<String, Object> map = new HashMap<String, Object>();
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
try {
if (connection()) {
Session session = conn.openSession();
session.execCommand(cmds);
stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset);
stdErr = new StreamGobbler(session.getStderr());
outErr = processStream(stdErr, charset);
map.put(Constants.STATUS, Constants.PROCESSING);
System.out.println("outStr=" + outStr);
System.out.println("outErr=" + outErr);
ret = session.getExitStatus();
} else {
logger.error("Login remote machine failed" + ip);
throw new Exception("Login remote machine failed" + ip);
}
} catch(Exception e){
logger.error("Login remote machine failed" + ip, e);
throw new Exception("Login remote machine failed" + ip, e);
} finally {
if (conn != null) {
conn.close();
}
IOUtils.closeQuietly(stdOut);
IOUtils.closeQuietly(stdErr);
}
return map;
}

public static String processStream(InputStream in, String charset) throws Exception {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
}
}