59 lines
2.3 KiB
Java
59 lines
2.3 KiB
Java
package com.example.plugin;
|
|
|
|
import com.intellij.openapi.actionSystem.AnAction;
|
|
import com.intellij.openapi.actionSystem.AnActionEvent;
|
|
import com.intellij.openapi.project.Project;
|
|
import com.intellij.openapi.ui.Messages;
|
|
import com.jcraft.jsch.*;
|
|
import org.jetbrains.annotations.NotNull;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.InputStreamReader;
|
|
import java.util.Optional;
|
|
|
|
public class RemoteCommandAction extends AnAction {
|
|
@Override
|
|
public void actionPerformed(@NotNull AnActionEvent e) {
|
|
Project project = e.getProject();
|
|
if (project == null) return;
|
|
String serverId = ProjectServerMapping.getInstance().getServerIdForProject(project.getBasePath());
|
|
if (serverId == null) {
|
|
Messages.showErrorDialog("No server associated with this project", "Error");
|
|
return;
|
|
}
|
|
Optional<SshServer> maybeServer = SshServerManager.getInstance().findServer(serverId);
|
|
if (maybeServer.isEmpty()) return;
|
|
SshServer server = maybeServer.get();
|
|
|
|
String command = Messages.showInputDialog("Enter command to run on " + server.host, "Remote Command", null);
|
|
if (command == null || command.isEmpty()) return;
|
|
|
|
try {
|
|
String output = executeCommand(server, command);
|
|
Messages.showInfoMessage(output, "Command output");
|
|
} catch (Exception ex) {
|
|
Messages.showErrorDialog("Command error: " + ex.getMessage(), "Error");
|
|
}
|
|
}
|
|
|
|
private String executeCommand(SshServer server, String command) throws Exception {
|
|
JSch jsch = new JSch();
|
|
Session session = jsch.getSession(server.user, server.host, server.port);
|
|
session.setPassword(SshServerManager.getInstance().getPassword(server.id));
|
|
session.setConfig("StrictHostKeyChecking", "no");
|
|
session.connect(5000);
|
|
|
|
Channel channel = session.openChannel("exec");
|
|
((ChannelExec) channel).setCommand(command);
|
|
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
|
|
channel.connect();
|
|
|
|
StringBuilder output = new StringBuilder();
|
|
String line;
|
|
while ((line = reader.readLine()) != null) output.append(line).append("\n");
|
|
|
|
channel.disconnect();
|
|
session.disconnect();
|
|
return output.toString();
|
|
}
|
|
} |