Java back-end development - call the remote Shell Script code examples

  // shell script calls the remote server 
  // ip: ip address of the remote server
  // username: login user name of the remote server
  // port: remote login server port number
  // cmd: command after login
public the Response <Boolean> runRemoteShell (IP String, String username, Port Integer, String cmd) throws JSchException, IOException { the try { Jsch JSch = new new JSch (); // Endpoint A Case Study, please fill in the other Region according to the actual situation. Endpoint = String "http://oss-cn-shanghai.aliyuncs.com" ; // Ali cloud AccessKey main account has access to all API's, the risk is high. It is strongly recommended that you create an account and use the RAM API access or daily operation and maintenance, please login https://ram.console.aliyun.com create a RAM account. AccessKeyId = String "********" ; String accessKeySecret = "********"; String bucketName = "********"; String objectName = "********"; // create OSSClient instance. = OssClient the OSS new new OSSClientBuilder () Build (Endpoint, accessKeyId, accessKeySecret).; // download OSS files to a local file. Overrides if specified local file exists, it does not exist New. ossClient.getObject ( new new GetObjectRequest (bucketName, objectName), new new File ( "data.pem" )); // close OSSClient. ossClient.shutdown ();

       // download key files from Ali cloud above Oss jsch.addIdentity (
"data.pem" ); Session session=jsch.getSession(username, ip, port); session.setConfig("StrictHostKeyChecking", "no"); session.connect ();                   // establish a session

ChannelShell channelShell
= (ChannelShell) session.openChannel("shell"); channelShell.connect();
       InputStream inputStream
=channelShell.getInputStream(); OutputStream outputStream = channelShell.getOutputStream(); A PrintWriter the PrintWriter = new new the PrintWriter (the outputStream); // channel established printWriter.println (cmd); // enter commands PrintWriter.println ( "Exit" ); // End command input printWriter.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String msg; // print a remote server on the console display results while((msg = in.readLine())!=null){ System.out.println(msg); } in.close(); return new new the Response <> ( "successful script execution" , Response.SUCCESS_CODE, Boolean.TRUE); }catch (JSchException e) { e.printStackTrace (); return new new the Response <> ( "sign remote server failed" ); } }

 

Guess you like

Origin www.cnblogs.com/bobbycheng/p/11867238.html