I Asked some days ago about executing python script from java. It solved my problem partially. But now, I am not able to pass any parameter and make that script to do anything.
My script has to receive a XBee frame and send it by serial port. I tested the script in shell and it works fine. So, doing: sudo python script.py frame, the frame is sent.
Now, I tried to do the same with java, and it fails. My code is:
Process p;
//System.out.println(packet.toString());
try{
StringBuffer p1 = new StringBuffer();
String[] cmd = {"/bin/bash", "-c", "echo pass | python script.py b'", packet.toString(), "'"};
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
p.waitFor();
p.destroy();
} catch (Exception e) {}
I have to add b' before argument and another ' after it. packet is StringBuffer so I get the String with toString method.
I need to run it as root because it uses serial port and if not, it says to me I have not permission.
Do you know how to do it? I tried to write a file with some word when I run the script but nothing happends, which makes me think about it doesn't run properly.
Related
I'm trying to use Runtime.getRuntime().exec() to call a program as if it was called from the terminal, but it just crashes with a fatal error after reading the first file.
In the terminal I run the command like so:
mace4 -c -f inputFile.in > outputFile.out
It works as expected, reading from the first file and outputting in the second one.
In Java I try to run it this way:
String args[] = new String[]{"mace4", "-c", "-f", inputFileName ,">",outputFileName};
try {
String s;
Process proc = Runtime.getRuntime().exec(args, null, new File("/home/user/workDirectory/"));
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
proc.waitFor();
proc.destroy();
As soon as the program reaches the end of the first file, it throws this:
Fatal error: read_all_input, file > not found
The program is quite old and I can't seem to find a way to get a more detailed error out of it..
I tried calling it with these arguments {"sh or bash", "-c", "mace4", "-c", "-f", inputFileName ,">",outputFileName} which makes the program run and then freeze (or at least nothing appears in the console)..
Am I calling the terminal command wrong and if yes what should I change?
PS: this is my first question here, if I missed anything, I'm sorry..
It looks like you're trying to use the Bash output redirection operator >. This redirects the output of the program you're running to a file (or another program)
This answer explains how to do this using ProcessBuilder which should work for what you're trying to do here.
For example:
ProcessBuilder pb = new ProcessBuilder("mace4", "-c", "-f", inputFileName);
pb.redirectOutput(new File(outputFileName));
Process p = pb.start();
I'm trying to execute a command in my terminal. The problem is, when I execute the command in terminal, it succeed, but when I run the command from java, the command is executed but, I got an error message showing me that some python module is missing.
try{
String[] list = { "python3", "script.py" };
ProcessBuilder pb = new ProcessBuilder(list);
pb.directory(
new File("/home/script"));
System.out.println("" + pb.directory());
Process process = pb.start();
InputStream str = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(str);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);}
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);
process.waitFor();
process.destroy();
}catch (Exception ex) {
ex.printStackTrace();
}
The error message:
/home/script
Output of running [] is:Traceback (most recent call last):
File "scraper.py", line 8, in <module>
from selenium import webdriver
ModuleNotFoundError: No module named 'selenium'
value is : null
PS: When I execute the command directly from terminal, everything works good, I don't get the missing module error.
Similar to Java, python allows to import other stuff. That message tells you that your python script wants to use the module selenium, but can't find it.
Most likely you have some special ENV var setup when running commands manually in a shell/console. So check your .bashrc or .initrc or whatever defines your ENV variables. On a unix system, typing the command env might show you all settings, too. Simply check if the env var PYTHONPATH is setup.
As that call works from the command line, then for sure, the module is installed on your system. Your only problem is that python can't find it when you invoke that script through the Java ProcessBuilder!
One solution might be that you "manually" adjust the PYTHONPATH from within your script. Thus: figure the correct setup for PYTHONPATH, then update your script to "do the right thing".
For further details, see the python documentation!
Question:
I have to call an exe file passing 2 string arguments. The call has to get executed as a different user
I referred few of the links that I got from hints. Couple of them were using powershell, few were using runas examples and so on.
But with powershell also, I am not sure if I will face the issue of "cannot be loaded because running scripts is disabled on this system".
Just because of this reason, I want to try something authentic.
Tried following approaches
Trying to do it through a call with RunAs command is making my life difficult. (called a batch file with RunAs command passing a separate pass.txt or savecred). savecred was ruled out by most people. Other one did not work as expected.
Powershell, has issues wherein, I always get a userid/password popup, even though I run through a Java file.
I also get an error in the command prompt as here below
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodExcept
ion
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.Power
Shell.Commands.NewObjectCommand
(Sample code attached below)
public class SamplePS {
public static void main(String[] args) throws IOException {
Runtime runtime = Runtime.getRuntime();
String command = "powershell C:\\Users\\Ramu\\Project\\SampleFile.ps1";
//String cmds[] = {"C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", "\\c", "SampleFile.ps"};
System.out.println("1");
Process proc = runtime.exec(command);
InputStream is = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
System.out.println("2");
}
}
My ps1 file is as here below
$credential = New-Object System.Management.Automation.PSCredential <<domain>>\<<user id>>, <<password>>
start-process cmd.exe -arg "/k dir" -Credential $credential
What is the best way to handle this scenario?
Please suggest! I am not sure what approach to take.
Powershell or Perl or any other scripting.
Whatever it be, I have to make a call from Java file.
Please suggest!
Note: For time being, I dont mind the password being sent as a plain text.
The exe file is in Windows machine
Thanks!
Ram
first of all, I found a lot of questions about xterm and java, but no questions handles my problem directly.
What is my problem?
I want to start a xterm terminal from java and I want to send commands to this terminal.
First I just want to change the directory, but it does not work. But it is important, that I don't know all commands at the beginning of the program, so it is recommended, that I can send commands to the terminal at run-time.
Here is my code:
String[] command= {"xterm"};
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
Thread.sleep(2000);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
ReadThread input = new ReadThread(in);
input.start();
BufferedReader error = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
ReadThread inputError = new ReadThread(error);
inputError.start();
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(pr.getOutputStream())),true);
printWriter.println("cd /home/***/sipp/sipp-3.3\n");
Thread.sleep(2000);
input.die();
inputError.die();
printWriter.close();
error.close();
in.close();
pr.destroy();
I thought that the terminal will open (it does) and change the directory to sipp-3.3 after 2 seconds. Another 2 seconds later the xterm should close (it does).
But what is the problem, that my command does not work?
And please I don't want to find a solution like
String [] gggg = {"xterm", "-c", "multiple commands, with |, &&, ; etc"};
rt.exec(gggg);
Because with a solution like this, I am not able to send further commands to the terminal.
Many thanks in advance!
I'm trying a new approach to a hitch I've been stuck on. Instead of using expect4j for my SSH connection, (I couldn't figure out a way past blocking consumer runs and issues with closures, see past posts for more info on that if you're knowledgeable and feeling saintly,) I'm going to try to use an expect script. I have a runtime exec coded in to a button.onclick, see below. Why am I getting a 127 exit value? I basically just need this expect script to ssh in, run a single set of expect and send, give me the readout, and that's it...
I'm using cygwin. Not sure if that's relevant to why this isn't working...is my sh-bang line pointing to the right place? My cygwin install is a full install, all packages, in C:\cygwin.
Why am I getting a 127 exit value instead of a readout from my server, and how do I alleviate this?
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec( new String [] {"C:\\cygwin\\bin\\bash.exe", "C:\\scripts\\login.exp"});
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
#!/usr/bin/expect -f
spawn ssh userid#xxx.xxx.xxx.xxx password
match_max 100000
expect "/r/nDestination: "
send -- "xxxxxx\r"
expect eof
The problem is that you use bash to execute an expect script. You need to use expect to execute an expect script, or bash to execute an expect script by means of a shell commandline (that would be Process proc = rt.exec( new String [] {"C:\\cygwin\\bin\\bash.exe", "-c", "C:\\scripts\\login.exp"});, note the "-c" which I have inserted) which makes use of the magic shebang at the top of your script. Or better, use only the shebang: Process proc = rt.exec( new String [] {"C:\\scripts\\login.exp"});
The exit value of 127 is a special exit value, and tells you "command not found". Which makes sense as you expect script contains many words for which no system binaries or shell builtins exist.