first write a test script test.sh on the remote server and give executable permissions: chmod +x test.sh
#!/bin/bash
Echo $
The first argument that the script passes in, now prints the first argument that comes in.
adding dependencies in Pom
| <dependency> <groupId>org.jvnet.hudson</groupId> <artifactid>ganymed-ssh2</artifact Id> <version>build210-hudson-1</version> </dependency> |
Creating a tool class
Package cn.ctyun.audit.utils;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.nio.charset.Charset;
Import ch.ethz.ssh2.Connection;
Import ch.ethz.ssh2.Session;
public class Remoteshelltool {private Connection conn;
Private String ipaddr;
Private String charset = Charset.defaultcharset (). toString ();
Private String UserName;
private String password; Public Remoteshelltool (String ipaddr, String userName, string password, string charset) {this.i
PADDR = ipaddr;
This.username = UserName;
This.password = password;
if (charset!= null) {this.charset = charset;
} public Boolean login () throws IOException {conn = new Connection (IPADDR); Conn.connect (); Connection return Conn.authenticatewithpassword (userName, password);
Authentication} public boolean exec (String cmds) { InputStream in = null;
String result = "";
Boolean flag = false;
try {if (This.login ()) {Session sessions = Conn.opensession ();//Open a conversation
Session.execcommand (CMDS);
in = Session.getstdout ();
result = This.processstdout (in, This.charset);
Session.close ();
Conn.close (); Flag = true;
} catch (IOException E1) {e1.printstacktrace ();
return flag; public string Processstdout (InputStream in, String charset) {byte[] buf = new byte[1024
];
StringBuffer sb = new StringBuffer ();
try {while (In.read (BUF)!=-1) {Sb.append (new String (BUF, CharSet));
} catch (IOException e) {e.printstacktrace ();
} return sb.tostring (); The public static void main (string[] args) {Remoteshelltool tool = new Remoteshelltool ("HDP03",
"Root", "Hadoop", "utf-8");
Boolean exec = Tool.exec ("/root/apps/jdk1.7.0_67/bin/java-jar Auditservice.jar");
System.out.print (exec);
}
}Note: If you need to write a full path to the JDK to execute the jar command, you will not find the Java environment variable.
If you do not want to enter a password, you can refer to the following article
Click to open the link