Sobes.tech
Junior — Middle

Can you establish a remote connection to the server to perform operations?

sobes.tech AI

Answer from AI

Yes, in Java it is possible to establish a remote connection to a server to perform operations. Protocols such as SSH or RMI (Remote Method Invocation) are often used for this purpose.

An example using SSH can be implemented with the JSch library:

import com.jcraft.jsch.*;

public class RemoteExecutor {
    public static void main(String[] args) {
        String host = "remote.server.com";
        String user = "username";
        String password = "password";

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand("ls -la");
            channel.setErrStream(System.err);
            channel.setInputStream(null);

            InputStream in = channel.getInputStream();
            channel.connect();

            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    break;
                }
                Thread.sleep(100);
            }
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Thus, commands can be executed on a remote server from a Java application.