问题
I have created the shell script to add two numbers. I want to execute that shell script from java and I am using Jsch library. Can you please help me on this.
first_num=0
second_num=0
echo -n "Enter the first number-->"
read first_num
echo -n "Enter the second number-->"
read second_num
echo "first number + second number = $ (( first_num + second_num ))"
Yes. I have checked examples in "Jsch" sites, But i am not able to enter the input to shell script.
I tried as you said. Please see the following piece of code
String command = "bash /home/opt/addtwonumber.sh 1 2"
And I changed the shell script mentioned below
$first_num
$second_num
echo "first number + second number = $ (( first_num + second_num ))"
But it doesn't work. i am getting the results like
first_number + second_number = 0
回答1:
from the examples :
String user = "USERNAME";
host = "HOSTNAME";
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
Session session=jsch.getSession(user, host, 22);
String command = "YOUR_SCRIPTFILE_HERE PARAMETER_ONE PARAMETER_TWO";
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
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 (in.available() > 0)
continue;
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
Mind you : never use while(true)
in any production-ready code, thats just ... bad code and it will break / generate deadlocks at some point, no matter how many exceptions you catch, no matter how often you insert statements like break
- it will happen.
So all you need to do is place your parameters immediately after your scriptfile and that should be about it - but that only works with commandline parameters, AFAIK it isnt easily possible to input parameters during script runtime - read
will not work for you as your script apparently isnt local. You cant use scripts which require local input, you need to switch to commandline parameters - namely $1
, $2
and so on.
Heres the interface for MyUserInfo
: *click
来源:https://stackoverflow.com/questions/32605233/how-to-pass-the-input-value-to-shell-script-using-java