导入maven依赖
<dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency>
实现类
import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class test { public static void main(String[] args) throws IOException { String host = "192.168.111.130"; //设备IP地址 int port = 22; //ssh端口号 String username = "root"; //连接用户 String password = "123"; //密码 // 创建连接 Connection conn = new Connection(host, port); // 启动连接 conn.connect(); // 验证用户密码 conn.authenticateWithPassword(username, password); Session session = conn.openSession(); session.execCommand("ansible webserver -m shell -a \'w\'"); //这里放要在Linux上执行的命令 // 消费所有输入流 // session.getStdout()输出的是结果,但是它是以一行的形式输出,所以传递给consumeInputStream进行换行 String inStr = consumeInputStream(session.getStdout()); String errStr = consumeInputStream(session.getStderr()); session.close(); conn.close(); } /** * 消费inputstream,并返回 */ public static String consumeInputStream(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String s ; StringBuilder sb = new StringBuilder(); while((s=br.readLine())!=null){ System.out.println(s); sb.append(s); } return sb.toString(); } }