我的要求如下:
我必须使用我的凭据登录到Unix机箱,并且一旦登录,我必须为不同的用户执行sudo。一旦sudo成功,我不得不在nohup中调用shell。完成执行后,关闭通道和会话。使用JSch的多个命令
我尝试了使用sudo命令连接的第一步,但我不知道如何在sudo命令后调用shell脚本。
在下面的代码中,我可以执行sudo命令,但是在获得sudo访问权后,如何在用户masteruser
的nohup中执行shell。所以创建我的外壳所需的文件的所有者为masteruser
。
public class SSHUploader {
Session session = null;
public SSHUploader(){
}
public void connect(){
try {
JSch jsch = new JSch();
session = jsch.getSession("user", "xxx.xxx.xx.xx", 22);
session.setPassword("test");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void executeCommand(String script) throws JSchException, IOException{
System.out.println("Execute sudo");
String sudo_pass = "test";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
((ChannelExec) channel).setCommand(script);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass + "\n").getBytes());
out.flush();
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()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee);
}
}
channel.disconnect();
System.out.println("Sudo disconnect");
}
public void disconnect(){
session.disconnect();
}
public static void main(String... args) throws JSchException, IOException {
SSHUploader up = new SSHUploader();
up.connect();
up.executeCommand("sudo -u masteruser bash");
up.disconnect();
}
}
[如何使用JSch执行多个操作](https://stackoverflow.com/questions/7419513/how-to-perform-multiple-operations-with-jsch) – Gregor