Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. package dispatcher;
  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 SSHRemoteConnector implements RemoteConnector {
  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. private SSHRemoteConnector() {
  28. jsch = null;
  29. session = null;
  30. channel = null;
  31. outputStream = null;
  32. }
  33.  
  34. public SSHRemoteConnector(final String userName, final String password, final String hostIp, final int portNumber, final int connectTimeout) throws JSchException, IOException {
  35. jsch = new JSch();
  36. Properties config = new Properties();
  37. config.put("StrictHostKeyChecking", "no");
  38. jsch.setConfig(config);
  39. System.out.println(userName + " " + password + " " + hostIp);
  40. this.userName = userName;
  41. this.password = password;
  42. this.portNumber = portNumber;
  43. this.timeout = connectTimeout;
  44. setupConnection(hostIp);
  45. }
  46.  
  47. private void setupConnection(final String hostIp) throws JSchException, IOException {
  48. System.out.println(userName + " " + password + " " + hostIp);
  49. session = jsch.getSession(userName, hostIp, portNumber);
  50. session.setPassword(password);
  51. session.connect(timeout);
  52. channel = session.openChannel(SHELL_CHANNEL);
  53. channel.setInputStream(System.in);
  54. outputStream = channel.getOutputStream();
  55. channel.connect();
  56. System.out.println(1);
  57. }
  58.  
  59. @Override
  60. public void updateHost(final String host) throws JSchException, IOException{
  61. setupConnection(host);
  62. }
  63.  
  64.  
  65. @Override
  66. public void executeCommand(final String command) throws IOException {
  67. outputStream.write((command + EXECUTE_TERMINATION).getBytes());
  68. System.out.println(channel + command);
  69. try {
  70. Thread.sleep(1000);
  71. } catch (InterruptedException e) {
  72. e.printStackTrace();
  73. }
  74. outputStream.flush();
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement