Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. package ssh;
  2.  
  3. import com.jcraft.jsch.Channel;
  4. import com.jcraft.jsch.JSch;
  5. import com.jcraft.jsch.JSchException;
  6. import com.jcraft.jsch.Session;
  7.  
  8. import java.io.IOException;
  9. import java.io.OutputStream;
  10. import java.util.Properties;
  11.  
  12. public class SSHManager {
  13.  
  14. private final JSch jsch;
  15. private Session session;
  16. private Channel channel;
  17. private OutputStream outputStream;
  18.  
  19. private static final String SHELL_CHANNEL = "shell";
  20. private static final String EXECUTE_TERMINATION = "\n";
  21.  
  22. private String userName;
  23. private String password;
  24. private int portNumber;
  25. private int timeout;
  26.  
  27.  
  28. @SuppressWarnings("static-access")
  29. public SSHManager(final String userName, final String password, final String hostIp, final int portNumber, final int connectTimeout) throws JSchException, IOException {
  30. jsch = new JSch();
  31. Properties config = new Properties();
  32. config.put("StrictHostKeyChecking", "no");
  33. jsch.setConfig(config);
  34. System.out.println(userName + " " + password + " " + hostIp);
  35. this.userName = userName;
  36. this.password = password;
  37. this.portNumber = portNumber;
  38. this.timeout = connectTimeout;
  39. setupConnection(hostIp);
  40. }
  41.  
  42. private void setupConnection(final String hostIp) throws JSchException, IOException {
  43. System.out.println(userName + " " + password + " " + hostIp);
  44. session = jsch.getSession(userName, hostIp, portNumber);
  45. session.setPassword(password);
  46. session.connect(timeout);
  47. channel = session.openChannel(SHELL_CHANNEL);
  48. channel.setInputStream(System.in);
  49. outputStream = channel.getOutputStream();
  50. channel.connect();
  51. System.out.println(1);
  52. }
  53.  
  54. public void updateHost(final String host) throws JSchException, IOException{
  55. setupConnection(host);
  56. }
  57.  
  58.  
  59. public void executeCommand(final String command) throws IOException {
  60. outputStream.write((command + EXECUTE_TERMINATION).getBytes());
  61. System.out.println(channel + command);
  62. try {
  63. Thread.sleep(1000);
  64. } catch (InterruptedException e) {
  65. e.printStackTrace();
  66. }
  67. outputStream.flush();
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement