上传下载文件到服务器

需要用到jar包:ganymed-ssh2-build210.jar


代码如下:

package easytest;
import java.io.IOException;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;


public class Send {

private static Logger log = LoggerFactory.getLogger(Send.class);
   private static String IP = "10.0.11.10";  //IP地址
   private static int PORT = 31575;               //ssh的端口号   
   private static String USER = "aaaa";        //登录用户名  
   private static String PASSWORD ="aaa";//用户密码
   private static Connection connection = new Connection(IP, PORT);  //创建连接
   *//** 
    * ssh用户登录验证,使用用户名和密码来认证 
    *  
    * @param user 
    * @param password 
    * @return 
    *//*  
   public static boolean isAuthedWithPassword(String user, String password) {  
       try {  
           return connection.authenticateWithPassword(user, password);  
       } catch (IOException e) {  
           e.printStackTrace();  
       }  
       return false;  
   }  
 
   public static boolean isAuth() {  
       
           return isAuthedWithPassword(USER, PASSWORD);  
      
   }  
   //下载文件
   public static void getFile(String remoteFile, String path) {  
       try {  
           connection.connect();  
           boolean isAuthed = isAuth();  
           if (isAuthed) {  
               System.out.println("认证成功!");  
               SCPClient scpClient = connection.createSCPClient();  
               scpClient.get(remoteFile, path);  
           } else {  
            log.info("用户连接"+"认证失败");
           }  
       } catch (IOException e) {  
           e.printStackTrace();  
       } finally {  
           connection.close();  
       }  
   }  
   //上传文件
   public static void putFile(String localFile, String remoteTargetDirectory) {  
       try {  
           connection.connect();  
           boolean isAuthed = isAuth();  
           if (isAuthed) {  
               SCPClient scpClient = connection.createSCPClient();  
               scpClient.put(localFile, remoteTargetDirectory);  
           } else {  
            log.info("用户连接"+"认证失败"); 
           }  
       } catch (Exception ex) {  
        log.info("上传数据"+ex);
       } finally {  
           connection.close();  
       }  
   }  
   //测试方法
public static void main(String[] args) {  
       try {  
           
           putFile("d://ss.txt", "........./webapps/ROOT/upload");  //第一个是要上传的文件路径    第二个参数是要在服务器存放文件的路径

       } catch (Exception e) {  
           e.printStackTrace();  
       } 

   }  



}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值