java使用Jsch實現從linux服務端下載檔案
阿新 • • 發佈:2019-01-26
java利用Jsch實現從linux服務端下載檔案
直接貼程式碼,大家只需改下配置,且充分驗證可行。
吐槽下,網上這類文章很多,但是沒幾個能用的(基本都是少依賴的類檔案),真是坑啊!
1. 設計一個SshConfiguration類,如下:
package com.cheers.qa; public class SshConfiguration { private String host; private String username; private String password; private int port; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
2. 獲取linux服務端檔案程式碼如下:
package com.cheers.qa; import java.io.File; import java.util.Properties; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class TranscodingAnalyzerDemo { private ChannelSftp channelSftp; private Session session=null; private int timeout=60000; public TranscodingAnalyzerDemo(SshConfiguration conf) throws JSchException{ System.out.println("try connect to "+conf.getHost()+",username: "+conf.getUsername()+",password: "+conf.getPassword()+",port: "+conf.getPort()); JSch jSch=new JSch(); //建立JSch物件 session=jSch.getSession(conf.getUsername(), conf.getHost(), conf.getPort());//根據使用者名稱,主機ip和埠獲取一個Session物件 session.setPassword(conf.getPassword()); //設定密碼 Properties config=new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config);//為Session物件設定properties session.setTimeout(timeout);//設定超時 session.connect();//通過Session建立連線 } public void download(String src,String dst) throws JSchException, SftpException, InterruptedException{ //src linux伺服器檔案地址,dst 本地存放地址 //判斷 如果本地dst如果存在,則先刪除,然後在下載 File file = new File(dst); if(file.exists()) { file.delete(); Thread.sleep(1000); } channelSftp=(ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); channelSftp.get(src, dst); System.out.println(">>>>>>>>>> File:"+src+" has downloaded success!"); channelSftp.quit(); } public void close(){ session.disconnect(); } public static void main(String[] args) { SshConfiguration configuration=new SshConfiguration(); configuration.setHost("192.168.1.26"); configuration.setUsername("cheersqa"); configuration.setPassword("123456"); configuration.setPort(22); try{ TranscodingAnalyzerDemo sshUtil=new TranscodingAnalyzerDemo(configuration); sshUtil.download("/opt/cheerstest1/1111111111","logs1_26"); sshUtil.close(); }catch(Exception e){ e.printStackTrace(); } } }