首先,需要明确java调用的是本地shell命令还是远程shell命令?
如果是本地的话,使用ProcessBuilder:
[Java] 纯文本查看 复制代码 ProcessBuilder pb = new ProcessBuilder();
pb.command("sh", "-c", "ls");
pb.directory(new File(SHELL_FILE_DIR));
try {
Process p = pb.start();
// shell脚本返回的结果
int runningStatus = p.waitFor();
} catch (Exception e) {
// exception
}
如果是远程的话,使用额外的jar包
[Java] 纯文本查看 复制代码 import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
Connection connection = new Connection(ip);
connection.connect();//连接
boolean isAuthenticated = connection.authenticateWithPassword(username, password);
if(isAuthenticated) {
Session session = connection.openSession();
session.execCommand("ifconfig");
session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, 1000 * 3600);
int runningStatus = session.getExitStatus()
} |