JSch 是一个纯 Java 实现的 SSH2 客户端库,它允许 Java 应用程序通过 SSH 协议连接到 SSH 服务器,并执行命令、传输文件等。JSch 是基于 SSH-2 协议的一个开源项目,广泛用于需要远程执行命令或文件传输的 Java 应用程序中。
<dependency> <groupId>com.github.mwiede</groupId> <artifactId>jsch</artifactId> <version>0.2.19</version> </dependency>
public Session getSession(){ if( this.session != null ){ return this.session; } try { jsch.getSession(property.getUsername(), property.getHost(), property.getPort()); session = jsch.getSession(property.getUsername(), property.getHost(), property.getPort()); session.setPassword(property.getPassword()); session.setConfig("StrictHostKeyChecking","no");// 设置第一次登陆的时候提示 session.setConfig("max_input_buffer_size","1024");// Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); session.setConfig(sshConfig); session.connect(); return session; } catch (JSchException e) { throw new RuntimeException(e); } }
public static ChannelSftp getSftp(Session session){ try { Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; sftp.setFilenameEncoding("UTF-8"); return sftp; } catch (Exception e) { throw new RuntimeException(e); } }
public static ChannelExec getExec(Session session){ try { Channel channel = session.openChannel("exec");// channel.connect(); ChannelExec exec = (ChannelExec) channel; return exec; } catch (Exception e) { throw new RuntimeException(e); } }
public static void execCommand(ChannelExec exec,String command){ try { exec.setCommand(command); InputStream in = exec.getInputStream(); exec.connect(); BufferedReader inputReader = new BufferedReader(new InputStreamReader(in, "UTF8")); String inputLine; while ((inputLine = inputReader.readLine()) != null) { System.out.println(inputLine); } } catch (Exception e) { throw new RuntimeException(e); } finally { exec.disconnect(); } }
public static void fileDownload(ChannelSftp sftp, String path,String dist){ try { InputStream is = sftp.get(path); FileUtils.copyInputStreamToFile(is, FileUtils.getFile(dist,FilenameUtils.getName(path))); is.close(); } catch (SftpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static Session getSession(){ ConnectProperty property = new ConnectProperty(); property.setHost("..."); property.setPort(22); property.setUsername("..."); property.setPassword("..."); ConnectHelper helper = new ConnectHelper(property); return helper.getSession();}
public static void download(Session session){ ChannelSftp sftp = ConnectHelper.getSftp(session); ConnectHelper.fileDownload(sftp,"/home/test/1.txt","E://home//tmp");}
public static void execCommand(Session session){ ChannelExec exec = ConnectHelper.getExec(session); ConnectHelper.execCommand(exec, "pwd");
本文链接:http://www.28at.com/showinfo-26-112725-0.html还不会用Java操作远程服务器?
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com