java jsch远程执行shell脚本命令
2014-06-05 21:16
686 查看
由于需要远程监控一些Linux主机的运行情况,需要通过java远程执行一些shell脚本,并获取返回值,可以通过jsch实现
jsch jar包下载地址:http://sourceforge.net/projects/jsch/files/jsch.jar/0.1.51/jsch-0.1.51.jar/download
当然还可以通过sftp上传文件
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; }
相关文章推荐
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- windows 下 java程序jsch连接远程linux服务器执行shell命令
- JSch:纯JAVA实现远程执行SSH2主机的SHELL命令
- java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行
- java 使用jsch 远程链接linux执行命令
- Java 连接远程Linux 服务器执行 shell 脚本查看 CPU、内存、硬盘信息
- Java SSH远程执行Shell脚本实现(转)
- Ganymed SSH-2 for Java系列3之执行远程shell 命令
- Java SSH远程执行Shell脚本实现
- java 使用jsch 远程链接linux执行命令
- java 使用jsch 远程链接linux执行命令
- Java远程执行Shell命令
- Java SSH远程执行Shell脚本实现
- Java SSH远程执行Shell脚本实现
- Java SSH远程执行Shell脚本实现(转)
- java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行
- Ganymed SSH-2 for Java系列3之执行远程shell 命令