1. 程式人生 > >java使用Jsch實現遠端操作linux伺服器進行檔案上傳、下載,刪除和顯示目錄資訊

java使用Jsch實現遠端操作linux伺服器進行檔案上傳、下載,刪除和顯示目錄資訊

  1 package com.fline.aic.utils;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileNotFoundException;
  7 import java.io.IOException;
  8 import java.io.InputStream;
  9 import java.io.InputStreamReader;
 10 import java.util.Properties;
11 import java.util.Vector; 12 13 import com.jcraft.jsch.Channel; 14 import com.jcraft.jsch.ChannelExec; 15 import com.jcraft.jsch.ChannelSftp; 16 import com.jcraft.jsch.JSch; 17 import com.jcraft.jsch.JSchException; 18 import com.jcraft.jsch.Session; 19 import com.jcraft.jsch.SftpException;
20 21 /** 22 * 23 * @Description TODO 24 * @author biehl 25 * @Date 2018年10月11日 上午10:20:11 26 * 27 * 說明:exec用於執行命令;sftp用於檔案處理 28 */ 29 public class SSHRemoteCall { 30 31 // 私有的物件 32 private static SSHRemoteCall sshRemoteCall; 33 34 /** 35 * 私有的構造方法 36
*/ 37 private SSHRemoteCall() { 38 } 39 40 // 懶漢式,執行緒不安全,適合單執行緒 41 public static SSHRemoteCall getInstance() { 42 if (sshRemoteCall == null) { 43 sshRemoteCall = new SSHRemoteCall(); 44 } 45 return sshRemoteCall; 46 } 47 48 // 懶漢式,執行緒安全,適合多執行緒 49 public static synchronized SSHRemoteCall getInstance2() { 50 if (sshRemoteCall == null) { 51 sshRemoteCall = new SSHRemoteCall(); 52 } 53 return sshRemoteCall; 54 } 55 56 private static final int DEFAULT_PORT = 22;// 預設埠號 57 private int port;// 埠號 58 59 private static String ipAddress = "192.168.110.130";// ip地址 60 private static String userName = "root";// 賬號 61 private static String password = "hadoop";// 密碼 62 63 private Session session;// JSCH session 64 private boolean logined = false;// 是否登陸 65 66 /** 67 * 構造方法,可以直接使用DEFAULT_PORT 68 * 69 * @param ipAddress 70 * @param userName 71 * @param password 72 */ 73 public SSHRemoteCall(String ipAddress, String userName, String password) { 74 this(ipAddress, DEFAULT_PORT, userName, password); 75 } 76 77 /** 78 * 構造方法,方便直接傳入ipAddress,userName,password進行呼叫 79 * 80 * @param ipAddress 81 * @param port 82 * @param userName 83 * @param password 84 */ 85 public SSHRemoteCall(String ipAddress, int port, String userName, String password) { 86 super(); 87 this.ipAddress = ipAddress; 88 this.userName = userName; 89 this.password = password; 90 this.port = port; 91 } 92 93 /** 94 * 遠端登陸 95 * 96 * @throws Exception 97 */ 98 public void sshRemoteCallLogin(String ipAddress, String userName, String password) throws Exception { 99 // 如果登陸就直接返回 100 if (logined) { 101 return; 102 } 103 // 建立jSch物件 104 JSch jSch = new JSch(); 105 try { 106 // 獲取到jSch的session, 根據使用者名稱、主機ip、埠號獲取一個Session物件 107 session = jSch.getSession(userName, ipAddress, DEFAULT_PORT); 108 // 設定密碼 109 session.setPassword(password); 110 111 // 方式一,通過Session建立連線 112 // session.setConfig("StrictHostKeyChecking", "no"); 113 // session.connect(); 114 115 // 方式二,通過Session建立連線 116 // java.util.Properties; 117 Properties config = new Properties(); 118 config.put("StrictHostKeyChecking", "no"); 119 session.setConfig(config);// 為Session物件設定properties 120 // session.setTimeout(3000);// 設定超時 121 session.connect();//// 通過Session建立連線 122 123 // 設定登陸狀態 124 logined = true; 125 } catch (JSchException e) { 126 // 設定登陸狀態為false 127 logined = false; 128 throw new Exception( 129 "主機登入失敗, IP = " + ipAddress + ", USERNAME = " + userName + ", Exception:" + e.getMessage()); 130 } 131 } 132 133 /** 134 * 關閉連線 135 */ 136 public void closeSession() { 137 // 呼叫session的關閉連線的方法 138 if (session != null) { 139 // 如果session不為空,呼叫session的關閉連線的方法 140 session.disconnect(); 141 } 142 143 } 144 145 /** 146 * 執行相關的命令 147 * 148 * @param command 149 * @throws IOException 150 */ 151 public void execCommand(String command) throws IOException { 152 InputStream in = null;// 輸入流(讀) 153 Channel channel = null;// 定義channel變數 154 try { 155 // 如果命令command不等於null 156 if (command != null) { 157 // 開啟channel 158 //說明:exec用於執行命令;sftp用於檔案處理 159 channel = session.openChannel("exec"); 160 // 設定command 161 ((ChannelExec) channel).setCommand(command); 162 // channel進行連線 163 channel.connect(); 164 // 獲取到輸入流 165 in = channel.getInputStream(); 166 // 執行相關的命令 167 String processDataStream = processDataStream(in); 168 // 列印相關的命令 169 System.out.println("1、列印相關返回的命令: " + processDataStream); 170 } 171 } catch (JSchException e) { 172 e.printStackTrace(); 173 } catch (IOException e) { 174 e.printStackTrace(); 175 } catch (Exception e) { 176 e.printStackTrace(); 177 } finally { 178 if (in != null) { 179 in.close(); 180 } 181 if (channel != null) { 182 channel.disconnect(); 183 } 184 } 185 186 } 187 188 /** 189 * 對將要執行的linux的命令進行遍歷 190 * 191 * @param in 192 * @return 193 * @throws Exception 194 */ 195 public String processDataStream(InputStream in) throws Exception { 196 StringBuffer sb = new StringBuffer(); 197 BufferedReader br = new BufferedReader(new InputStreamReader(in)); 198 String result = ""; 199 try { 200 while ((result = br.readLine()) != null) { 201 sb.append(result); 202 // System.out.println(sb.toString()); 203 } 204 } catch (Exception e) { 205 throw new Exception("獲取資料流失敗: " + e); 206 } finally { 207 br.close(); 208 } 209 return sb.toString(); 210 } 211 212 /** 213 * 上傳檔案 可參考:https://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html 214 * 215 * @param directory 216 * 上傳檔案的目錄 217 * @param uploadFile 218 * 將要上傳的檔案 219 */ 220 public void uploadFile(String directory, String uploadFile) { 221 try { 222 // 開啟channelSftp 223 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); 224 // 遠端連線 225 channelSftp.connect(); 226 // 建立一個檔名稱問uploadFile的檔案 227 File file = new File(uploadFile); 228 // 將檔案進行上傳(sftp協議) 229 // 將本地檔名為src的檔案上傳到目標伺服器,目標檔名為dst,若dst為目錄,則目標檔名將與src檔名相同. 230 // 採用預設的傳輸模式:OVERWRITE 231 channelSftp.put(new FileInputStream(file), directory, ChannelSftp.OVERWRITE); 232 // 切斷遠端連線 233 channelSftp.exit(); 234 System.out.println("2、" + file.getName() + " 檔案上傳成功....."); 235 } catch (JSchException e) { 236 e.printStackTrace(); 237 } catch (SftpException e) { 238 e.printStackTrace(); 239 } catch (FileNotFoundException e) { 240 e.printStackTrace(); 241 } 242 243 } 244 245 /** 246 * 下載檔案 採用預設的傳輸模式:OVERWRITE 247 * 248 * @param src 249 * linux伺服器檔案地址 250 * @param dst 251 * 本地存放地址 252 * @throws JSchException 253 * @throws SftpException 254 */ 255 public void fileDownload(String src, String dst) throws JSchException, SftpException { 256 // src 是linux伺服器檔案地址,dst 本地存放地址 257 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); 258 // 遠端連線 259 channelSftp.connect(); 260 // 下載檔案,多個過載方法 261 channelSftp.get(src, dst); 262 // 切斷遠端連線,quit()等同於exit(),都是呼叫disconnect() 263 channelSftp.quit(); 264 // channelSftp.disconnect(); 265 System.out.println("3、" + src + " ,下載檔案成功....."); 266 } 267 268 /** 269 * 刪除檔案 270 * 271 * @param directory 272 * 要刪除檔案所在目錄 273 * @param deleteFile 274 * 要刪除的檔案 275 * @param sftp 276 * @throws SftpException 277 * @throws JSchException 278 */ 279 public void deleteFile(String directoryFile) throws SftpException, JSchException { 280 // 開啟openChannel的sftp 281 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); 282 // 遠端連線 283 channelSftp.connect(); 284 // 刪除檔案 285 channelSftp.rm(directoryFile); 286 // 切斷遠端連線 287 channelSftp.exit(); 288 System.out.println("4、" + directoryFile + " 刪除的檔案....."); 289 } 290 291 /** 292 * 列出目錄下的檔案 293 * 294 * @param directory 295 * 要列出的目錄 296 * @param sftp 297 * @return 298 * @throws SftpException 299 * @throws JSchException 300 */ 301 public Vector listFiles(String directory) throws JSchException, SftpException { 302 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); 303 // 遠端連線 304 channelSftp.connect(); 305 // 顯示目錄資訊 306 Vector ls = channelSftp.ls(directory); 307 System.out.println("5、" + ls); 308 // 切斷連線 309 channelSftp.exit(); 310 return ls; 311 } 312 313 public static void main(String[] args) { 314 // 連線到指定的伺服器 315 try { 316 // 1、首先遠端連線ssh 317 SSHRemoteCall.getInstance().sshRemoteCallLogin(ipAddress, userName, password); 318 // 列印資訊 319 System.out.println("0、連線192.168.110.130,ip地址: " + ipAddress + ",賬號: " + userName + ",連線成功....."); 320 321 // 2、執行相關的命令 322 // 檢視目錄資訊 323 // String command = "ls /home/hadoop/package "; 324 // 檢視檔案資訊 325 // String command = "cat /home/hadoop/package/test "; 326 // 檢視磁碟空間大小 327 // String command = "df -lh "; 328 // 檢視cpu的使用情況 329 // String command = "top -bn 1 -i -c "; 330 // 檢視記憶體的使用情況 331 String command = "free "; 332 SSHRemoteCall.getInstance().execCommand(command); 333 334 // 3、上傳檔案 335 String directory = "/home/hadoop/package/poi.xlsx";// 目標檔名 336 String uploadFile = "E:\\poi.xlsx";// 本地檔名 337 SSHRemoteCall.getInstance().uploadFile(directory, uploadFile); 338 339 // 4、下載檔案 340 // src 是linux伺服器檔案地址,dst 本地存放地址,採用預設的傳輸模式:OVERWRITE 341 //test為檔名稱哈 342 String src = "/home/hadoop/package/test"; 343 String dst = "E:\\"; 344 SSHRemoteCall.getInstance().fileDownload(src, dst); 345 346 // 5、刪除檔案 347 String deleteDirectoryFile = "/home/hadoop/package/test"; 348 SSHRemoteCall.getInstance().deleteFile(deleteDirectoryFile); 349 350 // 6、展示目錄下的檔案資訊 351 String lsDirectory = "/home/hadoop/package"; 352 SSHRemoteCall.getInstance().listFiles(lsDirectory); 353 354 // 7、關閉連線 355 SSHRemoteCall.getInstance().closeSession(); 356 } catch (Exception e) { 357 // 列印錯誤資訊 358 System.err.println("遠端連線失敗......"); 359 e.printStackTrace(); 360 } 361 } 362 363 }