Execute Bash script from Bot Config
If the shell script needs to be executed on the same server where the WorkFusion instance is running, you can execute it via java.lang.ProcessBuilder.
The code below may help you understand how to call a bash script.
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://web-harvest.sourceforge.net/schema/1.0/config">
<var-def name="bashscriptresult">
<script return="executeShellScript()"><![CDATA[
import com.freedomoss.workfusion.utils.gson.GsonUtils;
import org.apache.commons.io.IOUtils;
/**
* This is a demo for calling your_shell.sh
**/
static String executeShellScript() throws InterruptedException {
String shellScriptOutput = invoke(new ProcessBuilder(new String[] {
"/bin/bash",
"your_shell.sh",
"param1",
"param2",
"param3"
}));
return shellScriptOutput;
}
/**
* Invokes the to return any result, your script must output something to the out stream, you then capture it and return as the resutl of invoke()
*/
static String invoke(ProcessBuilder builder) throws IOException, InterruptedException {
builder.redirectErrorStream(true);
log.debug("Executing shell command: {}", builder.command());
Process process = builder.start();
BufferedReader reader = null;
String output = null;
try {
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
output = IOUtils.toString(reader);
} finally {
if (reader != null) {
reader.close();
}
}
int code = process.waitFor();
if (code != 0) {
throw new RuntimeException("Failed to invoke process: " + builder.command() + ". Return code: " + code + ". Output: " + output);
}
return output;
}
]]></script>
</var-def>
<export include-original-data = "true"/>
</config>
note
The above script will try to run the command /bin/bash your_shell.sh param1 param2 param3.
If you can establish a ssh connection from the Linux server where WorkFusion is running to the Linux server where you need to execute your script, you may use the above code as well, but this time your invoke call should be something as below:
String output = invoke(new ProcessBuilder(new String[] {
"ssh",
"user2@host2",
"""echo \$HOME"""
}));
}
This will print the value of HOME variable declared for user2 on host2.