In my Java program what I am trying to do is:
First, I connect to a Unix server and execute one shell script. But in that shell script, you have to select the option to perform the different operation once the option is selected.
For example:
Please select from below menu options
1. Create directory and subdirectory
2. Copy files
3. Update paths
4. Press 9 to exit
Here each option performs different operations and upon selecting any asks for further input. For ex: If I select an option 1 it will ask for the path:
Please enter the path where you want to create a directory
Now my question is: How can I enter this input while running this shell script from Java code?
Below code is written For connecting to unix server and execution of shell script:
JSch jsch = new JSch();
String command = "/tmp/myscript.sh";
Session session = jsch.getSession(user, host, 22);
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (channel.getExitStatus() == 0) {
System.out.println("Command executed successully.");
}
break;
}
}
channel.disconnect();
session.disconnect();
channel.setInputStream(System.in);.myscript.shnobody but you has, you executed something likeString[]{"bash", "-c", "read -p 'need input: ' input; echo \"got input: $input\""}-- that way your code wouldn't require dependencies it doesn't contain.