Java连接linux服务器实现文件下载到本地 和 本地上传文件到服务器
1、pom文件引入jar包
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
2、代码实现
package com.example.demo.server;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import java.io.IOException;
public class ServerUploadAndDownload {
public static Connection connection;
public static void main(String[] args) {
getSSHConnection("192.168.0.110",22,"root","123456");
getSSHFile("/root/testdata.txt","D:\\");
putSSHFile("D:\\","/root/testdata.txt");
}
/**
*实现服务器连接
* @param host 192.168.0.110
* @param port 22
* @param username root
* @param password 123456
* @return
* @throws IOException
*/
public static void getSSHConnection(String host,int port,String username,String password){
connection=new Connection(host,port);
try {
connection.connect();
boolean b=connection.authenticateWithPassword(username,password);
System.out.println(b);
if (b){
System.out.println("登录连接成功");
}else {
System.out.println("登录连接失败,请检查用户名、密码");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*实现下载服务器上的文件到本地指定目录
* @param fileName 服务器上的文件地址 /root/app/test.txt
* @param localPath 本地路径:D:\
* @throws IOException
*/
public static void getSSHFile(String fileName,String localPath){
SCPClient scpClient= null;
try {
scpClient = connection.createSCPClient();
//String logPath="cd /root/app/";
//Session session = conn.openSession();
//session.execCommand(logPath);//执行shell命令
scpClient.get(fileName,localPath);
System.out.println("下载文件成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*实现上传本地文件到服务器上指定目录
* @param fileName D:\test.txt
* @param localPath 服务器地址路径://root/app/
* @throws IOException
*/
public static void putSSHFile(String fileName,String localPath){
SCPClient scpClient= null;
try {
scpClient = connection.createSCPClient();
scpClient.put(fileName,localPath);
System.out.println("上传文件成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}