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.
Related
I would like to write a Java program to control the Android emulator to do some testing, and now I have to take snapshots of the emulator when it is created and every time it has changes, so according to google, the command is like:
telnet localhost 5555
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK
avd snapshot save 1
OK
So basically two commands, the first is to open a telnet connection and then enter avd snapshot save x command to save the snapshot.
However using the command like this:
public static void main(String[] args) throws IOException{
int initScore = 1000;
int ID = 0;
// monitor the log, check if a new activity is reached.
// if so, take a snapshot of the current activity and save it to the snapshot folder.
String cmd1 = "telnet localhost " + 5555;
// the static port 5557 should change to this.getVM_consolePort();
String cmd2 = "avd snapshot save " + ID;
ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", cmd1, cmd2);
Process p = pb.start();
// read the process output
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
can only run the first command (which is to open telnet connection).
So could anyone tell me how to interact with a opened connection or enter command to another process in Java?
Here's an example using grep:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class Test {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "grep foo");
Process p = pb.start();
BufferedReader stdOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
Writer stdIn = new OutputStreamWriter(p.getOutputStream());
stdIn.write("foo1\nbar\nfoo2\n");
stdIn.close();
String s = null;
while ((s = stdOut.readLine()) != null) {
System.out.println(s);
}
while ((s = stdErr.readLine()) != null) {
System.out.println(s);
}
}
}
I renamed stdIn to stdOut, so they are named from the point of view of the process you're running.
I read from stderr, so that you can see any problems.
Actually I have tried this before like the code below:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
public class Main {
public static void main(String[] args) throws IOException {
// int initScore = 1000;
int ID = 0;
Process p = Runtime.getRuntime().exec("telnet localhost 5555");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter stdIn = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String line;
while ((line = stdInput.readLine()) != null) {
System.out.println(line);
if (line.contains("OK")){
break;
}
}
stdIn.write("avd snapshot save " + ID);
while ((line = stdInput.readLine()) != null) {
System.out.println(line);
}
}
}
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK
I think the reason is that the telnet created a new shell and the writer is writing to the old shell, therefore it is not working, so I am looking for a solution to enter the new command into the new shell.
I have a PowerShell Command which I need to execute using Java program. Can somebody guide me how to do this?
My command is Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize
You should write a java program like this, here is a sample based on Nirman's Tech Blog, the basic idea is to execute the command calling the PowerShell process like this:
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");
}
}
In order to execute a powershell script
String command = "powershell.exe \"C:\\Pathtofile\\script.ps\" ";
No need of reinvent the wheel. Now you can just use jPowerShell
String command = "Get-ItemProperty " +
"HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* " +
"| Select-Object DisplayName, DisplayVersion, Publisher, InstallDate " +
"| Format-Table –AutoSize";
System.out.println(PowerShell.executeSingleCommand(command).getCommandOutput());
you can try to calle the powershell.exe with some commands like :
String[] commandList = {"powershell.exe", "-Command", "dir"};
ProcessBuilder pb = new ProcessBuilder(commandList);
Process p = pb.start();
You can use -ExecutionPolicy RemoteSigned in the command.
String cmd = "cmd /c powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive C:\Users\File.ps1
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));
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.