Java可以通过Runtime调用Linux命令,形式如下:
Runtime.getRuntime().exec(command)
但是这样执行时没有任何输出,因为调用Runtime.exec方法将产生一个本地的进程,并返回一个Process子类的实例(注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例)该实例可用于控制进程或取得进程的相关信息。
由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过Process.getOutputStream(),Process.getInputStream(),Process.getErrorStream()方法重定向给它的父进程了。
用户需要用这些stream来向子进程输入数据或获取子进程的输出,下面的代码可以取到linux命令的执行结果:
try{
String[]cmd=newString[]{”/bin/sh”,“-c”,”ls“}
Processps=Runtime.getRuntime().exec(cmd)
BufferedReaderbr=newBufferedReader(newInputStreamReader(ps.getInputStream()))
StringBuffersb=newStringBuffer()
Stringline
while((line=br.readLine())!=null){
sb.append(line).append(”\n”)
}
Stringresult=sb.toString()
System.out.println(result)
}catch(Exceptione){
e.printStackTrace()
}
执行linux命令基,基本思路是从控制台获得输入的指令,启动命令行执行命令,捕捉异常,示例如下:
public class TestRunTime {
public static void main(String[] args) throws IOException, InterruptedException {
String cmd = ""
if(args == null || args.length == 0){
System.out.println("请输入命令行参数")
}else{
for(int i=0i<args.length i++){//获得输入的命令
cmd += args[i] + " "
}
}
try {
Process process = Runtime.getRuntime().exec(cmd)//执行命令
InputStreamReader ir = new InputStreamReader(process.getInputStream())
LineNumberReader input = new LineNumberReader(ir)
String line
while ((line = input.readLine()) != null) {//输出结果
System.out.println(line)
}
} catch (java.io.IOException e) {
System.err.println("IOException " + e.getMessage())//捕捉异常
}
}
}
首先确保Linux开启sshd服务,并支持远程SSH连接。java程序使用jsch框架登录Linux,执行命令。protected void creation() throws Exception {
JSch jsch = new JSch()
session = jsch.getSession(userName, host, port)
session.setPassword(password)
Properties config = new Properties()
config.put("StrictHostKeyChecking", "no")
session.setConfig(config)
session.setTimeout(CONNECT_TIMEOUT)
session.setConfig("PreferredAuthentications", "password,keyboard-interactive")
session.setServerAliveInterval(1000 * 60 * 2)
session.connect()
}
public String sendCommand(String command) throws Exception {
if(!isConnected())
throw new JSchException("Session is not connected, command exec faild.")
final ChannelExec exec = (ChannelExec)session.openChannel("exec")
ByteArrayOutputStream out = new ByteArrayOutputStream()
exec.setCommand(command)
exec.setOutputStream(out)
exec.setExtOutputStream(out)
exec.connect()
final Thread thread = new Thread() {
public void run() {
while(!exec.isEOF()) {
try { Thread.sleep(500L)} catch(Exception e) {}
}
}
}
thread.setDaemon(true)
thread.start()
thread.join(EXEC_TIMEOUT)
thread.interrupt()
if(thread.isAlive()) {
throw new JSchException("Exec Time Out Error")
} else {
try {
exec.disconnect()
out.close()
} catch (Exception e) {
}
byte[] lens = out.toByteArray()
String result = new String(lens, charset)
if(result.startsWith("bash") &&result.indexOf("command not found") != -1)
return ""
return result
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)