java连接linux并执行命令
时间: 2023-05-11 18:05:06 浏览: 57
可以使用Java中的SSH库来连接Linux并执行命令,例如JSch库。以下是一个简单的示例代码:
```
import com.jcraft.jsch.*;
public class SSHExample {
public static void main(String[] args) {
String host = "your_host";
String user = "your_username";
String password = "your_password";
String command = "ls -l";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (in.available() > 0) continue;
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
```
这段代码连接到指定的Linux主机,执行`ls -l`命令,并将结果输出到控制台。你需要将`your_host`、`your_username`和`your_password`替换为实际的主机名、用户名和密码。