由於需要遠程監控一些Linux主機的運行情況,需要通過java遠程執行一些shell腳本,並獲取返回值,可以通過jsch實現
jsch jar包下載地址:http://sourceforge.net/projects/jsch/files/jsch.jar/0.1.51/jsch-0.1.51.jar/download
public static void SSHCommand(String host,String user,String pass,int port,String command){
JSch jsch = new JSch();
Session session=null;
Channel channel=null;
try {
session = jsch.getSession(user, host, port);
session.setPassword(pass);
session.setTimeout(2000);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("exec");
ChannelExec execChannel = (ChannelExec)channel;
execChannel.setCommand(command);
InputStream in = channel.getInputStream();
channel.connect();
StringBuffer sb = new StringBuffer();
int c = -1;
while((c = in.read()) != -1){
sb.append((char)c);
}
System.out.println("輸出結果是:"+sb.toString());
in.close();
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
channel.disconnect();
session.disconnect();
}
}
當然還可以通過sftp上傳文件
public static boolean upload(String host, String username, String password, int port, String location,File uploadFile){
Session session;
Channel channel;
Channel channelExec;
JSch jsch = new JSch();
try {
session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
ChannelSftp c = (ChannelSftp)channel;
c.cd(location);
c.put(new FileInputStream(uploadFile),uploadFile.getName());
//-------------------------
c.disconnect();
session.disconnect();
return true;
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
