以下方法支持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本身就是阻塞的。