以下方法支持Linux和windows兩個系統的命令行調用。還用到了apache的lang工具包commons-lang3-3.1.jar來判斷操作系統類型、也用到了和log4j-1.2.16.jar來列印日誌。至於rm -rf 是否能成功刪除文件,可以手動去調用命令行試試。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
private String callCmd(String cmd) throws InterruptedException, UnHandledOSException, ExecuteException {
if(SystemUtils.IS_OS_LINUX){
try {
// 使用Runtime來執行command,生成Process對象
Process process = Runtime.getRuntime().exec(
new String[] { "/bin/sh", "-c", cmd });
int exitCode = process.waitFor();
// 取得命令結果的輸出流
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 + "執行出錯!");
}
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 + "執行出錯!");
}
throw new UnHandledOSException("不支持本操作系統");
}
⑵ 怎麼在java中執行linux 命令 netstat -nat|grep -i "80"|wc -l
或許這就是你想要的 package question.save; import java.io.InputStreamReader; import java.io.LineNumberReader;/*** java在linux環境下執行linux命令,然後返回命令返回值。 * @author lee*/public class ExecLinuxCMD { public static Object exec(String cmd) {try {String[] cmdA = { /bin/sh, -c, cmd }; Process process = Runtime.getRuntime().exec(cmdA); LineNumberReader br = new LineNumberReader(new InputStreamReader( process.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { System.out.println(line); sb.append(line).append(\n);}return sb.toString(); } catch (Exception e) { e.printStackTrace();}return null;} public static void main(String[] args) { // TODO Auto-generated method stub String pwdString = exec(pwd).toString(); String netsString = exec(netstat -nat|grep -i \80\|wc -l).toString(); System.out.println(==========獲得值=============); System.out.println(pwdString); System.out.println(netsString);}}輸出結果:/home/lee/program/workspace/java/test20==========獲得值=============
⑶ linux用ssh讀取本地文件後寫入遠程文件
主要代碼:
pom.xml
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>0.10.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.11</artifactId>
<version>0.10.2.0</version>
</dependency>
<!--ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
主類:
/**
* Project Name:kafkademo
* File Name:TailLogToKafka.java
* Package Name:cmm.kafkademo
* Date:2018年12月7日下午2:40:46
* Copyright (c) 2018, [email protected] All Rights Reserved.
*
*/
package cmm.TailLogToKafka;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import cmm.util.PathUtil;
/**
* ClassName:TailLogToKafka <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2018年12月7日 下午2:40:46 <br/>
* @author mmchen
* @version
* @since JDK 1.7
* @see
*/
public class TailLogToKafka {
private static Connection conn;
private static int threadNum=0;
private static String cmd = "echo no commond";
private static String topic = "cmmtest";
public static void main(String[] args) {
Properties properties = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(new File(PathUtil.getProjectParentPath()+"/remote.properties")));
properties.load(in);
} catch (IOException e1) {
System.out.println("遠程連接配置讀取失敗!!!");
e1.printStackTrace();
}
//遠程連接linux伺服器
String ip = properties.getProperty("ip");
String usr = properties.getProperty("user");
String psword = properties.getProperty("password");
cmd = properties.getProperty("shell");
topic = properties.getProperty("topic");
//創建遠程連接,默認連接埠為22,如果不使用默認,可以使用方法
//new Connection(ip, port)創建對象
conn = new Connection(ip);
try {
//連接遠程伺服器
conn.connect();
//使用用戶名和密碼登錄
conn.authenticateWithPassword(usr, psword);
} catch (IOException e) {
System.err.printf("用戶%s密碼%s登錄伺服器%s失敗!", usr, psword, ip);
e.printStackTrace();
}
//創建線程,執行shell命令,獲取實時數據流,寫入kafka
threadNum=1;
new Thread(new Runnable() {
@Override
public void run() {
try {
Session session = conn.openSession();
session.execCommand(cmd);
InputStream out = new StreamGobbler(session.getStdout());
BufferedReader outBufferedReader = new BufferedReader(new InputStreamReader(out));
myProcer procerDemo = new myProcer();
while (true) {
String line = outBufferedReader.readLine();
if (line == null) {
threadNum=0;
outBufferedReader.close();
session.close();
conn.close();
break;
}
System.out.println(line);
//數據寫入kafka
procerDemo.proce(topic,line);
}
} catch (IOException e) {
System.out.println("open session fail");
e.printStackTrace();
}
}
}).start();
while (threadNum>0) {
Thread.yield();
}
}
}
⑷ java程序里調用linux命令
Java語言以其跨平台性和簡易性而著稱,在Java裡面的lang包里(java.lang.Runtime)提供了一個允許Java程序與該程序所運
行的環境交互的介面,這就是Runtime類,在Runtime類里提供了獲取當前運行環境的介面。
其中的exec函數返回一個執行shell命令的子進程。exec函數的具體實現形式有以下幾種:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws
IOException
public Process exec(String command,String[] envp,File dir) throws
IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws
IOException
public Process exec(String[] cmdarray, String[] envp,File dir)
throws IOException
我們在這里主要用到的是第一個和第四個函數,具體方法很簡單,就是在exec函數中傳遞一個代表命令的字元串。exec函數返回的是一個Process類
型的類的實例。Process類主要用來控制進程,獲取進程信息等作用。(具體信息及其用法請參看Java doc)。
1)執行簡單的命令的方法:
代碼如下:
⑸ 怎麼調用system函數,使用Android的linux命令
先來看一下system()函數的簡單介紹:
int system(const char *command);
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.
system()函數調用/bin/sh來執行參數指定的命令,/bin/sh 一般是一個軟連接,指向某個具體的shell,比如bash,-c選項是告訴shell從字元串command中讀取命令;
在該command執行期間,SIGCHLD是被阻塞的,好比在說:hi,內核,這會不要給我送SIGCHLD信號,等我忙完再說;
在該command執行期間,SIGINT和SIGQUIT是被忽略的,意思是進程收到這兩個信號後沒有任何動作。
再來看一下system()函數返回值:
The value returned is -1 on error (e.g. fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127).
If the value of command is NULL, system() returns nonzero if the shell is available, and zero if not.
為了更好的理解system()函數返回值,需要了解其執行過程,實際上system()函數執行了三步操作:
1.fork一個子進程;
2.在子進程中調用exec函數去執行command;
3.在父進程中調用wait去等待子進程結束。
對於fork失敗,system()函數返回-1。
如果exec執行成功,也即command順利執行完畢,則返回command通過exit或return返回的值。
(注意,command順利執行不代表執行成功,比如command:」rm debuglog.txt」,不管文件存不存在該command都順利執行了)
如果exec執行失敗,也即command沒有順利執行,比如被信號中斷,或者command命令根本不存在,system()函數返回127.
如果command為NULL,則system()函數返回非0值,一般為1.
popen和system都可以執行外部命令。
popen相當於是先創建一個管道,fork,關閉管道的一端,執行exec,返回一個標準的io文件指針。
system相當於是先後調用了fork, exec,waitpid來執行外部命令
popen本身是不阻塞的,要通過標准io的讀取使它阻塞
system本身就是阻塞的。