java 如何使用java程序运行命令提示符命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15852144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use java program to run command prompt commands?
提问by Woobie
this is my first time posting here, so I'm not really sure what to say/ask. Anyways, I am trying to make a simple java program that runs command prompt commands from the java program, mainly used for ping flood (ping flooding myself).
这是我第一次在这里发帖,所以我不确定该说什么/问什么。无论如何,我正在尝试制作一个简单的java程序,该程序从java程序中运行命令提示符命令,主要用于ping flood(ping flooding自己)。
Here is my current code
这是我当前的代码
public class Core extends JFrame {
JTextField ipTextField;
int packets = 0;
boolean running = false;
public Core() {
super("Fatique");
Container container = getContentPane();
JButton bAttack = new JButton("Start Attack");
JButton bStop = new JButton("Stop Attack");
JPanel jPanel = new JPanel();
container.setLayout(new FlowLayout());
ipTextField = new JTextField("IP Address", 30);
container.add(ipTextField);
bAttack.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = ipTextField.getText();
String[] value = input.split(":");
int amountOfPackets = Integer.parseInt(value[1]);
exec("cmd /c" + input + " -t -n " + amountOfPackets);
running = true;
}
});
bStop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stop();
}
});
if(!running) {
jPanel.add(bAttack);
} else {
jPanel.add(bStop);
}
add(jPanel);
}
public void exec(String cmd) {
try {
Process p = Runtime.getRuntime().exec(cmd);
System.out.println(getOutput(p) + " - " + getPacketsSent());
} catch (IOException e) {
e.printStackTrace();
}
}
public String getOutput(Process p) {
String output = null;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
output = line;
packets++;
}
return output;
} catch (IOException e) {
System.err.println(e.getStackTrace());
}
return null;
}
public int getPacketsSent() {
return packets;
}
public void stop() {
exec("cmd /c break");
running = false;
}
public static void main(String[] args) {
Core c = new Core();
c.setSize(500, 300);
c.setVisible(true);
c.setResizable(false);
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setLocationRelativeTo(null);
}
I'm quite new at java, so that might not do what I want it to do. What I want it to do is I enter an ip address in the textfield, and split it with ":", and after that the amount of packets, for instance
我对 Java 还很陌生,所以这可能不会做我想做的事情。我想要它做的是我在文本字段中输入一个 ip 地址,并用“:”分割它,然后是数据包的数量,例如
127.0.0.1:100
Though now when I try to use that ip and packet amount, it returns "null - 0" (from exec method), and I'm not even sure if it did anything related to ping.
虽然现在当我尝试使用该 ip 和数据包数量时,它返回“null - 0”(来自 exec 方法),我什至不确定它是否做了与 ping 相关的任何事情。
What I am trying to accomplish is as I already said, ping flood myself, and then output whatever I get as response, though I have no idea if this code does anything even related to that, I mostly use logic when coding java.
我想要完成的是,正如我已经说过的那样,ping 自己,然后输出我得到的任何响应作为响应,尽管我不知道这段代码是否做了与此相关的任何事情,但我在编写 java.lang.Object 时主要使用逻辑。
public String getOutput(Process p) {
String output = null;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
output = line;
packets++;
}
return output;
} catch (IOException e) {
System.err.println(e.getStackTrace());
}
return null;
}
Could someone explain me why my code code is not working how I want it to work? Please don't judge, as I already said, I'm quite new to java programming.
有人可以解释我为什么我的代码无法正常工作吗?请不要判断,正如我已经说过的,我对 Java 编程还很陌生。
EDIT: Here is a quick "informative" explanation of what I am trying to accomplish.
编辑:这是对我要完成的工作的快速“信息性”解释。
- I type in an ip address and how many packets I want to send. In this explanation, I am using localhost ip, and 5 packets.
I start the attack. At this part, I want the program to run cmd prompt command
ping 127.0.0.1 -t -n 5
127.0.0.1 being the ip that I put in the textfield in my program, and 5 is the amount of packets I put in the textfield.
I started the attack, so this is what should happen in the command prompt:
The language is Finnish, but still the same thing.
This is the basic explanation of what I am trying to accomplish, hopefully someone understood and can help/tell why my code is not working, or is working but not printing the proper lines in eclipse console.
- 我输入一个IP地址和我想发送多少数据包。在这个解释中,我使用 localhost ip 和 5 个数据包。
我开始进攻。在这部分,我希望程序运行 cmd prompt 命令
平 127.0.0.1 -t -n 5
127.0.0.1 是我在程序中放入文本字段的 ip,而 5 是我放入文本字段中的数据包数量。
我开始了攻击,所以这就是命令提示符中应该发生的事情:
语言是芬兰语,但还是一样的东西。
这是我试图完成的基本解释,希望有人理解并可以帮助/说明为什么我的代码不工作,或者工作但没有在 Eclipse 控制台中打印正确的行。
回答by Pablo Santa Cruz
Try something like this:
尝试这样的事情:
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("ping 192.168.16.67");
InputStream in = p.getInputStream();
OutputStream out = p.getOutputStream ();
InputStream err = p.getErrorStream();
p.destroy();
} catch(Exception exc) {}
Then, you'll have to read the out
variable to parse the ping
command output continuously.
然后,您必须读取out
变量以ping
连续解析命令输出。
回答by Stephen C
There is a problem with your getOutput method. It looks like you intend to collect every line of output. But in fact, since you are assigning line
to output
, you will only return the last line before the end of stream.
您的 getOutput 方法有问题。看起来您打算收集每一行输出。但实际上,由于您分配line
给output
,您只会返回流结束之前的最后一行。
To fix this, change
要解决此问题,请更改
output = line;
to
到
output += line + "\n";
Or to be more correct:
或者更准确地说:
output += line + LINE_SEPARATOR;
where you previously declared the latter as:
您之前将后者声明为:
final String LINE_SEPARATOR = System.getProperty("line.separator");
That doesn't directly explain why you are getting null
, but that might be because the command you are running is writing output to the 'error' stream rather than the 'output' stream.
这并不能直接解释您为什么会得到null
,但这可能是因为您正在运行的命令正在将输出写入“错误”流而不是“输出”流。
回答by Rushi M Thakker
bAttack.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = ipTextField.getText();
String[] value = input.split(":");
int amountOfPackets = Integer.parseInt(value[1]);
try {
p=Runtime.getRuntime().exec("ping -n "+amountOfPackets+" "+value[0]);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
running = true;
}
Just a small modification of your code. get output is as:
只是对您的代码稍作修改。获取输出为:
public String getOutput(Process p) {
String output = null;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
output =output+ line+"\n";
packets++;
}
return output;
} catch (IOException e) {
System.err.println(e.getStackTrace());
}
return null;
}
Here output is JTextArea I have taken to display the output of PING process. I cannot show you the output because I lack reputation.
这里的输出是我用来显示 PING 过程输出的 JTextArea。我无法向您展示输出,因为我缺乏声誉。
I don't know why first line is null. Anyway, it works.
我不知道为什么第一行是空的。无论如何,它有效。
Hope this help you. Have good time coding.
希望这对你有帮助。玩得开心编码。