以下方法支持Linux和windows兩個系統(tǒng)的命令行調(diào)用。還用到了apache的lang工具包commons-lang3-3.1.jar來判斷操作系統(tǒng)類型、也用到了和log4j-1.2.16.jar來打印日志。至于rm -rf 是否能成功刪除文件,可以手動去調(diào)用命令行試試。
創(chuàng)新互聯(lián)公司是一家專注于網(wǎng)站設(shè)計、做網(wǎng)站與策劃設(shè)計,桂林網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10多年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:桂林等地區(qū)。桂林做網(wǎng)站價格咨詢:028-86922220
private?String?callCmd(String?cmd)?throws?InterruptedException,?UnHandledOSException,?ExecuteException?{
if(SystemUtils.IS_OS_LINUX){
try?{
//?使用Runtime來執(zhí)行command,生成Process對象
Process?process?=?Runtime.getRuntime().exec(
new?String[]?{?"/bin/sh",?"-c",?cmd?});
int?exitCode?=?process.waitFor();
//?取得命令結(jié)果的輸出流
InputStream?is?=?process.getInputStream();
//?用一個讀輸出流類去讀
InputStreamReader?isr?=?new?InputStreamReader(is);
//?用緩沖器讀行
BufferedReader?br?=?new?BufferedReader(isr);
String?line?=?null;
StringBuilder?sb?=?new?StringBuilder();
while?((line?=?br.readLine())?!=?null)?{
System.out.println(line);
sb.append(line);
}
is.close();
isr.close();
br.close();
return?sb.toString();
}?catch?(java.lang.NullPointerException?e)?{
System.err.println("NullPointerException?"?+?e.getMessage());
logger.error(cmd);
}?catch?(java.io.IOException?e)?{
System.err.println("IOException?"?+?e.getMessage());
}
throw?new?ExecuteException(cmd?+?"執(zhí)行出錯!");
}
if(SystemUtils.IS_OS_WINDOWS){
Process?process;
try?{
//process?=?new?ProcessBuilder(cmd).start();
String[]?param_array?=?cmd.split("[\\s]+");
ProcessBuilder?pb?=?new?ProcessBuilder(param_array);
process?=?pb.start();
/*process=Runtime.getRuntime().exec(cmd);*/
int?exitCode?=?process.waitFor();
InputStream?is?=?process.getInputStream();
InputStreamReader?isr?=?new?InputStreamReader(is);
BufferedReader?br?=?new?BufferedReader(isr);
String?line;
StringBuilder?sb?=?new?StringBuilder();
while?((line?=?br.readLine())?!=?null)?{
System.out.println(line);
sb.append(line);
}
is.close();
isr.close();
br.close();
return?sb.toString();
}?catch?(IOException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
throw?new?ExecuteException(cmd?+?"執(zhí)行出錯!");
}
throw?new?UnHandledOSException("不支持本操作系統(tǒng)");
}
system(執(zhí)行shell 命令)
相關(guān)函數(shù) fork,execve,waitpid,popen
表頭文件 #includestdlib.h
定義函數(shù) int system(const char * string);
函數(shù)說明 system()會調(diào)用fork()產(chǎn)生子進程,由子進程來調(diào)用/bin/sh-c string來執(zhí)行參數(shù)string字符串所代表的命令,此命令執(zhí)行完后隨即返回原調(diào)用的進程。在調(diào)用system()期間SIGCHLD 信號會被暫時擱置,SIGINT和SIGQUIT 信號則會被忽略。
返回值 如果system()在調(diào)用/bin/sh時失敗則返回127,其他失敗原因返回-1。若參數(shù)string為空指針(NULL),則返回非零值。如果system()調(diào)用成功則最后會返回執(zhí)行shell命令后的返回值,但是此返回值也有可能為system()調(diào)用/bin/sh失敗所返回的127,因此最好能再檢查errno 來確認執(zhí)行成功。
附加說明 在編寫具有SUID/SGID權(quán)限的程序時請勿使用system(),system()會繼承環(huán)境變量,通過環(huán)境變量可能會造成系統(tǒng)安全的問題。
范例 #includestdlib.h
main()
{
system(“l(fā)s -al /etc/passwd /etc/shadow”);
}
執(zhí)行 -rw-r--r-- 1 root root 705 Sep 3 13 :52 /etc/passwd
-r--------- 1 root root 572 Sep 2 15 :34 /etc/shadow
首先確保Linux開啟sshd服務(wù),并支持遠程SSH連接。java程序使用jsch框架登錄Linux,執(zhí)行命令。
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;
}
}