Java后端開發——調用遠程Shell腳本代碼示例


  //調用遠程服務器的shell腳本
  //ip:遠程服務器的ip地址
  //username:遠程服務器的登錄用戶名
  //port:遠程服務器的登錄端口號
  //cmd:登錄之后的命令
public Response<Boolean> runRemoteShell(String ip,String username,Integer port,String cmd) throws JSchException, IOException { try { JSch jsch = new JSch(); // Endpoint以杭州為例,其它Region請按實際情況填寫。 String endpoint = "http://oss-cn-shanghai.aliyuncs.com"; // 阿里雲主賬號AccessKey擁有所有API的訪問權限,風險很高。強烈建議您創建並使用RAM賬號進行API訪問或日常運維,請登錄 https://ram.console.aliyun.com 創建RAM賬號。 String accessKeyId = "********"; String accessKeySecret = "********"; String bucketName = "********"; String objectName = "********"; // 創建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 下載OSS文件到本地文件。如果指定的本地文件存在會覆蓋,不存在則新建。 ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("data.pem")); // 關閉OSSClient。 ossClient.shutdown();

       //從阿里雲Oss上面下載密鑰文件 jsch.addIdentity(
"data.pem"); Session session=jsch.getSession(username, ip, port); session.setConfig("StrictHostKeyChecking", "no"); session.connect();                  //建立會話

ChannelShell channelShell
= (ChannelShell) session.openChannel("shell"); channelShell.connect();
       InputStream inputStream
=channelShell.getInputStream(); OutputStream outputStream = channelShell.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream);    //建立通道 printWriter.println(cmd);      //輸入命令 printWriter.println("exit");    //輸入結束操作命令 printWriter.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String msg;              //在控制台上打印遠程服務器的顯示結果 while((msg = in.readLine())!=null){ System.out.println(msg); } in.close(); return new Response<>("腳本執行成功",Response.SUCCESS_CODE,Boolean.TRUE); }catch (JSchException e) { e.printStackTrace(); return new Response<>("登入遠程服務器失敗"); } }

 

如果覺得上述內容還可以的話,可以掃描下方二維碼進行贊賞喲~👇👇👇

 

同時也可關注微信公眾號獲得更多個人分享~👇👇👇


免責聲明!

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



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