您的位置:首页 > 运维架构 > Linux

scp实现OS之间的远程传输文件

2017-05-20 08:20 344 查看

问题场景

最近的项目可能会要求从Windows远程传输文件到Linux环境下,实现方式很多,本文采用ganymed-ssh2-build210.jar。支持递归上传与下载文件夹的例子请参照我的另一篇博客sftp实现OS之间的远程传输文件与文件夹

code

package scp;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* Created by yangyouxing
* date on 2017/5/13.
*/
public class Scpclient {

private static Scpclient instance;

public static synchronized Scpclient getInstance(String IP, int port, String username, String password) {

if (instance == null) {
instance = new Scpclient(IP, port, username, password);
}
return instance;
}

public Scpclient(String IP, int port, String username, String password) {
this.ip = IP;
this.port = port;
this.username = username;
this.password = password;
}

/**
* 下载单个文件
* @param remoteFile            /home/master/mac.sh
* @param localTargetDirectory  /Users/yyx/Downloads/test (must exist)
*/
public void download(String remoteFile, String localTargetDirectory) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);

if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
client.get(remoteFile, localTargetDirectory);
conn.close();
} catch (IOException ex) {
Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}

/**
* 上传单个文件,且支持上传单个文件夹下所有文件(不包括目录结构)
* @param localFile                 /Users/yyx/Downloads/mac.sh or /Users/yyx/Downloads/mac
* @param remoteTargetDirectory     /home/master/ (must exist)
*/
public void upload(String localFile, String remoteTargetDirectory) {
upload(localFile, remoteTargetDirectory, null);
}

/**
* 上传单个文件,且支持上传单个文件夹下所有文件(不包括目录结构)
* @param localFile                 /Users/yyx/Downloads/mac.sh or /Users/yyx/Downloads/mac
* @param remoteTargetDirectory     /home/master/ (must exist)
* @param mode                      0600 = 'rw- --- ---'
*/
public void upload(String localFile, String remoteTargetDirectory, String mode) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);

if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
File file = new File(localFile);
List<String> list = new ArrayList<>();
getAllFile(file, list);
String[] files = new String[list.size()];
list.toArray(files);
if((mode == null) || (mode.length() == 0)){
mode = "0600";
}
client.put(files, remoteTargetDirectory, mode);
conn.close();
} catch (IOException ex) {
Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}

/**
* 递归获取文件
* @param file  file or dir
* @return      List<String>
*/
private void getAllFile(File file, List<String> tmp) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
getAllFile(files[i], tmp);
}
} else  {
tmp.add(file.getAbsolutePath());
}
}

/**
* 上传单个文件并重命名该文件
* @param localFile             /Users/yyx/Downloads/mac.sh
* @param remoteFileName        copy.sh
* @param remoteTargetDirectory /home/master/
* @param mode                  0600 = 'rw- --- ---'
*/
public void upload(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);

if (!isAuthenticated) {
System.err.println("authentication failed");
}
SCPClient client = new SCPClient(conn);
if((mode == null) || (mode.length() == 0)){
mode = "0600";
}
client.put(localFile, remoteFileName, remoteTargetDirectory, mode);

//rename
Session session = conn.openSession();
String tmpPathName = remoteTargetDirectory + File.separator + remoteFileName;
String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf("."));
session.execCommand("mv " + remoteFileName + " " + newPathName);//重命名回来

conn.close();
} catch (IOException ex) {
Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}

private String ip;
private int port;
private String username;
private String password;

public static void main(String[] args) {
String IP = "192.168.***.***";//替换成目标IP
int port = 22;
String username = "master";
String password = "master";
Scpclient client = Scpclient.getInstance(IP, port, username, password);
//默认会连接到home/users目录下
client.upload("/Users/yyx/Downloads/android_upload.zip", "./");
//client.upload("/Users/yyx/Downloads/mac.sh", "maccpoy.sh", "./Public", null);
//client.download("/home/master/mac.sh", "/Users/yyx/Downloads/test");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux os scp