1.在大数据时代,服务器使用的频率难免上升,工作中难免会出现频繁使用的时候,有些场景不方便切换到服务器去操作,比如调用一个服务器的命令,但是要在程序里执行,当然不能手动去执行啦,所以java调用ssh就尤为重要。 首先,添加maven依赖 <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>1.8.5</version> </dependency> <!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 --> <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>build210</version> </dependency>
上一段demo
package quartz; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @Author: Monkey * @Date: Created in 14:15 2016/4/16. * @Description: Test SSH */ public class TestSSH { /** * Run SSH command. * @param host * @param username * @param password * @param cmd * @return exit status * @throws IOException */ public static int runSSH(String host, String username, String password, String cmd) throws IOException { System.out.println("running SSH cmd [" + cmd + "]"); Connection conn = getOpenedConnection(host, username, password); Session sess = conn.openSession(); sess.execCommand(cmd); InputStream stdout = new StreamGobbler(sess.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); while (true) { String line = br.readLine(); if (line == null){ break; } System.out.println(line); } sess.close(); conn.close(); return sess.getExitStatus().intValue(); } /** * return a opened Connection * @param host * @param username * @param password * @return * @throws IOException */ private static Connection getOpenedConnection(String host, String username, String password) throws IOException { System.out.println("connecting to " + host + " with user " + username + " and pwd " + password); //添加SSH连接端口,默认22 Connection conn = new Connection(host, 22); conn.connect(); // make sure the connection is opened boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (isAuthenticated == false) throw new IOException("Authentication failed."); return conn; } public static void main(String[] args) throws Exception{ String cmd = "mkdir -p /home/1.txt"; runSSH("10.0.43.106", "root", "monkey", cmd); } }
当然,服务器要开放22端口才行,正常情况下都是开启了的。然后就看到了对应的文件已经生成了。