java执行linux命令ssh
-
要在Java程序中执行Linux命令ssh,可以使用Java中的ProcessBuilder类来实现。下面是实现的步骤:
1. 导入所需的java.io和java.lang包:import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader;
2. 创建一个ProcessBuilder对象,并设置要执行的Linux命令:ProcessBuilder builder = new ProcessBuilder(“ssh”, “your_username@your_remote_host”, “your_command”);
3. 启动该命令并获取其输出结果:Process process = builder.start(); InputStream inputStream = process.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); }
4. 等待命令执行完毕并获取退出状态:int exitCode = process.waitFor(); if (exitCode == 0) { System.out.println(“Command executed successfully”); } else { System.out.println(“Command failed with exit code: ” + exitCode); }
注意:在执行ssh命令时,需要提前配置好SSH密钥,以免需要输入密码。
以上就是使用Java执行Linux命令ssh的简单实现方法。你可以根据具体需求进行相应的修改和扩展。
2年前 -
Java可以通过使用SSH协议来执行Linux命令。下面是一些方法可以在Java中执行SSH命令:
1. 使用JSch库:JSch是一个用于Java的SSH库,可以用来连接远程服务器并执行命令。你可以使用Maven或者直接从官方网站下载JAR文件来使用它。
以下是一个简单的示例代码使用JSch来执行SSH命令:“`java
import com.jcraft.jsch.*;public class SSHCommandExecutor {
public static void main(String[] args) {
String host = “your_hostname”;
String username = “your_username”;
String password = “your_password”;
int port = 22;try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig(“StrictHostKeyChecking”, “no”);
session.connect();ChannelExec channelExec = (ChannelExec) session.openChannel(“exec”);
channelExec.setCommand(“your_command”);
channelExec.connect();InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}channelExec.disconnect();
session.disconnect();
} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
“`2. 使用Apache Commons Net库:Apache Commons Net是一个用于处理网络协议的库,包括SSH。你可以使用Maven或者从Apache官网下载JAR文件来使用它。
以下是使用Apache Commons Net执行SSH命令的示例代码:“`java
import org.apache.commons.net.util.*;
import org.apache.commons.net.*;public class SSHCommandExecutor {
public static void main(String[] args) {
String host = “your_hostname”;
String username = “your_username”;
String password = “your_password”;
int port = 22;try {
SSHClient client = new SSHClient();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(host, port);
client.authPassword(username, password);Session session = client.startSession();
Command cmd = session.exec(“your_command”);InputStream in = cmd.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}cmd.close();
session.close();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
“`3. 使用Apache SSHD库:Apache SSHD是一个用于Java的SSH服务器和客户端库。你可以使用Maven或者从Apache官网下载JAR文件来使用它。
以下是一个使用Apache SSHD执行SSH命令的简单示例代码:“`java
import org.apache.sshd.client.*;
import org.apache.sshd.common.config.keys.*;
import org.apache.sshd.common.keyprovider.*;
import org.apache.sshd.common.util.security.*;
import java.io.*;public class SSHCommandExecutor {
public static void main(String[] args) {
String host = “your_hostname”;
String username = “your_username”;
String password = “your_password”;
int port = 22;try {
SshClient client = SshClient.setUpDefaultClient();
client.start();ClientSession session = client.connect(username, host, port).verify().getSession();
session.addPasswordIdentity(password);
session.auth().verify();ClientChannel channel = session.createExecChannel(“your_command”);
ByteArrayOutputStream out = new ByteArrayOutputStream();
channel.setOut(out);
channel.open().verify();channel.waitFor(ClientChannel.CLOSED, 0);
System.out.println(out.toString());
channel.close();
session.close();
client.stop();
} catch (IOException e) {
e.printStackTrace();
}
}
}
“`4. 使用SSHJ库:SSHJ是一个用于Java的SSH库,提供了使用SSH协议进行远程连接和执行命令的功能。你可以使用Maven或者从GitHub上下载JAR文件来使用它。
以下是一个使用SSHJ执行SSH命令的示例代码:“`java
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.sftp.*;
import net.schmizz.sshj.transport.verification.*;
import net.schmizz.sshj.userauth.*;public class SSHCommandExecutor {
public static void main(String[] args) {
String host = “your_hostname”;
String username = “your_username”;
String password = “your_password”;
int port = 22;try {
SSHClient client = new SSHClient();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(host, port);
client.authPassword(username, password);Session session = client.startSession();
Command cmd = session.exec(“your_command”);System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
cmd.join();
session.close();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
“`5. 使用ProcessBuilder类:Java中的ProcessBuilder类可以执行外部命令,也可以用来执行SSH命令。但是需要注意的是,这种方法只能执行本地的SSH命令。
以下是一个使用ProcessBuilder执行本地SSH命令的示例代码:“`java
import java.io.*;public class SSHCommandExecutor {
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder(“ssh”, “your_username@your_hostname”, “your_command”);
pb.redirectErrorStream(true);
Process process = pb.start();
InputStream is = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}process.waitFor();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
“`以上是一些可以在Java中执行SSH命令的方法。你可以根据自己的实际需求选择适合的方法来执行你需要的Linux命令。
2年前 -
在Java中执行Linux命令并通过SSH连接到远程服务器可以通过Java的开源库JSch来实现。JSch是一个纯Java实现的SSH2协议库,它提供了连接、身份验证和远程执行命令等功能。下面是一个使用JSch库执行Linux命令的示例代码:
1. Maven依赖
首先,在你的Java项目中,需要添加JSch的Maven依赖。在你的pom.xml文件中添加以下代码:“`xml
com.jcraft
jsch
0.1.56
“`2. 连接远程服务器
使用JSch库连接到远程服务器需要指定服务器的主机名、用户名和密码。以下是一个连接到远程服务器的示例代码:“`java
import com.jcraft.jsch.*;public class SSHExample {
public static void main(String[] args) {
String host = “your_remote_host”;
String username = “your_username”;
String password = “your_password”;try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, 22);
session.setPassword(password);// 配置主机健康验证
session.setConfig(“StrictHostKeyChecking”, “no”);// 连接
session.connect();System.out.println(“成功连接到远程服务器!”);
// 在连接结束后进行相关操作
// …// 断开连接
session.disconnect();
System.out.println(“已断开与远程服务器的连接!”);
} catch (JSchException e) {
e.printStackTrace();
}
}
}
“`在上面的示例代码中,需要替换`your_remote_host`、`your_username`和`your_password`为实际的服务器主机名、用户名和密码。`session.setConfig(“StrictHostKeyChecking”, “no”)`的作用是跳过对连接主机的身份验证。
3. 执行Linux命令
在连接到远程服务器之后,可以使用JSch库执行Linux命令。以下是一个执行Linux命令的示例代码:“`java
import com.jcraft.jsch.*;public class SSHExample {
public static void main(String[] args) {
// …try {
// …// 打开一个执行命令的通道
Channel channel = session.openChannel(“exec”);// 设置要执行的命令
((ChannelExec) channel).setCommand(“your_linux_command”);// 获取命令执行的结果
InputStream commandOutput = channel.getInputStream();// 连接通道
channel.connect();// 读取命令执行的结果
int readByte = commandOutput.read();
while (readByte != -1) {
System.out.print((char) readByte);
readByte = commandOutput.read();
}// 关闭通道
channel.disconnect();
System.out.println(“命令执行完成!”);
} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
“`在上面的示例代码中,需要替换`your_linux_command`为实际要执行的Linux命令。命令执行的结果通过`channel.getInputStream()`来获取,并通过循环读取每一个字节来输出到控制台。
请注意,执行Linux命令需要有执行命令的权限。如果你连接的是远程服务器,你需要确保你的账户有足够的权限来执行所需的命令。
2年前