Java使用Sftp實現對跨服務器上傳、下載、打包、寫入相關操做

一、Maven引入jarjava

<dependency>
     <groupId>com.jcraft</groupId>
     <artifactId>jsch</artifactId>
     <version>0.1.54</version>
 </dependency>

二、Test類linux

package com.tandaima.pub; import java.io.*; import java.util.Properties; import com.jcraft.jsch.*; /** * User longpizi * Date: 2019/10/30 * Time: 14:40 */
public class SftpUtil { public static final String CHANNELTYPE_SFTP="sftp"; public static final String CHANNELTYPE_EXEC="exec"; private Session session;//會話
    private Channel channel;//鏈接通道
    private ChannelSftp sftp;// sftp操做類
    private JSch jsch; protected static String host=getLinuxParam()[0]; protected static String port=getLinuxParam()[1]; protected static String user=getLinuxParam()[2]; protected static String password=getLinuxParam()[3]; private static String[] getLinuxParam(){ Properties props=new Properties();//讀取文件類型建立對象。
        try { ClassLoader classLoader = SftpUtil.class.getClassLoader();// 讀取屬性文件
            InputStream in = classLoader.getResourceAsStream("linux.properties"); props.load(in); /// 加載屬性列表
            if(in!=null){ in.close(); } } catch (Exception e) { System.out.println("Linux鏈接參數異常:"+e.getMessage()); } String[] str={"","","",""}; str[0]=props.getProperty("file.host"); str[1]=props.getProperty("file.port"); str[2]=props.getProperty("file.user"); str[3]=props.getProperty("file.password"); return str; } /** * 斷開鏈接 */
    public static void closeConnect(Session session, Channel channel, ChannelSftp sftp){ if (null != sftp) { sftp.disconnect(); sftp.exit(); sftp = null; } if (null != channel) { channel.disconnect(); channel = null; } if (null != session) { session.disconnect(); session = null; } System.out.println("鏈接已關閉"); } /** * 鏈接ftp/sftp服務器 * * @param sftpUtil 類 */
    public static void getConnect(SftpUtil sftpUtil,String openChannelType) throws Exception { Session session = null; Channel channel = null; JSch jsch = new JSch(); session = jsch.getSession(user, host, Integer.parseInt(port)); session.setPassword(password); // 設置第一次登錄的時候提示,可選值:(ask | yes | no) // 不驗證 HostKey
        session.setConfig("StrictHostKeyChecking", "no"); try { session.connect(); } catch (Exception e) { if (session.isConnected()) session.disconnect(); System.out.println("鏈接服務器失敗"); } channel = session.openChannel(openChannelType); try { channel.connect(); } catch (Exception e) { if (channel.isConnected()) channel.disconnect(); System.out.println("鏈接服務器失敗"); } sftpUtil.setJsch(jsch); if(openChannelType.equals(CHANNELTYPE_SFTP)){ sftpUtil.setSftp((ChannelSftp) channel); } sftpUtil.setChannel(channel); sftpUtil.setSession(session); } /** * 上傳文件 * * @param directory 上傳的目錄-相對於SFPT設置的用戶訪問目錄 * @param uploadFile 要上傳的文件全路徑 */
    public static boolean upload(String directory, String uploadFile) { boolean resultState=false; SftpUtil sftpUtil = new SftpUtil(); try{ getConnect(sftpUtil,CHANNELTYPE_SFTP);//創建鏈接
            Session session = sftpUtil.getSession(); Channel channel = sftpUtil.getChannel(); ChannelSftp sftp = sftpUtil.getSftp();// sftp操做類
            try { sftp.cd(directory); //進入目錄
            } catch (SftpException sException) { if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) { //指定上傳路徑不存在
                    sftp.mkdir(directory);//建立目錄
                    sftp.cd(directory);  //進入目錄
 } } File file = new File(uploadFile); InputStream in = new FileInputStream(file); sftp.put(in, file.getName()); in.close(); closeConnect(session, channel, sftp); resultState=true; }catch (Exception e){ System.out.println("上傳文件異常"); } return resultState; } /** * 獲取已鏈接的Sftp * @return SftpUtil */
    public static SftpUtil getConnectSftp(){ SftpUtil sftpUtil=new SftpUtil(); try { getConnect(sftpUtil,CHANNELTYPE_SFTP);//創建鏈接
          return sftpUtil; }catch (Exception e){ System.out.println("下載文件異常"); } return null; } /** * 刪除文件 * @param directory 要刪除文件所在目錄 * @param deleteFile 要刪除的文件 */
    public static boolean delete(String directory, String deleteFile){ boolean resultState=false; SftpUtil sftpUtil=new SftpUtil(); try { getConnect(sftpUtil,CHANNELTYPE_SFTP);//創建鏈接
            Session session = sftpUtil.getSession(); Channel channel = sftpUtil.getChannel(); ChannelSftp sftp = sftpUtil.getSftp();// sftp操做類
            sftp.cd(directory); //進入的目錄應該是要刪除的目錄的上一級
            sftp.rm(deleteFile);//刪除目錄
 closeConnect(session,channel,sftp); resultState=true; }catch (Exception e){ System.out.println("刪除文件異常"); } return resultState; } /** JSch有三種文件傳輸模式: (1)OVERWRITE:徹底覆蓋模式。JSch的默認文件傳輸模式,傳輸的文件將覆蓋目標文件。 (2)APPEND:追加模式。若是目標文件已存在,則在目標文件後追加。 (3)RESUME:恢復模式。若是文件正在傳輸時,因爲網絡等緣由致使傳輸中斷,則下一次傳輸相同的文件 時,會從上一次中斷的地方續傳。 */
    /** * 追加文件內容 * @param remoteFile 原文件路徑 * @param in 追加內容 * @return true成功,false失敗 */
    public static boolean appendFileContent(String remoteFile, InputStream in){ boolean resultState=false; SftpUtil sftpUtil = new SftpUtil(); try{ getConnect(sftpUtil,CHANNELTYPE_SFTP);//創建鏈接
            Session session = sftpUtil.getSession(); Channel channel = sftpUtil.getChannel(); ChannelSftp sftp = sftpUtil.getSftp();// sftp操做類
            OutputStream out = sftp.put(remoteFile, ChannelSftp.APPEND); int bufferSize=1024; byte[] buff = new byte[bufferSize]; // 設定每次傳輸的數據塊大小
            int read; if (out != null) { do { read = in.read(buff, 0, buff.length); if (read > 0) { out.write(buff, 0, read); } out.flush(); } while (read >= 0); } if(out!=null){ out.close(); } closeConnect(session, channel, sftp); resultState=true; }catch (Exception e){ System.out.println("寫入文件異常"); } return resultState; } /** * 建立文件 * @param fileDir 文件路徑 * @param fileName 文件名稱 * @return
     */
    public static boolean createFile(String fileDir,String fileName){ try{ execute("mkdir -p "+fileDir+"\n" +
                    "touch "+fileDir+"/"+fileName); }catch (Exception e){ return false; } return true; } /** * 建立文件夾 * @param fileDir 文件路徑 * @return true成功/false失敗 */
    public static boolean createFileDir(String fileDir){ try{ execute("mkdir -p "+fileDir+""); }catch (Exception e){ return false; } return true; } /** * 壓縮文件夾爲ZIP * @param fileDir 文件路徑 * @param fileName 文件名稱 * @param additionalName 壓縮附加名 * @return
     */
    public static boolean zipDir(String fileDir,String fileName,String additionalName){ try{ execute("cd "+fileDir+"\n" +
                    "zip  -r "+fileDir+"/"+fileName+additionalName+".zip "+fileName); }catch (Exception e){ return false; } return true; } /** * 獲取文件大小 單位(K) * @param fileDir 文件路徑 * @return 文件大小 */
    public static long getFileSize(String fileDir){ return Long.parseLong(execute("ls -l "+fileDir+" | awk '{ print $5 }'")); } /** * 執行liunx 命令 * @param command 命令內容 * @return 命令輸出 */
    private static String execute(String command){ SftpUtil sftpUtil=new SftpUtil(); StringBuffer strBuffer=new StringBuffer(); try { getConnect(sftpUtil,CHANNELTYPE_EXEC); // Create and connect session.
            Session session = sftpUtil.getSession(); // Create and connect channel.
            Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); BufferedReader input = new BufferedReader(new InputStreamReader(channel .getInputStream())); channel.connect(); System.out.println("命令: " + command); // 獲取命令的輸出
 String line; while ((line = input.readLine()) != null) { strBuffer.append(line); } input.close();
            closeConnect(session,channel,null); } catch (Exception e) {
 e.printStackTrace(); } return strBuffer.toString(); } // public static void main(String[] args) throws FileNotFoundException { // String window_dir="C:\\Users\XXX\\Desktop\\test\\test.txt"; // String liunx_dir="/usr/local/longpizi"; // try { //// System.out.println(upload(liunx_dir,window_dir)); //// System.out.println(download(liunx_dir,"test.txt","C:\\Users\\XXX\\Desktop\\test")); //// System.out.println(delete(liunx_dir,"test.txt")); // //// InputStream inputStream = new ByteArrayInputStream("this is test".getBytes()); //// System.out.println(appendFileContent(liunx_dir+"/test.txt",inputStream)); // //// String command="touch /usr/local/longlin/longpizi.sh\nmkdir -p sss"; //// System.out.println(execute(command)); // //// System.out.println(createFile("/usr/local/longlin/test/sfdsfdf","sss.txt")); // } catch (Exception e) { // e.printStackTrace(); // } // }

    public JSch getJsch() { return jsch; } public  void setJsch(JSch jsch) { this.jsch = jsch; } public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } public Channel getChannel() { return channel; } public void setChannel(Channel channel) { this.channel = channel; } public ChannelSftp getSftp() { return sftp; } public void setSftp(ChannelSftp sftp) { this.sftp = sftp; } }
相關文章
相關標籤/搜索