I work with Bash script. My bash script is
#!/bin/bash
function aa(){
echo "Run";
su - postgres -c "shp2pgsql -I -s 4269 /tmp/gismanager/Wards.shp ff | psql postgis;";
echo "Run";
return 0;
}
aa;
when this script run by linux result is Run Run but from java result is Run
my java code is
public static void execShellCmd(String path) {
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(path);
BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
System.out.println("exec response: " + line);
}
} catch (Exception e) {
System.out.println(e);
}
}
Can anybody help me?
Have you tried to capture the OutputStream and ErrorStream?
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
InputStream inputStream = process.getInputStream();
InputStream errorStream = process.getErrorStream();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
Related
I am trying to call python within my java code. However I found that if I import numpy in my python code, this is my java code
Process pcs = Runtime.getRuntime().exec(cmd);
String result = null;
BufferedInputStream in = new BufferedInputStream(pcs.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
System.out.println("\nExecuting python script file now.");
String lineStr = null;
while ((lineStr = br.readLine()) != null) {
result = lineStr;
}
br.close();
in.close();
System.out.println("done!");
System.out.println(result);
This is my python code:
import sys
import os
import numpy as np
a = sys.argv[1]
b = sys.argv[2]
print("hello world!")
print("%s * %s = %s"%(a,b,int(a)*int(b)))
Results if I don't include "import numpy as np":
10 * 11 = 110
Results if include "import numpy as np":
null
Any intuitive explanation?
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Hello{
public static void main(String[] args)throws java.io.IOException{
Process pcs=Runtime.getRuntime().exec("python test.py 8 5");// in linux or unix use python3 or python
String result=null;
BufferedInputStream in = new BufferedInputStream(pcs.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
System.out.println("\nExecuting python script file now.");
String lineStr = null;
while ((lineStr = br.readLine()) != null) {
result = lineStr;
}
br.close();
in.close();
System.out.println("done!");
System.out.println(result);
}
}
java code
compile:
javac Hello.java
run:
java Hello
#test.py
import sys
import os
import numpy as np
a = sys.argv[1]
b = sys.argv[2]
print("hello world!")
print("%s * %s = %s"%(a,b,int(a)*int(b)))
Have you got the right PYTHONPATH setup in your application? When you have import numpy as np in your code, you may be receiving back empty STDOUT and an ModuleNotFoundError in STDERR. You can confirm by extracting STDERR - or check with this code:
Launch.exe(cmd);
where Launch.java is:
public class Launch
{
/** Launch using FILE redirects */
public static int exec(String[] cmd) throws InterruptedException, IOException
{
System.out.println("exec "+Arrays.toString(cmd));
Path tmpdir = Path.of(System.getProperty("java.io.tmpdir"));
ProcessBuilder pb = new ProcessBuilder(cmd);
Path out = tmpdir.resolve(cmd[0]+"-stdout.log");
Path err = tmpdir.resolve(cmd[0]+"-stderr.log");
pb.redirectError(out.toFile());
pb.redirectOutput(err.toFile());
Process p = pb.start();
int rc = p.waitFor();
System.out.println("Exit "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****")
+" STDOUT \""+Files.readString(out)+'"'
+" STDERR \""+Files.readString(err)+'"');
System.out.println();
return rc;
}
}
The fix for using numpy should be to access ProcessBuilder pb.environment() and set your PYTHONPATH for the subprocess before calling start()
I wrote a Java program which executes a PowerShell Command. Here is my code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PowerShellCommand {
public static void main(String[] args) throws IOException {
String command = "powershell.exe your command";
// Getting the version
String command = "powershell.exe $PSVersionTable.PSVersion";
// Executing the command
Process powerShellProcess = Runtime.getRuntime().exec(command);
// Getting the results
powerShellProcess.getOutputStream().close();
String line;
System.out.println("Standard Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
powerShellProcess.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
System.out.println("Standard Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
powerShellProcess.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
}
}
What I want to do is: instead of executing a command in a local PowerShell I want to make the code execute a command in the Windows Server PowerShell which is running on VMware? How should I modify the code to do so?
Have PowerShell invoke the command on the remote host:
String server = "remotehost";
String command = "powershell.exe -Command \"&{Invoke-Command -Computer " +
server + " -ScriptBlock {$PSVersionTable.PSVersion}}\"";
The remote host needs to have PSRemoting enabled for this to work.
I'm trying to execute batch file in java.
My source is below:
List<String> comm = new ArrayList<String>();
comm.add("cmd");
comm.add("c:/Users/cointreau/workspace/pmd-bin-5.3.2/pmd-bin-5.3.2/bin/pmd.bat");
comm.add("-d");
comm.add("C:\\Users\\cointreau\\workspace\\counter\\src\\Counter.java");
comm.add("-f");
comm.add("xml");
comm.add("-R");
comm.add("java-codesize");
comm.add("-r");
comm.add("C:\\Users\\cointreau\\workspace\\counter\\report.xml");
ProcessBuilder probuilder = new ProcessBuilder( comm );
Process process = probuilder.start();
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//Wait to get exit value
try {
int exitValue = process.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the original command line is this,
c:/Users/cointreau/workspace/pmd-bin-5.3.2/pmd-bin-5.3.2/bin/pmd.bat -d C:\\Users\\cointreau\\workspace\\counter\\src\\Counter.java -f xml -R java-codesize -r C:\\Users\\cointreau\\workspace\\counter\\report.xml`
pmd.bat is the batch file what i want to execute and the remainders are just parameters for the bat file.
The only output I can see is just exit Value is 1.
When I execute this command line in cmd, it runs properly but not in my java source.
What should I do?
Thanks for your help in advance.
Try adding the /C option to carry out the batch command
comm.add("cmd");
comm.add("/c");
comm.add("c:/Users/cointreau/workspace/pmd-bin-5.3.2/pmd-bin-5.3.2/bin/pmd.bat");
...
I want to execute database import from .sql file from java program. My program is working fine on windows. But I am facing problem on linux machine.
Code -
try {
ProcessBuilder builder = new ProcessBuilder("mysql -u root -p password db-name < db_script.sql");
builder.redirectErrorStream(true);
Process pr = builder.start();
InputStream is = pr.getInputStream();
// Now read from it and write it to standard output.
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
I am getting - java.io.IOException: Cannot run program "mysql -u root
-p password db-name < db_script.sql":
java.io.IOException: error=2, No such file or directory
The above command is working fine on linux terminal.
Some one please advice me on this.
Thanks in advance
The < redirection is a shell thing. Try something like this:
ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", "mysql -u root -p password db-name < b_script.sql");
UPDATE:
Otherwise, if you're using java 7+, you can do the redirection in java:
ProcessBuilder builder = new ProcessBuilder(
"mysql", "-u", "root", "-p", "password", "db-name");
builder.redirectInput(ProcessBuilder.Redirect.from(new File("b_script.sql")));
have you checked that your code is executed from proper dir??
that if your db_script.sql is inhome then you are running from home as
home>mysql -u root -p password db-name < db_script.sql
or provide full path of db_script.sql in the command
A simple way to achieve it.
String DBUSERNAME = "";
String DBUSERPASSWORD = "";
String sqlfilename = "";
PrintWriter writer = new PrintWriter("tmp.dmp", "UTF-8");
writer.println("mysql --user " + DBUSERNAME + " --password=" + DBUSERPASSWORD + " < " + sqlfilename);
writer.close();
runCommand("chmod 777 tmp.dmp");
runCommand("./tmp.dmp");
runCommand("rm tmp.dmp");
public static void runCommand(String command) throws IOException {
String s = "";
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = null;
BufferedReader stdError = null;
try {
stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} finally {
if (stdInput != null) {
stdInput.close();
}
if (stdError != null) {
stdError.close();
}
}
}
I want to invoke my powershell script from java. Can it be done. I tried with the following code, but the stream is not closing.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestPowershell {
public static void main(String[] args) throws IOException
{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("powershell C:\\testscript.ps1");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
proc.getOutputStream().close();
}
}
Does java invoke a powershell script which performs create remote session and execute cmdlets?
Do we have support to invoke powershell scripts in java?
Anyone could you please help on this.
Awaiting for your responses.
Thanks,
rammj
After starting the process ( runtime.exec() ), add a line to close the input stream of the process ( which JAVA calls output stream!!):
proc.getOutputStream().close();
Now you can do it easily with jPowerShell
powerShell = PowerShell.openSession();
//Print results
System.out.println(powerShell.executeScript("\"C:\\testscript.ps1\"").getCommandOutput());
powerShell.close();
Yes we can create remote session and execute cmdlets using powershell script.
Save the following Power shell script to testscript.ps1
#Constant Variables
$Office365AdminUsername="YOUR_USERNAME"
$Office365AdminPassword="TOUR_PASSWORD"
#Main
Function Main {
#Remove all existing Powershell sessions
Get-PSSession | Remove-PSSession
#Encrypt password for transmission to Office365
$SecureOffice365Password = ConvertTo-SecureString -AsPlainText $Office365AdminPassword -Force
#Build credentials object
$Office365Credentials = New-Object System.Management.Automation.PSCredential $Office365AdminUsername, $SecureOffice365Password
Write-Host : "Credentials object created"
#Create remote Powershell session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $Office365credentials -Authentication Basic –AllowRedirection
Write-Host : "Remote session established"
#Check for errors
if ($Session -eq $null){
Write-Host : "Invalid creditials"
}else{
Write-Host : "Login success"
#Import the session
Import-PSSession $Session
}
#To check folder size
Get-MailboxFolderStatistics "YOUR_USER_NAME" | Select Identity, FolderAndSubfolderSize
exit
}
# Start script
. Main
Java Code :
try {
String command = "powershell.exe \"C:\\testscript.ps1\"";
ExecuteWatchdog watchdog = new ExecuteWatchdog(20000);
Process powerShellProcess = Runtime.getRuntime().exec(command);
if (watchdog != null) {
watchdog.start(powerShellProcess);
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()));
String line;
System.out.println("Output :");
while ((line = stdInput.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
If you do not get output, try this: powerShellProcess.getErrorStream() instead powerShellProcess.getInputStream(). It will show the errors.