Im trying to use Jsch to execute a .csh script on a remote server. I am able to execute commands like cp, mv and ls. But when I try to execute a script that internally references some environment variables, the script is exiting with status 1. There is an INTERNAL_ENV_VARIABLE referenced inside script.sh that is not accessible when i run using exec. Is there some way I can run the .csh script from exec that will take care of this dependency ?
Using the shell instead of exec is not an option as there are multiple authentication levels when we open a shell and would make the test framework we are developing, dependent on multiple credentials.
Commands I am calling to navigate to the script directory and execute the script.
util.executeCommand(session,"cd " + script directory+";"+"./script.csh");
console output
com.jcraft.jsch.Channel$MyPipedInputStream@4bff64c2 INTERNAL_ENV_VARIABLE: Undefined variable. exit-status: 1
Method to Execute the Command : executeCommand
public int executeCommand(Session session, String script) throws JSchException, IOException { System.out.println("Execute Script " + script); ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); ((ChannelExec)channelExec).setPty(true); InputStream in = channelExec.getInputStream(); channelExec.setInputStream(null); channelExec.setErrStream(System.err); channelExec.setCommand(script); channelExec.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); System.out.println(channelExec.getErrStream()); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channelExec.isClosed()) { System.out.println("exit-status: " + channelExec.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { System.out.println(ee); } } channelExec.disconnect(); return channelExec.getExitStatus(); }
Method to Create a Session : createSession
public Session createSession(String user, String host, int Port, String Password) throws JSchException { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, Port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(Password); session.connect(5000); System.out.println(session.isConnected()); return session; } }
Advertisement
Answer
util.executeCommand(session,"cd " + script directory); util.executeCommand(session,"ls "+"script.csh"+" && exit 0 || exit 1" ); util.executeCommand(session,"./script.csh");
Each of these command invocations will run independently of the others. Notably, each command will start with the same working directory–probably the home directory of whatever user you used to log in–and the cd
command that you invoke first won’t have any effect on the other commands that you run.
If you want to string together a sequence of commands, you have to run them in one invocation:
util.executeCommand(session, "cd /some/directory && ./script.csh");