java实现ssh登录linux并执行命令的三种实现方式
作者:坚持奋斗的李洛克
文章介绍了三种在Java中实现SSH登录Linux并执行命令的方法,包括使用ganymed-ssh2、jsch和sshd-core,由于ganymed-ssh2和jsch的最新版本较旧,可能无法与较新的Linux系统兼容,而sshd-core一直在更新,推荐使用
java实现ssh登录linux并执行命令
1.方法一
使用ganymed-ssh2
<dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency>
但是这个包最新版本是2014年之后,就没有更新了,linux 操作系统安装 open-ssh 8.5及更高级版本,就一直提示连接失败。就不再提供demo
2.方法二
jsch 暂时能使用,也是很久没有更新了,恐怕后续也会有无法匹配系统最新协议的问题。
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
public class RemoteExecuteCommand { public static List<String> remoteExecute(Session session, String command) { System.out.println("CMD:" + command); List<String> resultLines = new ArrayList<>(); ChannelExec channel = null; try { channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); InputStream input = channel.getInputStream(); channel.connect(50000); BufferedReader inputReader = new BufferedReader(new InputStreamReader(input)); String inputLine = null; while ((inputLine = inputReader.readLine()) != null) { System.out.println(inputLine); resultLines.add(inputLine); } } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("最后关闭channel"); channel.disconnect(); } return resultLines; } } String usrName = "root"; String passWord = "******"; String remoteIP = "*****"; String remoteIP = "ifconfig"; JSch jSch = new JSch(); try { Session session = jSch.getSession(usrName, remoteIP); session.setPassword(passWord); session.setConfig("StrictHostKeyChecking", "no"); session.connect(100000); session.setTimeout(15000); if (session.isConnected() == true) { System.out.println("Host(" + remoteIP + ") connected!"); } ChannelExec channel = (ChannelExec) session.openChannel("exec"); remoteExecute(session, cmd);
3.方法三
使用sshd-core,一直在更新
<dependency> <groupId>org.apache.sshd</groupId> <artifactId>sshd-core</artifactId> <version>2.8.0</version> </dependency>
//SshConnection 是自定义的,包含userName,pwd,hostName的实体类 public static SshResponse runCommand(SshConnection conn, String cmd, long timeout) throws IOException { SshClient client = SshClient.setUpDefaultClient(); try { // Open the client client.start(); // Connect to the server ConnectFuture cf = client.connect(conn.getUsername(), conn.getHostname(), 22); ClientSession session = cf.verify().getSession(); session.addPasswordIdentity(conn.getPassword()); session.auth().verify(TimeUnit.SECONDS.toMillis(timeout)); // Create the exec and channel its output/error streams ChannelExec ce = session.createExecChannel(cmd); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); ce.setOut(out); ce.setErr(err); // Execute and wait ce.open(); Set<ClientChannelEvent> events = ce.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout)); session.close(false); // Check if timed out if (events.contains(ClientChannelEvent.TIMEOUT)) { throw new RuntimeException(conn.getHostname()+" 命令 "+cmd+ "执行超时 "+timeout); } return new SshResponse(out.toString(), err.toString(), ce.getExitStatus()); } finally { client.stop(); } } public static void main(String[] args) throws IOException { String hostName = "*****"; String userName = "root"; String pwd = "****"; SshConnection conn = new SshConnection(userName,pwd,hostName); // &&-表示前面命令执行成功在执行后面命令; ||表示前面命令执行失败了在执行后面命令; ";"表示一次执行两条命令 String cmd = "pwd && ps -ef|grep tomcat"; SshResponse response = runCommand(conn,cmd,15); System.out.println("==error=>"+response.getErrOutput()); System.out.println("===return==>"+response.getReturnCode()); System.out.println("===stdOut===>"+response.getStdOutput()); }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。