/*** * 第一种方法,仅仅执行命令无须关注返回结果 * @throws Exception */ public static void exeCmd() throws Exception{ Runtime r = Runtime.getRuntime(); //执行linux命令,不关心返回结果,此处,可以执行一个shell脚本,或者python脚本 Process p = r.exec("tesseract 12.jpg ko "); p.waitFor(); } /** * 第二种方法,需要执行命令完后的返回结果 * @return result * @throws Exception */ public static String getCodeResult()throws Exception{ exeCmd(); //执行一个命令需要展示返回结果的 Runtime r = Runtime.getRuntime(); Process p = r.exec("cat ko.txt "); p.waitFor(); BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; StringBuffer sb=new StringBuffer(); while ((line = b.readLine()) != null) { sb.append(line).append("\n"); } System.out.println("result: "+sb.toString()); b.close(); return sb.toString(); }
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.53</version> </dependency>
package com.java.ssh; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class RemoteSSH { /** * 远程 执行命令并返回结果调用过程 是同步的(执行完才会返回) * @param host 主机名 * @param user 用户名 * @param psw 密码 * @param port 端口 * @param command 命令 * @return */ public static String exec(String host,String user,String psw,int port,String command){ String result=""; Session session =null; ChannelExec openChannel =null; try { JSch jsch=new JSch(); session = jsch.getSession(user, host, port); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setPassword(psw); session.connect(); openChannel = (ChannelExec) session.openChannel("exec"); openChannel.setCommand(command); // int exitStatus = openChannel.getExitStatus(); openChannel.connect(); InputStream in = openChannel.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String buf = null; while ((buf = reader.readLine()) != null) { result+= new String(buf.getBytes("gbk"),"UTF-8")+" \n"; } } catch (JSchException | IOException e) { result+=e.getMessage(); }finally{ if(openChannel!=null&&!openChannel.isClosed()){ openChannel.disconnect(); } if(session!=null&&session.isConnected()){ session.disconnect(); } } return result.trim(); } public static void main(String[] args) { String exec = exec("192.168.1.187", "user", "pwd", 22, "tesseract 12.jpg ko && cat ko.txt "); // String exec = exec("192.168.1.187", "user", "pwd", 22, "ls -l "); System.out.println(exec); } }
藏家569 2025-03-28
藏家838 2025-03-29
奇美拉 2025-03-29
许老头 2025-03-28
藏家942 2025-03-28
mei 2025-03-28
藏家113 2025-03-28
藏家518 2025-03-28
藏家372 2025-03-28
藏家372 2025-03-28