Java 中用SCPClient远程上传下载文件到linux服务器
记录一次最近在工作中用到的,需求是在一台服务器部署代码,需要远程上传下载文件到另一台服务器(Linux系统)
,核心方法用到的就是SCPClient类,看了一下源码 ,就是远程连接目标服务器,通过linux命令上传和下载,不多上源码
- SCPClient 需要导入的jar包 (maven形式)
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
- SCPClient 实现上传
public static void main(String[] args) {
//连接服务器 服务器名称和端口号
//xx.xx.xx.xx 就是目标服务器的ip 端口是22
Connection connection = new Connection("xx.xx.xx.xx",22);
//你要上传文件所在地址,linux和window路径不一样看你自己的系统
String filePath1 ="C:/JepsFile/202007211503.png" ;
File f = new File(filePath1);
try(FileInputStream fis = new FileInputStream(f)) {
connection.connect();
//yuan服务器用户名和密码
boolean isAuthenticated = connection.authenticateWithPassword("root","root");
if(!isAuthenticated){
System.out.println("连接建立失败");
return ;
}
SCPClient scpClient = new SCPClient(connection);
//这个是你要上传文件的目标服务器的文件路径
String remoteTargetDirectory = "/app/JepsUpload/sup/202007/";
SFTPv3Client sftpv3Client = new SFTPv3Client(connection);
//判断是否有这个文件夹 如果没有就创建一个
Boolean isdir = isDir(sftpv3Client, remoteTargetDirectory);
if(!isdir){
sftpv3Client.mkdir(remoteTargetDirectory,0600);
}
SCPOutputStream os = scpClient.put(f.getName(),f.length(),remoteTargetDirectory,null);
byte[] b = new byte[4096];
int i;
while ((i = fis.read(b)) != -1) {
os.write(b, 0, i);
}
Session session= connection.openSession();//打开一个会话
//远程执行linux命令 因为上传的文件没有读的文件 需要加上才能下载 (如果你上传的文件有)
String cmd = "chmod +r "+remoteTargetDirectory+f.getName();
System.out.println("linux命令=="+cmd);
session.execCommand(cmd);//执行命令
os.flush();
fis.close();
os.close();
connection.close();
System.out.println("upload ok");
} catch (IOException e) {
log.error(e.toString());
}
}
- SCPClient 实现下载
public static void main(String[] args) {
Connection connection = new Connection("XX.XX.XX.XX",22);
//客户端要存储的下载文件的路径可以自己随便定义
File newFile = new File("C:/JepsFile/20200722001.jpg" );
try(FileOutputStream fos = new FileOutputStream(newFile);) {
connection.connect();
boolean isAuthenticated = connection.authenticateWithPassword("root","root");
if(isAuthenticated){
SCPClient scpClient = connection.createSCPClient();
//从目标文件服务器下载文件
SCPInputStream sis = scpClient.get("/app/JepsUpload/sup/202007/202007211501.png");
//先将远程服务器的文件下载到用户的电脑某个磁盘内
File f = new File("C:/JepsFile");
if(!f.exists()){
f.mkdirs();
}
byte[] b = new byte[4096];
int i;
while ((i = sis.read(b)) != -1){
fos.write(b,0, i);
}
fos.flush();
fos.close();
sis.close();
connection.close();
System.out.println("download ok");
}else{
System.out.println("连接建立失败");
}
} catch (IOException e) {
log.error("下载文件异常="+e.toString());
}
}
以上代码亲测有效 如果有人跑不通 还得具体问题具体分析 比如目标服务器 防火墙一类的,环境问题是最难调的,加油!