Unable to run Shell Script - java

Hi i am trying to run shell script from following code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ScriptTest {
public static void main(String[] args){
BufferedReader stdErr=null;
BufferedReader stdIn=null;
try{
System.out.println("In Script");
String[] commands= {"ls"};
Process process = Runtime.getRuntime().exec("/mobilityapps/testScript/testScript.sh");
stdIn= new BufferedReader(new InputStreamReader(process.getInputStream()));
stdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String inline= stdIn.readLine();
String errline =stdErr.readLine();
System.out.println("*Inline*"+inline);
System.out.println("*Errline*"+errline);
while(inline!=null){
System.out.println(inline);
inline=stdIn.readLine();
}
while(errline!=null){
System.out.println(errline);
errline=stdErr.readLine();
}
System.out.println("Process Exit Value: "+process.waitFor());
}catch(Exception excp){
excp.printStackTrace();
}
}
}
The script i am trying to call is
CURRDATE=`date '+%d%b%Y'`
TIMESTAMP=`date '+%H:%M'`
BASE_PATH=/mobilityapps/testScript
LOGFILE=${BASE_PATH}/logs_${CURRDATE}_${TIMESTAMP}.log
echo ${CURRDATE} ${TIMESTAMP}>>${LOGFILE}
All both the script and Java program are in the same directory.
When i run testScript.sh from PUTTY it runs fine
But when i run from Java program Process Exit Value is 255
Can anyone suggest the changes?

Try replacing the path
Runtime.getRuntime().exec("/mobilityapps/testScript/testScript.sh");
with
Runtime.getRuntime().exec("./mobilityapps/testScript/testScript.sh");
If you just use / at the begining, it means that it's a absolute path.
Using '.' indicates that is a relative path.

Related

Converting interactive shell output to plain text

I am trying to view the temperature table for my CPU on my Linux machine with Java. This bit of code will display the shell output for other commands, ls, cat file, but will not display watch sensors as it returns an interactive output. Is there a way I can convert it to plain text somehow?
Error: [/usr/bin/watch, sensors]
Error opening terminal: unknown.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class tempapp{
public static void main (String args[]) throws IOException, InterruptedException {
//build command
List<String> commands = new ArrayList<String>();
commands.add("/usr/bin/watch");
//args
commands.add("sensors");
System.out.println(commands);
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/ethano"));
pb.redirectErrorStream(true);
Process process = pb.start();
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
}
//Check result
if (process.waitFor() == 0){
System.out.println("\n success");
System.exit(0);
}
//weird termination
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}
}
All that watch does is call the command it is given (sensors in this case) once every two seconds. You can simply have your application emulate this behaviour by calling /usr/bin/sensors in a for-loop once every two seconds (or however many times you need), therefore omitting the need to read interactive shell output.

Java: Read file from stdin then prompt user for input

I'm writing a Java program that reads a file from stdin and then prompts the user for interactive input. It should be executed like:
cat file.txt | java -jar myprog.jar
#
# ...Read file.txt then prompt user:
#
Some input please:
The problem is that after reading file.txt, the stdin seems "used up" and I don't know how to restore it to get user's input. Here's an example of what I'm trying to do:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String line;
while((line = br.readLine()) != null) {
// Do something with line
System.out.println(line);
}
br.close();
Scanner scanner = new Scanner(System.in);
String input= scanner.nextLine();
}
}
When I executed it, I get:
echo -e "foo\nbar\nbaz" | java -jar biojava-tmp.jar
foo
bar
baz
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at biojava_tmp.Main.main(Main.java:21)
How can I resolve this?
PS: In my real program I don't use Scanner, instead I use jline as below but I figure the problem is the same.
ConsoleReader console= new ConsoleReader();
console.readLine()

return string from shell to java file

I have written code in below way.
Java program 1(call shell program) => Shell program => Java program 2 (Will perform encryption).
Hence when I run the Java program 1, it should call shell and followed by java program 2. The java program 2 will return the encrypted value to me and same need to be passed to Java program 1.
When execute shell directly from command prompt, I am getting message like below.
[Serverapp01 AESEncryption]$ sh AESEncrypt.sh /keys/keyfile_05.txt texttoencrypt
AESEncrypt.sh: line 28: exit: 0UhSI9LTa/7efiT0quKUsg==: numeric argument required
My aim is to get the value 0UhSI9LTa/7efiT0quKUsg== to my java program 1. But i am not getting this value from shell to java program 1.
Any help is much appreciated.
Java Program 1
package com.abc.encrypt;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class AESEncrypt1 {
public static String callScript(String encryptionScriptPath,String KeyLocation,String textToEncrypt)
{
int value = 0;
String enc ="Error";
try
{
ProcessBuilder pb = new ProcessBuilder(encryptionScriptPath,KeyLocation,textToEncrypt);
Process p = pb.start();
value = p.waitFor();
BufferedReader br=new BufferedReader(
new InputStreamReader(
p.getInputStream()));
String line;
String temp ="";
while((line=br.readLine())!=null){
System.out.println(line);
temp = temp + line;
}
enc=temp;
}
catch (Exception e)
{
//value = 2;
enc = "ErrorOccured.."+e.toString();
}
return enc;
}
}
Shell look like below
unset CLASSPATH
KeyLocation=$1
TextToEncrypt=$2
isolatedjreLocation=/AESEncryption/isolatedjre17
JarLocation=/AESEncryption
CLASSPATH="/AESEncryption/isolatedjre17/jre17/bin"
export CLASSPATH
#echo $CLASSPATH
encryptedValue='ErrorInJava'
#echo 'Call Java Program'
encryptedValue=$($isolatedjreLocation/jre17/bin/java -cp $JarLocation/AESCryptoJava_v1.0.0.jar com.abc.AESEncryption $KeyLocation $TextToEncrypt)
#echo $encryptedValue
exit $encryptedValue

How do i execute shell script using java

How do I execute shell script file with an input parameter like "./flows.sh suspend" and print the the result to a file using java in linux?
This is a simple code to execute the shell script and read its output:
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String[] command = { "./flows.sh", "suspend" };
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s); // Replace this line with the code to print the result to file
}
}
}
To print it to a file, just replace the System.out.println for the code to write into a file
You can use the JSCH API:
http://www.jcraft.com/jsch/examples/Shell.java.html
http://www.jcraft.com/jsch/examples/Exec.java.html
Bye!

Copying a file form one drive to multiple drive won't work in Eclipse IDE

I need to copy a directory form one source form multiple destination. For example, i copied a file from my C: drive and paste it into many external drives like E:,F:,G:...etc. For this process i used the following code,
set src=%~1
:Loop
shift
set dest=%~1
if "%dest%"=="" goto :EOF
xcopy "%src%" "%dest%" /E
goto Loop
i saved this code snippet as .bat in system32 folder. Then i use this command as
C:\Windows\System32>mcopy C:\Users\FSSD\Desktop\Screenshot E: F:
i executed this command in my command prompt it executed successfully.
Then i tried to implement this command in my java application.
My java code is,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MultipleCopy{
public static void main(String args[]) {
String exe_Cmd = "c:/Windows/System32/mcopy C:/Users/FSSD/Desktop/Screenshot E: F:";
Runtime r = Runtime.getRuntime();
ProcessBuilder p = new ProcessBuilder(new String[] { "cmd.exe", "/C",
exe_Cmd });
Process pro;
try {
pro = p.start();
InputStream is = pro.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("IO Exception" + e.getMessage());
}
}
}
it was executed without any errors but the files won't copied.
My eclipse IDE's console's output is:
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>set src=C:/Users/FSSD/Desktop/Screenshot
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>shift
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>set dest=E:
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>if "E:" == "" goto :EOF
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>xcopy "C:/Users/FSSD/Desktop/Screenshot" "E:" /E
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>goto Loop
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>shift
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>set dest=F:
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>if "F:" == "" goto :EOF
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>xcopy "C:/Users/FSSD/Desktop/Screenshot" "F:" /E
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>goto Loop
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>shift
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>set dest=
C:\Users\FSSD\IndigoWorkSpace\Multi_Copy>if "" == "" goto :EOF
In this, what is my mistake, how can i get the exact output. Reply me as soon as possible. Thanks in advance...!
Parameters to ProcessBuilder may not contain spaces, instead of
String exe_Cmd = "c:/Windows/System32/mcopy C:/Users/FSSD/Desktop/Screenshot E: F:";
you need
String[] pars = {"cmd.exe", "/C","c:/Windows/System32/mcopy","C:/Users/FSSD/Desktop/Screenshot","E:","F:"};
Runtime r = Runtime.getRuntime();
ProcessBuilder p = new ProcessBuilder(pars);
But I still would rather use a Java solution, like I suggested in the comments already ;-)

Categories