@tsing1226
        
        2016-10-20T04:23:15.000000Z
        字数 2148
        阅读 1180
    java
sudo chmod u+x /path/to/shellfilename.sh
<dependency><groupId>org.jvnet.hudson</groupId><artifactId>ganymed-ssh2</artifactId><version>build210-hudson-1</version></dependency>
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;//ip地址private String charset = Charset.defaultCharset().toString();private String userName;//用户名private String password;//密码/*** 构造函数 连接远程** @param ipAddr* @param userName* @param password* @param charset*/public RemoteShellTool(String ipAddr, String userName, String password,String charset) {this.ipAddr = ipAddr;this.userName = userName;this.password = password;if (charset != null) {this.charset = charset;}}public RemoteShellTool(String ipAddr, String userName, String password) {this.ipAddr = ipAddr;this.userName = userName;this.password = password;}/*** 登陆** @return* @throws IOException*/public boolean login() throws IOException {conn = new Connection(ipAddr);conn.connect(); // 连接if (conn.isAuthenticationComplete()) {System.out.println("是");}return conn.authenticateWithPassword(userName, password); // 认证}/*** 运行** @param cmds* @return*/public String exec(String cmds) {InputStream in = null;String result = "";try {if (this.login()) {Session session = conn.openSession(); // 打开一个会话session.execCommand(cmds);in = session.getStdout();result = this.processStdout(in, this.charset);session.close();conn.close();}} catch (IOException e1) {e1.printStackTrace();}return result;}/*** 标准输出** @param in* @param charset* @return*/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();}/*** @param args* @throws IOException* @throws InterruptedException*/public static void main(String[] args) throws IOException, InterruptedException {RemoteShellTool tool = new RemoteShellTool("10.7.111.117", "root","123456", "utf-8");String result = tool.exec("/home/root/test.sh");System.out.print(result);}}