1

I am trying to execute python script using a JSch, what I want is to run the python script from a .sh file using a different interpreter (shebang).

Here is the content of my shell script file (fileExec.sh):

#!/usr/bin/env python
print 'hello from python'

It looks like the shebang cannot be changed since I getting:

bash : print command is not found

Here is my Java code:

session = newSessionFor(user, host, port);
Channel channel = session.openChannel("exec");

File shFile = new File("fileExec.py");
FileWriter writer = new FileWriter(shFile);
writer.write(shebang + "\n");
writer.write(command);
writer.close();

PrintWriter printWriter = new PrintWriter(shFile);
printWriter.println(shebang);
printWriter.println(command);
printWriter.close();

((ChannelExec) channel).setCommand(FileUtils.readFileToByteArray(shFile));

3 Answers 3

1

The shebang is only used by the OS when executing a file.

You are not executing a file, you are basically copy-pasting the contents of a python file onto your shell prompt.

If you don't want to store and execute a file on the server, you can run a Python command from a shell with python -c yourcommand. Here's how that looks in a terminal, feel free to try:

user@host ~$ python -c 'print "hello world"'
hello world

To do this in your program, add a method to escape an arbitrary string in shells:

static String escapeForShell(String s) {
  return "'" + s.replaceAll("'", "'\\\\''") + "'";
}

then run

((ChannelExec) channel).setCommand("python -c " + escapeForShell(command));

where String command = "print 'hello from python'";

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not very good with Java, but it could be checking the file extension before checking the hashbang. You should change the file to fileExec.py to make sure, or just fileExec.

(You also appear to be calling the wrong file in the java code?)

Comments

0

File extensions should not be relevant, but for consistency you usually don't call a python script fileExec.sh.

If you test fileExec.sh from command line, assuming you set the execute permission on it, it should work:

$ chmod +x fileExec.sh
$ ./fileExec.sh
hello from python

However, there's no need to rely on shebang and changing file permissions, just do:

$ python fileExec.sh

from the command line and from your java program too

((ChannelExec)channel).setCommand("/usr/bin/python /path/to/fileExec.sh");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.