JTextPane output weird console characters - java

I was trying to run console command in Kali linux, but the output are just weird when i pipe it to the JTextPane. When I diplay it on the output console of Netbean it was fine.
Command that I'm trying to run: wifite -e Experiment -c 1
code:
public cracker(JTextPane aOutputPane)
{
super();
mOutputPane = aOutputPane;
}
#Override
protected String doInBackground() throws Exception
{
Process p = null;
try
{
String Channel=CNinput.getText();
String WName=WN.getText();
p = Runtime.getRuntime().exec("wifite -e "+WName+" -c "+Channel);
}
catch (IOException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
String output = "";
try
{
while ((line = buf.readLine()) != null)
{
publish(line);
output += line + "\n";
}
}
cat
ch (IOException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
p.waitFor();
}
catch (InterruptedException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
return output;
}
#Override
protected void process(java.util.List<String> aChunks)
{
mOutputPane.setText(null);
final String intermediateOutput = aChunks.stream().collect(Collectors.joining("\n"));
final String existingText = mOutputPane.getText();
final String newText = existingText + "\n" + intermediateOutput;
mOutputPane.setText(newText);
}
}

The characters are ANSI escape codes, intended to control the appearance of the terminal output generated by wifite. Among your options,
Elide the character sequences as they arrive in your implementation of doInBackground(); they all start with the ESC character.
Examine the codes and recapitulate the corresponding style in your JTextPane, as shown in the StyledDocument seen here.
Use a library such as the NetBeans console or Jansi, cited here.

Related

Running python script from java and sending input/output

I am writing a java program that will need to run a python script.
The script will print output which will java need to read to know the progress of the script.
To be able to pause the script while running I want it to ask for input once in a while, only when java give it input the script will keep going.
Here is my Java method:
private static void sevenTry(String[] strCommands) throws IOException {
Object oLock1 = new Object();
Object oLock2 = new Object();
ProcessBuilder pBuilder = new ProcessBuilder(strCommands);
pBuilder.redirectErrorStream(true);
Process proc = pBuilder.start();
Thread tReader = new Thread() {
#Override
public void run() {
System.out.println("~~tReader starting~~");
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
synchronized (oLock1) {
try {
String line = reader.readLine();
while (line != null && !line.trim().equals("--EOF--")) {
System.out.println("Stdout: " + line);
if (line.trim().equals("--INPUT--")) {
synchronized (oLock2) {
oLock2.notify();
}
oLock1.wait();
}
line = reader.readLine();
}
} catch (IOException e) {
System.out.println("tReader: " + e.getMessage());
} catch (InterruptedException e) {
System.out.println("tReader: " + e.getMessage());
} catch (Exception e) {
System.out.println("tReader: " + e.getMessage());
}
}
System.out.println("~~tReader end~~");
synchronized (oLock2) {
oLock2.notify();
}
}
};
Thread tWriter = new Thread() {
#Override
public void run() {
System.out.println("~~tWriter starting~~");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
String line, input;
Scanner scan = new Scanner(System.in);
synchronized (oLock2) {
try {
oLock2.wait();
} catch (InterruptedException e1) {
System.out.println("tWriter: " + e1.getMessage());
}
}
while (tReader.isAlive()) {
synchronized (oLock1) {
System.out.println("Java: insert input");
scan.hasNext();
input = scan.nextLine();
try {
writer.write(input + "\n");
writer.flush();
} catch (IOException e) {
System.out.println("tWriter: " + e.getMessage());
}
oLock1.notify();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
System.out.println("tWriter: " + e1.getMessage());
}
}
System.out.println("~~tWriter end~~");
}
};
tReader.start();
tWriter.start();
System.out.println("~~everything submitted~~");
try {
tReader.join();
tWriter.join();
System.out.println("~~finish~~");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This is my python script:
# coding=utf-8
import sys
print '1'
print '--INPUT--'
inum = sys.stdin.readline()
print '2'
print '--EOF--'
I tried running my code
sevenTry("python", "C:\\Testing.py");
but on java side it get stuck inside tReader at line:
String line = reader.readLine();
The program does work if i take out the input line from the python file
inum = sys.stdin.readline()
Using
inum = raw_input()
still bring up the same problem (im using python 2.7)
The most confusing part here that i even tried to test this with a java file (instead of python)
sevenTry("java", "-classpath", "C:\\class", "CheckCMD");
and it worked even with the input lines
import java.util.Scanner;
public class CheckCMD {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line;
System.out.println("1");
System.out.println("--INPUT--");
in.hasNext();
line = in.nextLine();
System.out.println("2");
System.out.println("--EOF--");
}
}
As you may have noticed, this is a problem related to Python.
As described in https://unix.stackexchange.com/questions/182537/write-python-stdout-to-file-immediately,
" when process STDOUT is redirected to something other than a terminal, then the output is buffered into some OS-specific-sized buffer (perhaps 4k or 8k in many cases)."
So, you need to call sys.stdout.flush() after each invoke to print.
Or, as a better option, you can change the default behaviour for the process, using the -u param, to get unbuffered output.

Linux terminal Output to JTextpane

I am currently looking for ways that I could actually print information to the jTextpane when I run the following code. When I press the button to run it, the program actually hang and no display for the output. Is there anyway to go round it or to fix it?
private void ScannetworkActionPerformed(java.awt.event.ActionEvent evt) {
Process p = null;
try {
p = Runtime.getRuntime().exec("ipconfig /all");
} catch (IOException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
try {
p.waitFor();
} catch (InterruptedException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader buf = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
String output = "";
try {
while ((line = buf.readLine()) != null) {
output += line + "\n";
} } catch (IOException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
nninfo.setText(output);
Screenshot:
You will need to execute the process in a separate thread, otherwise it will be executed in the UI-Thread and will block any refresh events as long as the process is running. In swing this is usually done by using a SwingWorker (just google for it and you'll probably find some nice tutorials).
Furthermore Process.waitFor() will wait for the process to finish and after that you'll read the contents of the process' output. That is you'll not get any updates as long as the process is running. To update your UI with information from the running process you have to read the data from the process' input stream prior to waiting for the process to finish. Maybe this question and the accepted answer will help you to figure out how to do this.
This is what your SwingWorker might look like. I haven't tested it, but it should give you some idea:
public class ScannetworkWorker
extends SwingWorker<String, String>
{
private final JTextPane mOutputPane;
public ScannetworkWorker(JTextPane aOutputPane)
{
super();
mOutputPane = aOutputPane;
}
#Override
protected String doInBackground() throws Exception
{
Process p = null;
try
{
p = Runtime.getRuntime().exec("ipconfig /all");
}
catch (IOException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
String output = "";
try
{
while ((line = buf.readLine()) != null)
{
publish(line);
output += line + "\n";
}
}
catch (IOException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
p.waitFor();
}
catch (InterruptedException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
return output;
}
#Override
protected void process(List<String> aChunks)
{
final String intermediateOutput = aChunks.stream().collect(Collectors.joining("\n"));
final String existingText = mOutputPane.getText();
final String newText = existingText + "\n" + intermediateOutput;
mOutputPane.setText(newText);
}
}

Execute the command julia.exe in Java

I'm trying to execute julia.exe in Java.
Here is the code:
Process pTest = Runtime.getRuntime().exec("C:/Program Files/Julia-0.4.1/bin/julia.exe");
When I run it, nothing happens.
However, if I try another executable file, it works well. For example:
Process pTest = Runtime.getRuntime().exec("C:/Program Files/anotherProgram/program.exe");
program.exe will run just as expected.
julia.exe is a little special.
If I run it on command prompt, it will execute on the command prompt. In other words, it won't pop up its own window.
I've done a test:
#julia script, it's path: C:/Users/Thomas/Julia/test.jl
function test1()
println("it's test1")
end
test1()
I execute this command on the command prompt:
C:\>C:/Program Files/Julia-0.4.1/bin/julia.exe C:/Users/Thomas/Julia/test.jl
then I will get it's test1 on the command prompt.
What I need is to execute C:/Program Files/Julia-0.4.1/bin/julia.exe C:/Users/Thomas/Julia/test.jl in my java project and get it's test1 on the console of eclipse.
Here is my java project:
public class Main {
public static void main(String[] args){
try {
String[] params = {"C:/Program Files/Julia-0.4.1/bin/julia.exe", "C:/Users/Thomas/Julia/test.jl"};
Process pTest = Runtime.getRuntime().exec(params);
try {
if (pTest.waitFor() != 0) {
System.err.println("exit value = " + pTest.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(pTest.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line+"-");
}
System.out.println(stringBuffer.toString());
} catch (InterruptedException e) {
System.err.println(e);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Consider this changed (and working) implementation removing the too-early invocation of waitFor and exitValue:
public class Main {
public static void main(String[] args) {
try {
String[] params = {"C:/Program Files/Julia-0.4.1/bin/julia.exe",
"C:/Users/Thomas/Julia/test.jl"};
Process pTest = Runtime.getRuntime().exec(params);
BufferedReader in = new BufferedReader(new InputStreamReader(pTest.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.println("===");
System.out.println("Julia exit value = " + pTest.exitValue());
} catch (IOException e) {
e.printStackTrace();
}
}
}
This produced the following output with your test-script:
it's test1
===
Julia exit value = 0
I got it finally.
As julia.exe execute on the command prompt immediately, we must give admin privileges to the users of cmd.exe.

Scanner doesn't read from file

I'm writing program, which will be read file, choose by user. I have code:
public class program extends javax.swing.JFrame {
private String textEncode;
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fch = new JFileChooser();
int choose = fch.showOpenDialog(this);
if(choose == JFileChooser.APPROVE_OPTION) {
String help = fch.getSelectedFile().getPath();
jTextField2.setText(help);
try {
Scanner in = new Scanner(new File(help));
while(in.hasNextLine()) {
textEncode = in.nextLine();
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Nie znaleziono pliku", "Błąd wczytywania", JOptionPane.ERROR_MESSAGE);
}
}
jTextArea1.setText(textEncode);
System.out.println(textEncode);
}
My file has 1 line of text. When program end read file, variable textEncode has value "null". Where is problem?
I try with in.next() and in.hasNext(), but it doesn't work too.
I found a solution:
public class program extends javax.swing.JFrame {
private String textEncode;
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fch = new JFileChooser();
int choose = fch.showOpenDialog(this);
if(choose == JFileChooser.APPROVE_OPTION) {
String help = fch.getSelectedFile().getPath();
jTextField2.setText(help);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(help), "UTF-8"));
String line;
String readed = "";
while((line = in.readLine()) != null) {
readed = readed + line + "\n";
}
jTextArea1.setText(readed);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Nie znaleziono pliku", "Błąd wczytywania", JOptionPane.ERROR_MESSAGE);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(aes.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(aes.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
But now I have problem with display jTextArea1. When file has loaded, the textArea is resize and looks like this: application window
TextArea is added into jScrollPane.
I had the same problem, and it took me a while to figure it out.
My problem was that my file contained french special characters like "é".
This caused the scanner to return "null" for scanner.nextLine() without causing any exception, no matter how long was the file, no matter where the special characters were placed.
To solve this, I just removed all the special characters. If anybody has a solution to make Scanner read the special characters, he's welcome to comment below.

busybox mv with whitespaces fails silently

I'm running a device with busybox.
Folder or files with no whitespaces moved correctly, but seems that folders with whitespaces don't move correctly
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv -v ");
command.append('\"');
command.append(source.getCanonicalPath());
command.append('\"');
command.append(' ');
command.append('\"');
command.append(target.getCanonicalPath());
command.append('\"');
System.out.println(command.toString());
Process process = Runtime.getRuntime().exec(command.toString());
StringBuilder output = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
output.append(line);
}
System.out.println(output.toString());
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
The output is
mv -v "/storage/sdcard0/media/music/Progressive Death Metal" "/storage/sdcard0/Music"
No mv output, method just returns "false" (non-zero exit code).
And must I use canonical path, or is it okay to use absolute path and leave it to shell?
EDIT
I also came up that if the filename had quotes, the argument will be wrong, so I made a method adding escape characters
private static String getCommandLineString(String input) {
return input.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\'", "\\\'")
.replace("`", "\\`")
.replace(" ", "\\ ");
}
And now mv looks like this
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv -v ");
command.append(getCommandLineString(source.getAbsolutePath()));
command.append(' ');
command.append(getCommandLineString(target.getAbsolutePath()));
System.out.println(command.toString());
Process process = Runtime.getRuntime().exec(command.toString());
StringBuilder output = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
output.append(line);
}
System.out.println(output.toString());
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
what I get is
mv -v /sdcard/media/music/Progressive\ Death\ Metal /sdcard/Music
But still I get silent non-zero exit code.
Finally got it working. Exec should ask for shell, while OutputStream should write commands.
private static boolean execute(boolean superuser, String command) {
DataOutputStream os = null;
try {
Process process = Runtime.getRuntime().exec(superuser ? "su" : "sh");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) { try { os.close(); } catch (Exception e) {} }
}
return false;
}
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv ");
command.append(getCommandLineString(source.getAbsolutePath()));
command.append(' ');
command.append(getCommandLineString(target.getAbsolutePath()));
return execute(false, command.toString());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

Categories

Resources