java调用linux的cmd执行命令
-
要在Java中调用Linux的命令,可以使用Java的Runtime类和Process类。下面是一个示例代码:
“`java
import java.io.BufferedReader;
import java.io.InputStreamReader;public class LinuxCommand {
public static void main(String[] args) {
String command = “ls /home”; // 要执行的Linux命令try {
Process process = Runtime.getRuntime().exec(command); // 执行命令
int exitCode = process.waitFor(); // 等待命令执行完成BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); // 获取命令输出流
String line;
StringBuilder output = new StringBuilder();
while ((line = reader.readLine()) != null) { // 读取输出
output.append(line).append(“\n”);
}System.out.println(“命令输出结果:\n” + output.toString());
System.out.println(“命令退出码:” + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
“`上述代码通过Java的Runtime类的exec方法执行Linux命令,并通过Process类获取命令的输出流和退出码。你可以根据需要修改command变量的值,来执行不同的命令。
注意,这个例子只适用于非交互式命令,如果需要执行交互式命令,可以考虑使用Apache Commons Exec库,它提供了更多功能和更好的API来执行命令。你可以通过添加相应的依赖来使用这个库。
2年前 -
在Java中调用Linux的命令行(cmd)执行命令有多种方法。下面是其中一种常用的方法:
1. 使用Runtime类的exec()方法执行命令:
“`java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;public class CommandExecutor {
public static void main(String[] args) {
try {
// 执行命令
Process process = Runtime.getRuntime().exec(“ls -l”);// 获取命令输出的InputStream
InputStream inputStream = process.getInputStream();// 创建读取器
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));// 逐行读取输出
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}// 关闭流
reader.close();} catch (IOException e) {
e.printStackTrace();
}
}
}
“`
以上代码中,我使用`exec()`方法执行了一个`ls -l`命令,并读取了命令的输出。你可以根据需要替换成其他Linux命令。请注意,执行命令时需要捕获IOException。2. 使用ProcessBuilder类执行命令:
“`java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;public class CommandExecutor {
public static void main(String[] args) {
try {
// 创建命令列表
Listcommand = new ArrayList<>();
command.add(“ls”);
command.add(“-l”);// 创建ProcessBuilder对象
ProcessBuilder processBuilder = new ProcessBuilder(command);// 执行命令
Process process = processBuilder.start();// 获取命令输出的InputStream
InputStream inputStream = process.getInputStream();// 创建读取器
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));// 逐行读取输出
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}// 关闭流
reader.close();} catch (IOException e) {
e.printStackTrace();
}
}
}
“`
以上代码中,我使用`ProcessBuilder`类来创建一个命令列表,并使用`start()`方法执行该命令。然后我按照与第一种方法相同的方式读取命令输出。3. 使用Java中的SSH库连接到Linux并执行命令:
可以使用一些Java库,如JSch,来通过SSH连接到Linux,并执行命令。这种方法适用于需要远程执行命令的情况。以下是使用JSch的示例代码:
“`java
import com.jcraft.jsch.*;public class CommandExecutor {
public static void main(String[] args) {
try {
// 创建SSH会话
JSch jsch = new JSch();
Session session = jsch.getSession(“用户名”, “主机名”, 22);
session.setPassword(“密码”);// 配置SSH会话
java.util.Properties config = new java.util.Properties();
config.put(“StrictHostKeyChecking”, “no”);
session.setConfig(config);// 连接到SSH服务器
session.connect();// 打开SSH通道
Channel channel = session.openChannel(“exec”);// 设置命令
((ChannelExec)channel).setCommand(“ls -l”);// 获取命令输出
InputStream inputStream = channel.getInputStream();// 连接通道
channel.connect();// 创建读取器
byte[] buffer = new byte[1024];
int bytesRead;
StringBuilder output = new StringBuilder();while ((bytesRead = inputStream.read(buffer)) != -1) {
output.append(new String(buffer, 0, bytesRead));
}// 输出结果
System.out.println(output);// 关闭流和通道
inputStream.close();
channel.disconnect();// 断开SSH会话
session.disconnect();} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
“`
以上代码使用JSch库与Linux主机建立SSH连接,并执行了一个`ls -l`命令。请注意,需要将”用户名”、“主机名”、“密码”替换为实际的SSH登录凭据。4. 使用SSH库连接到Linux并执行远程脚本文件:
如果需要在远程Linux主机上执行脚本文件,也可以使用SSH库来实现。以下是一个示例代码:
“`java
import com.jcraft.jsch.*;public class CommandExecutor {
public static void main(String[] args) {
try {
// 创建SSH会话
JSch jsch = new JSch();
Session session = jsch.getSession(“用户名”, “主机名”, 22);
session.setPassword(“密码”);// 配置SSH会话
java.util.Properties config = new java.util.Properties();
config.put(“StrictHostKeyChecking”, “no”);
session.setConfig(config);// 连接到SSH服务器
session.connect();// 打开SSH通道
Channel channel = session.openChannel(“exec”);// 设置脚本文件路径和参数
String scriptFilePath = “/home/user/script.sh”;
String scriptArguments = “arg1 arg2″;// 设置命令
((ChannelExec)channel).setCommand(scriptFilePath + ” ” + scriptArguments);// 获取命令输出
InputStream inputStream = channel.getInputStream();// 连接通道
channel.connect();// 创建读取器
byte[] buffer = new byte[1024];
int bytesRead;
StringBuilder output = new StringBuilder();while ((bytesRead = inputStream.read(buffer)) != -1) {
output.append(new String(buffer, 0, bytesRead));
}// 输出结果
System.out.println(output);// 关闭流和通道
inputStream.close();
channel.disconnect();// 断开SSH会话
session.disconnect();} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
“`
以上代码连接到远程Linux主机并执行了一个脚本文件。请注意,需要将”用户名”、“主机名”、“密码”替换为实际的SSH登录凭据,并将”script.sh”替换为实际的脚本文件路径。5. 使用Java中的Apache Commons-Net库连接到Linux并执行命令:
另一种方法是使用Apache Commons-Net库中的SSH类。以下是一个示例代码:
“`java
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;import java.io.IOException;
import java.io.InputStream;public class CommandExecutor {
public static void main(String[] args) {
FTPClient ftp = new FTPClient();
try {
// 连接到SSH服务器
http://ftp.connect(“主机名”);
int reply = http://ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
http://ftp.disconnect();
System.err.println(“FTP server refused connection.”);
System.exit(1);
}// 登录SSH服务器
http://ftp.login(“用户名”, “密码”);// 执行命令
String command = “ls -l”;
InputStream inputStream = http://ftp.sendCommand(command);// 读取输出
byte[] buffer = new byte[1024];
int bytesRead;
StringBuilder output = new StringBuilder();while ((bytesRead = inputStream.read(buffer)) != -1) {
output.append(new String(buffer, 0, bytesRead));
}// 输出结果
System.out.println(output);// 断开连接
http://ftp.logout();
http://ftp.disconnect();} catch (IOException e) {
e.printStackTrace();
}
}
}
“`
以上代码使用Apache Commons-Net库中的FTPClient类来连接到Linux主机并执行了一个`ls -l`命令。请注意,需要将”主机名”、“用户名”、“密码”替换为实际的SSH登录凭据。这些方法提供了多种在Java中调用Linux命令行执行命令的选项。你可以根据你的需求和偏好选择其中的一种方法。
2年前 -
在Java中调用Linux的命令可以通过使用Runtime或ProcessBuilder类来实现。具体步骤如下:
1. 使用Runtime类调用命令:
“`
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;public class CmdCommand {
public static void main(String[] args) {
try {
String cmd = “ls -l”; // 你要执行的命令
Runtime runtime = Runtime.getRuntime();// 执行命令并获取输出结果
Process process = runtime.exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}// 等待命令执行完毕并获取返回值
int exitCode = process.waitFor();
System.out.println(“命令执行结果:” + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
“`通过Runtime类的exec方法可以在Java代码中调用Linux的命令。使用BufferedReader读取命令的输出结果,并通过循环逐行输出。最后,通过process.waitFor()方法等待命令执行完毕,并通过process.exitValue()方法获取命令的返回值。
2. 使用ProcessBuilder类调用命令:
“`
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;public class CmdCommand {
public static void main(String[] args) {
try {
Listcommand = new ArrayList<>();
command.add(“ls”);
command.add(“-l”);ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}int exitCode = process.waitFor();
System.out.println(“命令执行结果:” + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
“`使用ProcessBuilder类可以更加灵活地构建命令参数。通过创建List对象并添加命令及参数,在ProcessBuilder中使用该列表。其余的步骤与Runtime方法相同。
无论是使用Runtime类还是ProcessBuilder类,可以根据实际需求构建命令,并通过Java代码执行Linux命令。注意始终谨慎处理用户输入,避免执行恶意代码。
2年前