java调用本地进程和远程进程
导读:Java 是一种跨平台的编程语言,可以用于开发本地应用程序和 Web 应用程序。在开发中,我们可能需要调用本地进程或远程进程来执行一些操作。Java 提供了调用本地进程和远程进程的 API。下面分别介绍这两种方法。调用本地进程:try {P...
Java 是一种跨平台的编程语言,可以用于开发本地应用程序和 Web 应用程序。在开发中,我们可能需要调用本地进程或远程进程来执行一些操作。Java 提供了调用本地进程和远程进程的 API。下面分别介绍这两种方法。
调用本地进程:
try { Process p = Runtime.getRuntime().exec("cmd /c dir"); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (IOException e) { e.printStackTrace(); }
Java 通过 Runtime.getRuntime().exec() 方法调用本地进程,可以执行任何系统命令。上面的代码调用了 Windows 系统的 dir 命令,输出当前目录中的文件列表。
调用远程进程:
try { String host = "192.168.0.2"; String user = "username"; String password = "password"; JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand("ls -l"); BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream())); channel.connect(); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); channel.disconnect(); session.disconnect(); } catch (JSchException | IOException e) { e.printStackTrace(); }
Java 远程调用需要依赖第三方库,如上面示例代码所使用的 JSch 库,我们也可以使用其他库,如 Apache 的 SSHD 库。上面的代码通过 SSH 协议连接到远程服务器,并执行 ls -l 命令,输出当前目录中的文件列表。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: java调用本地进程和远程进程
本文地址: https://pptw.com/jishu/534211.html