需要用到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();
}
}
}