Reputation: 159
I want to execute a shell script from java. I have the next code
ProcessBuilder pb2 = null;
if (this.args.size() == 0) {
pb2 = new ProcessBuilder(file.getPath());
} else if (this.args.size() > 0) {
pb2 = new ProcessBuilder(file.getPath(), this.args.get(0));
}
Process p2;
p2 = pb2.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
log(line);
}
But I'm getting Permission denied
. I have try execute the file with sh
in the beginning, but the code it's not working.
ProcessBuilder pb2 = null;
if (this.args.size() == 0) {
pb2 = new ProcessBuilder("sh", file.getPath());
} else if (this.args.size() > 0) {
pb2 = new ProcessBuilder("sh", file.getPath(), this.args.get(0));
}
Process p2;
p2 = pb2.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
log(line);
}
I could give it permission with chmod a+x
but the idea is to do it automatic.
Update: I tried the first code with file.setExecutable(true)
but nothing happens, I don't get Permission Denied
but the file is not executing
Upvotes: 0
Views: 86
Reputation: 718798
If you want to execute a file as a shell script, it must have execute permission(s) set. There is no way around this.
If you are creating the script file from your Java application then your application could change the file permissions after it has created the file.
If some user is uploading this script, then you need to be really, really sure that you trust the user. There are all sorts of nasty things that could happen if you accepted an shell script from someone who isn't trustworthy. (This includes consequences of innocent but dangerous mistakes.)
Update: I tried the first code with
file.setExecutable(true)
but nothing happens, I don't get Permission Denied but the file is not executing.
Something has happened. You have stopped getting the Permission Denied message!
Next step will be to debug the script you are generating / executing:
Eyeball it. Check that the "hash bang" line is correct. Look for other errors.
Capture the stdout and stderr from the script, and check for errors.
Add some "trace prints" to the script; e.g.
echo "here 1" >> /tmp/log
Is the child process waiting for input from the Java parent process?
Are you reading the child's standard output AND standard error in the parent process?
Upvotes: 1