Skip to content

Commit

Permalink
new test class ShellExecutor created
Browse files Browse the repository at this point in the history
  • Loading branch information
astrapisixtynine committed Jun 22, 2024
1 parent 96a2312 commit 65ced32
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
42 changes: 42 additions & 0 deletions src/test/java/io/github/astrapi69/net/ShellExecutor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package io.github.astrapi69.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class ShellExecutor
{

public static String execute(String shellPath, String executionPath, String command)
throws IOException, InterruptedException
{
if(executionPath.contains("~")){
executionPath = executionPath.replace("~", System.getProperty("user.home"));
}
File executionDirectory = new File(executionPath);
if (!executionDirectory.exists())
{
throw new IllegalArgumentException("Execution directory does not exist");
}
String cdToExecutionPath = "cd " + executionPath;
String commands = cdToExecutionPath + " && " + command;
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(shellPath, "-c", commands);

Process process = processBuilder.start();
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
int waitFor = process.waitFor();

if (waitFor != 0)
stringBuilder.append("Exit code: ").append(waitFor).append("\n");
return stringBuilder.toString();
}
}
20 changes: 20 additions & 0 deletions src/test/java/io/github/astrapi69/net/ShellExecutorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.github.astrapi69.net;

import org.testng.annotations.Test;

import java.io.IOException;

public class ShellExecutorTest {

@Test
public void testExecute() throws IOException, InterruptedException {

String shellPath = "/usr/bin/zsh";
String executionPath = "~/dev/tmp";
String command = "touch foo.txt";

String shellOutput = ShellExecutor.execute(shellPath, executionPath, command);
System.out.println(shellOutput);

}
}
2 changes: 1 addition & 1 deletion src/test/java/io/github/astrapi69/net/SshConnector.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public static void main(final String[] args) throws Exception
try
{

session = getSshSession("root", "admin", "192.168.0.1", 22);
session = getSshSession("root", "admin", "192.168.178.1", 22);
channel = (ChannelShell)session.openChannel("shell");

final PipedOutputStream reply = new PipedOutputStream();
Expand Down

0 comments on commit 65ced32

Please sign in to comment.