gpt4 book ai didi

java在cmd中写入netstat

转载 作者:搜寻专家 更新时间:2023-11-01 03:56:48 24 4
gpt4 key购买 nike

我的目标是打印我计算机上的所有互联网连接。当我在 cmd 上键入 netstat 时,我得到了互联网连接列表。我想在 java 中自动执行相同的操作。

我的代码:

Runtime runtime = Runtime.getRuntime();

process = runtime.exec(pathToCmd);

byte[] command1array = command1.getBytes();//writing netstat in an array of bytes
OutputStream out = process.getOutputStream();
out.write(command1array);
out.flush();
out.close();

readCmd(); //read and print cmd

但是使用这段代码我得到 C:\eclipse\workspace\Tracker>Mais?而不是连接列表。显然我正在使用 eclipse,在 Windows 7 中。我做错了什么?我看过类似的主题,但找不到问题所在。感谢您的回答。

编辑:

public static void readCmd() throws IOException {

is = process.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;

while ((line = br.readLine()) != null) {
System.out.println(line);
}
}

最佳答案

试试这个:我能够在我的默认临时目录中创建一个包含所有连接的文件

final String cmd = "netstat -ano";

try {

Process process = Runtime.getRuntime().exec(cmd);

InputStream in = process.getInputStream();

File tmp = File.createTempFile("allConnections","txt");

byte[] buf = new byte[256];

OutputStream outputConnectionsToFile = new FileOutputStream(tmp);

int numbytes = 0;

while ((numbytes = in.read(buf, 0, 256)) != -1) {

outputConnectionsToFile.write(buf, 0, numbytes);

}

System.out.println("File is present at "+tmp.getAbsolutePath());


} catch (Exception e) {
e.printStackTrace(System.err);
}

关于java在cmd中写入netstat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15735379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com