pom文件:
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>261</version>
</dependency>
连接远程服务器:
package com.heiheihaxi.jszxdemo2.utils;
import ch.ethz.ssh2.Connection;
public class SCPClientUtil {
private static Connection conn=null;
public static Connection getConnection(){
String hostname="xxx.xxx.xxx.xxx";// ip地址
String username="xxxx";// 用户名
String password="xxxx";// 密码
int port=22;// 端口
conn = new Connection(hostname, port);
try {
// 连接到主机
conn.connect();
// 使用用户名和密码校验
boolean isconn = conn.authenticateWithPassword(username, password);
if (!isconn) {
System.out.println("用户名称或者是密码不正确");
return null;
} else {
System.out.println("远程服务器连接成功.");
return conn;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
根据现在文件名获取最新的文件
public void getFiles(Connection connection, String fileName) throws IOException {
if (connection != null) {
Session ss = null;
List<String> lists=new ArrayList<>();
try {
SCPClient scpClient = connection.createSCPClient();
Session session = connection.openSession();
session.execCommand("ls /home/test/file_*"); //进入目录
//显示执行命令后的信息
System.out.println("连接远程服务器成功");
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null){
break;
}
if(line.compareTo(fileName)>0){//说明有新文件
SCPInputStream scpInputStream = scpClient.get(line);
// 下载文件
downLoadFileIO(scpInputStream,line);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 连接的Session和Connection对象都需要关闭
if(ss!=null){
ss.close();
}
connection.close();
}
}
}
private void downLoadFileIO(SCPInputStream scpInputStream,String line) throws IOException {
// IO流下载文件
BufferedInputStream bis=new BufferedInputStream(scpInputStream);
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("E:\\"+line+".txt"));
byte [] bytes=new byte[1024];
int len;
while ((len=bis.read(bytes))>0){
bos.write(bytes,0,len);
}
bis.close();
bos.close();
}