Java – multiple commands using jsch
•
Java
My requirements are as follows:
I tried the first step of using the sudo command to connect, but I don't know how to call the shell script after the sudo command.
In the following code, I can execute the sudo command, but after obtaining sudo access, how to execute the shell in nohup in the user masteruser So create the required files and my shell will have the owner as master user
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,1024); if (i < 0) break; System.out.print(new String(tmp,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(); } }
Solution
To execute multiple commands in order, you can create the following command string:
String script ="pbrun su - user; cd /home/scripts;./sample_script.sh”
Execute it and pass this string to the above method
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码