First of all , i've already seen couple of documents, stackoverflow questions regarding the same ..I've my project specific question
When trying to run command :
curl -u username:password https://example.com/xyz/abc
from the mac terminal , I get my desired json format data.
But running the same command from java code , I get Unauthorised 401 error in console.
My code is :
String username="myusername";
String password="mypassword";
String url="https://www.example.com/xyz/abc";
String[] command = {"curl", "-u" ,"Accept:application/json", username, ":" , password , url};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
try
{
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.print(result);
}
catch (IOException e)
{ System.out.print("error");
e.printStackTrace();
}
I get Unauthorised 401 error and bunch of html tags .
It seems like a repetitive question, but I've tried all the approaches.
I know alternative is using http response method, but particularly I want to use curl commands.
Thanks in advance.
Try changing this line
String[] command = {"curl", "-u" ,"Accept:application/json", username, ":" , password , url};
into
String[] command = {"curl", "-H", "Accept:application/json", "-u", username+":"+password , url};
hey try this I had the same problem.
It worked in my terminal had the same error as yours.
String[] command = {"curl", "-u" , username+ ":" + password , url};
Related
I am trying to execute the following curl command from Java, but the answer I get is incorrect, since it always returns the status 401.
curl -k -v -u "admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI" -d "{"username":"test","token_code":"246212"}" -H "Content-Type: application/json" https://192.168.101.59/api/v1/auth/
I am sending correctly the user "admin2" with his password for the authentication. I think the problem is the use of character (") in my code.
String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
"-d", "{\"username\":\"test\",\"token_code\":\"246212\"}","-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
String curlResult = "";
String line = "";
try {
Process process = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (true) {
line = r.readLine();
if (line == null) {
break;
}
curlResult = curlResult + line;
}
} catch (Exception e) {
e.printStackTrace();
}
In 'command', try removing the single quotes from
"'admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI'"
so that it becomes
"admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI"
and see if that helps. It might be considering them as part of the actual username and password.
I think the issue is the Json in this case and I think you are right then that the double quotes are the issue. Try putting the Json in a file and use curl to send the file contents as the body of your message.
String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
"-d", "#/path/to/filename.json", "-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};
Here is the snapshot what I want exately!
I am trying to develop a program in java which can get all opened application in the taskbar. I have tried many links but none of those are helpful to me. The same question was also asked by Ganesh Rangarajan in July 2013 but none has answered him. Here is his question.
Here is the solution to get titles of ALL (visible, non-visible) windows:
https://stackoverflow.com/a/11067492/6401177
If you want to get titles of opened top-level windows only (i.e. Applications taskbar), you have to check the visibility of each window (and/or check other conditions as listed here: http://vb.mvps.org/articles/ap200003.asp). Although, checking window's visibility seems sufficient.
I just altered method "callback" in previous code like this:
String wText = Native.toString(windowText, System.getProperty("file.encoding")).trim();
com.sun.jna.platform.win32.WinDef.HWND hwnd_1 = new WinDef.HWND(hWnd);
boolean b = com.sun.jna.platform.win32.User32.INSTANCE.IsWindowVisible(hwnd_1);
if (!wText.isEmpty() && b) {
windowNames.add(wText);
}
I also added "file.encoding" so titles are shown correctly in non-english Windows environment too.
I tested code in Windows XP/7/8 and it works nice.
The only problem seems to be that some default internal(?) window called "Program Manager" is always included in the list.
You need both JARs (JNA libraries) from: https://github.com/java-native-access/jna
This reply is too late for you, but may help someone else who is now facing a similar issue.
I just wrote a similar applications to do it but to opened CMD only
and you can replace the listCommand by
powershell -command "get-Process | format-table mainwindowtitle"
(takig care with \ to use it in java) to get all opened applications .
public String[] getEnginesFromTaskManger()
{
// listCommand is a command to get all opened CMD program like (batches,.......)
// you can test it in your CMD as powershell -command "get-Process cmd | format-table mainwindowtitle"
String listCommand = "powershell -command \"get-Process cmd | format-table mainwindowtitle\"";
try
{
String line;
// since line length for powershell output is 79
int outLen = 79;
Process p = Runtime.getRuntime().exec(listCommand);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
line = input.readLine();
System.out.println("line: " + line + "\t" + line.length());
EnginesListFromTaskManeger = new ArrayList<String>();
int i = 0;
/*
I used this outLen > 0 condition to make sure that this method will close automatically
in case of no running CMD applications and you running this from your IDE's (Eclipse, Netbeans , ......)
the powershell will not stopped so i used it. */
while(line != null && outLen > 0)
{
System.out.println("line: " + line + "\t" + line.length());
line = input.readLine().trim().toLowerCase();
outLen = line.length();
EnginesListFromTaskManeger.add(i, line);
System.out.println(EnginesListFromTaskManeger.get(i));
// EnginesListFromTaskManeger[i]=(String)input.readLine().trim();
// System.out.println("EnginesListFromTaskManeger"+ EnginesListFromTaskManeger[i]);
i++;
}
input.close();
}catch(Exception err)
{
err.printStackTrace();
}
ListFromTaskManeger = new String[EnginesListFromTaskManeger.size()];
ListFromTaskManeger = EnginesListFromTaskManeger.toArray(ListFromTaskManeger);
return ListFromTaskManeger;
}
The process list from the command "ps -e":
try {
String line;
Process p = Runtime.getRuntime().exec("ps -e");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
In windows see following used following code
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
Hope the info help!
"tasklist.exe /nh /v" worked perfectly to get the running applications.
try {
Process p = Runtime.getRuntime().exec("tasklist.exe /nh /v");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((String line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.
This is my code:
Process p;
try{
System.out.println("SEND");
String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
//System.out.println(cmd);
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
System.out.println(s);
System.out.println("Sent");
p.waitFor();
p.destroy();
} catch (Exception e) {}
Nothing happened. It reached SEND but it just stopped after it...
I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).
You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.
You could do either
Put your command to a shell script and execute that shell script with .exec() or
You can do something similar to the following
String[] cmd = {
"/bin/bash",
"-c",
"echo password | python script.py '" + packet.toString() + "'"
};
Runtime.getRuntime().exec(cmd);
#Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named) Process.getOutputStream().
Process p = Runtime.exec(
new String[]{"python", "script.py", packet.toString()});
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(p.getOutputStream()));
writer.write("password");
writer.newLine();
writer.close();
You would do worse than to try embedding jython and executing your script. A simple example should help:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
// Using the eval() method on the engine causes a direct
// interpretataion and execution of the code string passed into it
engine.eval("import sys");
engine.eval("print sys");
If you need further help, leave a comment. This does not create an additional process.
First, open terminal and type "which python3". You will get the complete path of python3. For example "/usr/local/bin/python3"
String[] cmd = {"/usr/local/bin/python3", "arg1", "arg2"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
String line = "", output = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine())!= null) {sb = sb.append(line).append("\n"); }
output = sb.toString();
System.out.println(output);
I am trying to get the output of curl command in java.
I am able to execute the same curl command manually through terminal and obtain the output but when I try to execute through java code as below, the output obtained is null.
I could use Apache HttpClient for the same, but I want to try and use this curl cli.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class MyCurlClient {
public static void main(String[] args) {
MyCurlClient obj = new MyCurlClient();
// in mac oxs
// String command = "ping -c 5 " + domainName;
String command = "curl "
+ "'http://localhost:8080/auth/login' -H 'Origin: http://localhost:9000' --data-binary '{\"username\":\"policy-engine\",\"password\":\"openstack\"}' --compressed";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
System.out.println(reader.readLine()); // value is NULL
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
process.waitFor() waits until the process is terminated.
Therefore, you won't see any output from it. You need to capture the output before the process terminates.
Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
You can fix your code by removing the process.waitFor() line.
You may want to try using an absolute path to the curl command, e.g.
command = "/usr/bin/curl " + ...
It's possible Java is not able to find the curl binary and that is why it doesn't work.
If this doesn't fix your problem, verify that the curl command is working at all by doing:
String[] command = new String[]{"curl", "http://localhost:8080/auth/login",
"-H", "Origin: http://localhost:9000", "--data-binary",
"{\"username\":\"policy-engine\",\"password\":\"openstack\"}", "--compressed"};
private String executeCommand(String... command) {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectOutput(new File("curloutput.txt"));
p.start();
}
And see if the curl command actually outputs anything to the file. If it does, then this is an InputStream timing issue. If it does not, then something is wrong with the curl command itself.
Using the String[] along with removing the single quotes from the curl command solved the issue.
Uf only String[] is used(with single quotes) then you get the expected response but along with it, you also see "unauthorized" as output.
Result is -->
{"username":"policy-engine","token":"dc7e017f-d5a3-4b72-a1c2-066880e775c7"}unauthorized
but when both String[] is used (without single quotes) the response is clean and as expected.
Result is -->
{"username":"policy-engine","token":"dc7e017f-d5a3-4b72-a1c2-066880e775c7"}
Please remove the quotes in th curl command , For Eg -
String command = "curl http://localhost:8080/auth/login -H Origin: shttp://localhost:9000 --data-binary {\"username\":\"policy-engine\",\"password\":\"openstack\"} --compressed";
I can execute Linux commands like ls or pwd from Java without problems but couldn't get a Python script executed.
This is my code:
Process p;
try{
System.out.println("SEND");
String cmd = "/bash/bin -c echo password| python script.py '" + packet.toString() + "'";
//System.out.println(cmd);
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
System.out.println(s);
System.out.println("Sent");
p.waitFor();
p.destroy();
} catch (Exception e) {}
Nothing happened. It reached SEND but it just stopped after it...
I am trying to execute a script which needs root permissions because it uses serial port. Also, I have to pass a string with some parameters (packet).
You cannot use the PIPE inside the Runtime.getRuntime().exec() as you do in your example. PIPE is part of the shell.
You could do either
Put your command to a shell script and execute that shell script with .exec() or
You can do something similar to the following
String[] cmd = {
"/bin/bash",
"-c",
"echo password | python script.py '" + packet.toString() + "'"
};
Runtime.getRuntime().exec(cmd);
#Alper's answer should work. Better yet, though, don't use a shell script and redirection at all. You can write the password directly to the process' stdin using the (confusingly named) Process.getOutputStream().
Process p = Runtime.exec(
new String[]{"python", "script.py", packet.toString()});
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(p.getOutputStream()));
writer.write("password");
writer.newLine();
writer.close();
You would do worse than to try embedding jython and executing your script. A simple example should help:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
// Using the eval() method on the engine causes a direct
// interpretataion and execution of the code string passed into it
engine.eval("import sys");
engine.eval("print sys");
If you need further help, leave a comment. This does not create an additional process.
First, open terminal and type "which python3". You will get the complete path of python3. For example "/usr/local/bin/python3"
String[] cmd = {"/usr/local/bin/python3", "arg1", "arg2"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
String line = "", output = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine())!= null) {sb = sb.append(line).append("\n"); }
output = sb.toString();
System.out.println(output);