Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package dispatcher;
- import com.jcraft.jsch.Channel;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.JSchException;
- import com.jcraft.jsch.Session;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.util.Properties;
- public class SSHRemoteConnector implements RemoteConnector {
- private final JSch jsch;
- private Session session;
- private Channel channel;
- private OutputStream outputStream;
- private static final String SHELL_CHANNEL = "shell";
- private static final String EXECUTE_TERMINATION = "\n";
- private String userName;
- private String password;
- private int portNumber;
- private int timeout;
- private SSHRemoteConnector() {
- jsch = null;
- session = null;
- channel = null;
- outputStream = null;
- }
- public SSHRemoteConnector(final String userName, final String password, final String hostIp, final int portNumber, final int connectTimeout) throws JSchException, IOException {
- jsch = new JSch();
- Properties config = new Properties();
- config.put("StrictHostKeyChecking", "no");
- jsch.setConfig(config);
- System.out.println(userName + " " + password + " " + hostIp);
- this.userName = userName;
- this.password = password;
- this.portNumber = portNumber;
- this.timeout = connectTimeout;
- setupConnection(hostIp);
- }
- private void setupConnection(final String hostIp) throws JSchException, IOException {
- System.out.println(userName + " " + password + " " + hostIp);
- session = jsch.getSession(userName, hostIp, portNumber);
- session.setPassword(password);
- session.connect(timeout);
- channel = session.openChannel(SHELL_CHANNEL);
- channel.setInputStream(System.in);
- outputStream = channel.getOutputStream();
- channel.connect();
- System.out.println(1);
- }
- @Override
- public void updateHost(final String host) throws JSchException, IOException{
- setupConnection(host);
- }
- @Override
- public void executeCommand(final String command) throws IOException {
- outputStream.write((command + EXECUTE_TERMINATION).getBytes());
- System.out.println(channel + command);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- outputStream.flush();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement