How to execute a shell script to start a service by sudo command in Linux via Java Ex:cmd="sudo path/script.sh start"
This Java program will execute commands in linux. Even I am able to do 'sudo ls -lt path' and also 'sudo path/script.sh start'
//Java
public List<String> sshConnection(String usr,String host,int port,String pass)
{
Session session=null;
List<String> outputList = new ArrayList<String>();
try
{
JSch jsch = new JSch();
session = jsch.getSession(usr, host, port);
session.setPassword(pass);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
//String cmd="sudo ls path"; //working fine
String cmd="sudo path/script.sh start"; //service is not starting..but getting the exact output as linux
ChannelExec channelEx=new ChannelExec();
channelEx = (ChannelExec) session.openChannel("exec");
if(cmd.contains("sudo"))
{
channelEx.setPty(true);
}
((ChannelExec) channelEx).setCommand(cmd);
channelEx.connect();
InputStream cmdOp = channelEx.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(cmdOp));
String printOp;
while ((printOp = br.readLine()) != null)
{
outputList.add(printOp);
}
br.close();
channelEx.disconnect();
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
finally
{
if (channelEx != null)
{
channelEx.disconnect();
}
}
if(session!=null)
{
session.disconnect();
}
System.out.println("disconnected successfully");
return outputList;
}
I executed the same command directly in linux and got a output telling the 'service is running' with the process id.When I did grep for the process ID using ps command it displayed the service with the same process ID.
But when I executed the same command via the above Java Program,I got the exact output('service is running') as linux with the process ID in the output console.After the java program execution, I did grep for the process ID(from Java output console) in linux,no such process was running with that process ID .
I am not able to find where it is going wrong.
Please help !