I have three machines and I need to ssh
to them one by one, and then sudo a command.
I need the JSch to do the following things:
ssh <user>@<machine>
sudo <some command>
This is the code block how I use to run JSch:
String homeFolder = System.getProperty("user.home");
JSch jsch = new JSch();
jsch.addIdentity(homeFolder + "/.ssh/id_rsa.pub");
jsch.setKnowHosts(homeFolder + "/.ssh/known_hosts");
final Session session = jsch.getSession(user, machine);
session.connect();
StringBuilder response = new StringBuilder();
try {
final Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("sudo /etc/init.d/eedir status")
channel.connect();
try {
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
out.write((password + System.getProperty("line.separator")).getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while (null != (line = reader.readLine())) {
System.out.println(line);
}
} finally {
channel.disconnect();
}
} finally {
session.disconnect();
}
My problem is that I can use this program successfully to get the status of the eedir service on two of the three machines I have, but not the last one.
I can ssh to the remote machine with the given user name and then run this command directly:
sudo /etc/init.d/eedir status
The username used in ssh is already configured in my /etc/sudoers
.
So, my questions are:
Why JSch can run this program on two of the three machines while the rest one cannot? The sudoers' configuration is exactlly the same on these machines.
And another question is: why sudo on the real machine can run without typing the password again if I configured the current user in sudoers, while JSch sudo require the password in the program?
Any directions are really appreciated. If there are some potential errors that I might have under my current circumstances, welcome everybody to point them out.
Thanks.