Java實現Linux上傳&下載文件


/**
*實現服務器連接
* @param host
* @param port
* @param username
* @param password
* @param privateKeyFile
* @return
* @throws IOException
*/

public static Connection getSSHConnection(String host,int port,String username,String password,String privateKeyFile) throws IOException {
Connection connection=new Connection(host,port);
connection.connect();

File file=new File(privateKeyFile);
System.out.println(file);
boolean b=connection.authenticateWithPublicKey(username,file,password);
System.out.println(b);
if (b){
return connection;
}else {
System.out.println("登錄連接失敗,請檢查用戶名、密碼、私鑰文件");
return null;
}
}
/**
*實現下載服務器上的文件到本地指定目錄
* @param conn SSH連接信息
* @param fileName 服務器上的文件地址/opt/rpc/log/order/all.log
* @param localPath 本地路徑:D:\
* @throws IOException
*/

public void getFile(Connection conn, String fileName,String localPath) throws IOException{

SCPClient scpClient=conn.createSCPClient();
//String logPath="cd /opt/rpc/log/order";
//Session session = conn.openSession();
//session.execCommand(logPath);//執行shell命令
scpClient.get(fileName,localPath);

}

/**
*實現上傳本地文件到服務器上指定目錄
* @param conn SSH連接信息
* @param fileName D:\a.txt
* @param localPath 服務器地址路徑:/opt/rpc/log/order
* @throws IOException
*/
public void putFile(Connection conn, String fileName,String localPath) throws IOException{

SCPClient scpClient=conn.createSCPClient();
scpClient.put(fileName,localPath);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM