Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. public String runCommand(String command) {
  2. String host = "XX.XX.X.XX";
  3. String user = "user";
  4. String password = "password";
  5. String result = "";
  6.  
  7. try{
  8. Properties config = new Properties();
  9. config.put("StrictHostKeyChecking", "no");
  10. JSch jsch = new JSch();
  11.  
  12. // Create a JSch session to connect to the server
  13. Session session = jsch.getSession(user, host, 22);
  14. session.setPassword(password);
  15. session.setConfig(config);
  16.  
  17. // Establish the connection
  18. session.connect();
  19.  
  20. if(session.isConnected()) {
  21. System.out.println("Connected...");
  22. }
  23.  
  24. ChannelExec channel = (ChannelExec) session.openChannel("exec");
  25.  
  26. channel.setCommand("pwd");
  27.  
  28. int stat = channel.getExitStatus();
  29.  
  30. StringBuilder outputBuffer = new StringBuilder();
  31. StringBuilder errorBuffer = new StringBuilder();
  32.  
  33. InputStream in = channel.getInputStream();
  34. InputStream err = channel.getExtInputStream();
  35.  
  36. channel.setPty(true);
  37. channel.connect();
  38.  
  39. System.out.println("Channel Connected");
  40. System.out.println("channel.isConnected() "+channel.isConnected());
  41. System.out.println("channel.isClosed() "+channel.isClosed());
  42.  
  43.  
  44. byte[] tmp = new byte[1024];
  45. while (true) {
  46. while (in.available() > 0) {
  47. int i = in.read(tmp, 0, 1024);
  48. if (i < 0) break;
  49. outputBuffer.append(new String(tmp, 0, i));
  50. }
  51. while (err.available() > 0) {
  52. int i = err.read(tmp, 0, 1024);
  53. if (i < 0) break;
  54. errorBuffer.append(new String(tmp, 0, i));
  55. }
  56. if (channel.isClosed()) {
  57. if ((in.available() > 0) || (err.available() > 0)) continue;
  58. System.out.println("exit-status: " + channel.getExitStatus());
  59. break;
  60. }
  61. try {
  62. Thread.sleep(1000);
  63. } catch (Exception ee) {
  64. }
  65. }
  66.  
  67. System.out.println("output: " + outputBuffer.toString());
  68. System.out.println("error: " + errorBuffer.toString());
  69. channel.disconnect();
  70. session.disconnect();
  71. System.out.println("Channel And Session Closed!!!");
  72. }catch(JSchException e){
  73. e.printStackTrace();
  74. result = "Auth fail";
  75. }catch(Exception e){
  76. e.printStackTrace();
  77. }
  78. return result;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement