用的ch.ethz.ganymed
先导包:
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 --> <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>build210</version> </dependency>
调用方法,主要碰到的是中文乱码的问题,服务器是GB18030编码的,做了一个转码。(Linux使用 locale 命令查看编码)
@Override
public void downloadFile() throws IOException {
//新建连接ip
Connection conn = new Connection(“ip”);
conn.connect();
//登录
boolean isAuthenticated = conn.authenticateWithPassword(“账户”, “密码”);
if (!isAuthenticated){
throw new IOException("Authentication failed!");
}
SCPClient client = new SCPClient(conn);
//防止中文乱码
conData.setFileName(new String("中文filename.txt".getBytes(),"GB18030"));
//下载文件
client.get(“远程地址(精确到文件名)”, "本机地址");
//上传文件
client.put(“本机地址(精确到文件名)”, "远程地址");
Session session = conn.openSession();
//关闭连接
conn.close();
session.close();
}