首先在远程服务器上编写一个测试脚本test.sh,并赋予可执行权限:chmod +x test.sh
#!/bin/bash echo 'test22' echo $1
$1是脚本传进来的第一个参数,我们控制台打印一下这个参数
新建maven项目,添加依赖:
<dependency> <groupId>org.jvnet.hudson</groupId> <artifactId>ganymed-ssh2</artifactId> <version>build210-hudson-1</version> </dependency>
编写一个工具类:
package com.xj.runshell; 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.ipAddr = ipAddr; this.userName = userName; this.password = password; if (charset != null) { this.charset = charset; } } public boolean login() throws IOException { conn = new Connection(ipAddr); conn.connect(); // 连接 return conn.authenticateWithPassword(userName, password); // 认证 } 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; } 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 */ public static void main(String[] args) { RemoteShellTool tool = new RemoteShellTool("192.168.27.41", "hadoop", "hadoop", "utf-8"); String result = tool.exec("./test.sh xiaojun"); System.out.print(result); } }
main函数中执行了./test.sh xiaojun这个命令,控制台打印出:
test22
xiaojun
这个简单的远程调用shell demo就算完了。