I want to run a PowerShell command for create user using Java on a remote windows machine, I am writing this code in eclipse.
And below is the output, tried every reference and forms to resolve this issue can someone help me with this.
The command works on PowerShell command line, but it is not working in Java.
public class PowerShellSession {
private static String subModule = "PowerShellSession";
String targetIpAddress;
String username;
String password;
public static Object connectPShellLock = new Object();
public PowerShellSession() {}
public void exec(String cmd, String credentials) {
//String ex = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";
String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";
String[] args = new String[] { "powershell", ex};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
String command = "Exit-PSSession";
String[] args = new String[] { "powershell", command};
try {
execRemote(args);
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCredentials(String domain, String userName,
String password) throws IOException {
String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
+ "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
+ "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
//creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";
String[] args = new String[] { "powershell", creds};
execRemote(args);
return creds;
}
private void execRemote(String[] arguments) throws IOException {
ProcessBuilder builder = new ProcessBuilder(arguments);
builder.redirectErrorStream(true);
Process process = builder.start();
doProcessIO(process);
}
// Do the IO for a passed process
private void doProcessIO(Process p) throws IOException {
p.getOutputStream().close();
String line;
System.out.println("Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
System.out.println("Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
p.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
}
public static void main(String[] args) throws IOException {
String ip_add = "192.168.193.101";
String user = "gs-259412";
String pass = "Windows412";
PowerShellSession psSession = new PowerShellSession();
String credentials = psSession.getCredentials(ip_add, user, pass);
psSession.targetIpAddress = ip_add;//;
String cmdd = "New-LocalUser -Name \"User02\" -Description \"Description of this account.\" -NoPassword";//"Get-Culture";
if(!credentials.equals("")) {
psSession.exec(cmdd, credentials);
System.out.println("Finished PowerShell remote session.");
}
psSession.close();
}
}
Output of this program :
Output:
Error:
Done
Output:
A positional parameter cannot be found that accepts argument 'of'.
+ CategoryInfo : InvalidArgument: (:) [New-LocalUser], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewLocalUserCommand
+ PSComputerName : 192.168.193.131
Error:
Done
Finished PowerShell remote session.
I tried this link also enter link description here
Today I meet a problem with "java" command.
I work in Intellij IDEA and think that I wrong classpath to "java" command.
Please, help me.
package ru.mch;
import ru.mch.RunTask;
public class Program {
public static void main(String[] args) {
String taskCode = "class UserProgram{ public static void main(String[] args) { int b = 3 + 1; System.out.println(b);}}";
String packageName = "package ru.mch; ";
String all = packageName + taskCode ;
RunTask runTask = new RunTask(all);
int result = runTask.run();
}
}
I want to get program code from String, create new java class, write code to the class and compile and run new java class.
package ru.mch;
import java.io.*;
public class RunTask {
private String answerFromPage;
private int programExitValue;
public RunTask(String answerFromPage) {
this.answerFromPage = answerFromPage;
this.programExitValue = 0;
}
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
private static int runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(/*command + */" stdout:", pro.getInputStream());
printLines(" stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exit value = " + pro.exitValue());
return pro.exitValue();
}
public int run(){
//String fileName = "src\\main\\java\\ru\\mch\\UserProgram.java";
String fileName = "src\\main\\java\\ru\\mch\\UserProgram.java";
File f = new File(fileName);
f.getParentFile().mkdirs();
try {
f.createNewFile();
} catch (IOException e) {
throw new IllegalArgumentException("File creating error");
}
try(FileWriter writer = new FileWriter(fileName, false))
{
writer.write(this.answerFromPage);
writer.flush();
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
try {
System.out.println(runProcess("javac -sourcepath src src\\main\\java\\ru\\mch\\UserProgram.java"));
System.out.println("------------");
this.programExitValue = runProcess("java src\\main\\java\\ru.mch.UserProgram");
} catch (Exception e) {
e.printStackTrace();
}
return this.programExitValue;
}
}
This is IDEA log :
javac src\main\java\ru\mch\UserProgram.java exit value = 0
0
------------
Error: Could not find or load main class src\main\java\ru.mch.UserProgram
java src\main\java\ru.mch.UserProgram exit value = 1
New class was created and .class too.
I try to write full classpath, try to write '\' instead of '.' in package name, but all is wrong.
Sorry for my bad English.
Use the following command:
java -cp src\main\java ru.mch.UserProgram
I want to query user credentials against an Active Directory without the user entering his credentials. i.e The user logs into his corporate system(Intranetwork) i need to use these credentials to verify against an AD and retrieve his email address if the user exists.(NO single sign on required)
Of course, It is too late to answer, but ... someone like me can search same answer...
I'm just not sure why do you need to verify user credentials?
If user already logged-in then ... credentials are verified.
Getting his email (and other info from AD) is possible by using Windows powershell.
public class TestWindowsAD {
public static void main(String... args) throws Exception {
System.out.println("Current user e-mail: " + getCurrentUserEmail());
}
private static String getCurrentUserEmail() {
String cmd = "powershell \"Add-Type -AssemblyName System.DirectoryServices.AccountManagement;[System.DirectoryServices.AccountManagement.UserPrincipal]::Current.EmailAddress;\"";
String userEmail = "";
if (!System.getProperty("os.name").toLowerCase().startsWith("win")) { throw new RuntimeException(
"We are not in Windows! OS is " + System.getProperty("os.name")); }
Runtime rt = Runtime.getRuntime();
Process pr;
try {
pr = rt.exec(cmd);
pr.waitFor();
BufferedReader bf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String nextLine = null;
while (true) {
nextLine = bf.readLine();
if (nextLine == null) break;
userEmail = nextLine;
}
bf.close();
} catch (Exception e) {
System.err.println("Failed to get user email: " + e.getMessage());
throw new RuntimeException(e);
}
return userEmail;
}
P.S. if you need more info just run in command prompt:
powershell "Add-Type -AssemblyName System.DirectoryServices.AccountManagement;[System.DirectoryServices.AccountManagement.UserPrincipal]::Current"
and pick what you need.
I am using Ubuntu. I want to use java application to dump the MySQL database. Below are my code:
String userName = "root";
String userPassword = "root";
String oldDatabaseName = "testing";
String executeCommand = "";
executeCommand = "mysqldump -u "+userName+" -p"+userPassword+" --no-data "
+OldDatabaseName+" > testingbackup.sql";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
System.out.println("Backup successful.");
}else{
System.out.println("Backup failed.");
}
But, when I run the above program, I always get the "Backup failed" message.
Am I writing the wrong code? And what library/file I need to include in my java application? Any help please.
This is working fine in my windows machine.
package org.some.test;
import java.io.File;
public class dateformat {
private static final String dbUserName = "root";
private static final String dbPassword = "manager";
private static final String dbName = "opencms";
public static void main(String[] args){
try {
File path =new File("D:\\dump1.sql");
String[] executeCmd = new String[]{"C:/Program Files/MySQL/MySQL Server 5.6/bin/mysql", "--user=" + dbUserName, "--password=" + dbPassword,""+ dbName,"-e", "source "+path};
Process p = Runtime.getRuntime().exec(executeCmd);
int processComplete = p.waitFor();
if (processComplete == 0)
{
System.out.println("Restore created successfully");
//return true;
}
else
{
System.out.println("Could not restore");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
It seems to me you omitted a space between -p and quote:
-p "+userPassword+
^-- insert space here
I was able to create a backup of my current mysql database as .SQL file using the mysqldump.exe with the help of the following java code.
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql");
Now I want to restore this same .SQL Backup file to mysql database using java code similar to above on the event of a button clicked.
Thanks a lot :)
So now I tried this ;
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr < C:\\SCM Files\\SQL Backup\\RR.sql");
Still it didn't work :/
public static boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", " source "+source};
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup restored successfully");
return true;
}
} else {
System.out.println("Could not restore the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
source example : "E:\\My Backup\\Test\\file.sql"
Runtime.getRuntime().exec("mysql -u username -ppassword database_name FILE.sql")
This statement will regenerate database from the file
You have to use java swings where you can design forms. Here is some code which can do that.
import javax.swing.JFrame;
public final class RestoreMySQLDatabase extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
RestoreMySQLDatabase restoreMySQL = new RestoreMySQLDatabase();
restoreMySQL.setTitle("Restore mysql database");
javax.swing.JButton butRestore = new javax.swing.JButton("Restore");
butRestore.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event){
try{
Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql");
javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Successfully restored");
}catch(java.lang.Exception e){
javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Not able to restore");
}
}
});
}
}
I tried this code and works as perfect!
String[] restoreCmd = new String[]{"mysql ", "--user=" + DB.DB_USERNAME, "--password=" + DB.DB_PASSWORD, "-e", "source " + pathToFile};
try {
Process runtimeProcess = Runtime.getRuntime().exec(restoreCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Done");
} else {
System.out.println("Failed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
You should try DbUnit for backup and restore of database.Here is the demo code for that:
try {
Class.forName(DBDRIVER);
Connection jdbcConnection = DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD);
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new MySqlDataTypeFactory());
//////// Database backup
ITableFilter filter = new DatabaseSequenceFilter(connection);
IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet());
ExcludeTableFilter excludeFilter = new ExcludeTableFilter();
excludeFilter.excludeTable("DATABASECHANGELOG*");
IDataSet excludedataset = new FilteredDataSet(excludeFilter, dataset);
FlatXmlDataSet.write(excludedataset, new FileOutputStream(backupfilename));
System.out.println("\n Complete backup successful.");
//////// Database backup
//////// Database restore
IDataSetProducer producer = new FlatXmlProducer(new InputSource(restoreFileName));
IDataSet dataSet = new StreamingDataSet(producer);
TransactionOperation operation = new TransactionOperation(DatabaseOperation.INSERT);
operation.execute(connection, dataSet);
//////// Database restore
} catch (DatabaseUnitException e) {
e.printStackTrace();
flag = false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
Use the same dump to import like this.
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr database_name < "C:\\SCM Files\\SQL Backup\\RR.sql");
For restore use the executeCmd in the form m.Torkashvand provided (array of strings). A working example on how to use these commands from JSP code can be found here
public static void mysqlExport(String host, String port, String user, String password, String dbname, String table, String folder, String query) {
System.out.println("------ Exporting "+dbname+"."+table+" at "+folder+"---------------------------");
try {
String command = "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " --where=\"" + query + "\" > " + folder + table + ".sql";
System.out.println(command);
int returnValue = executeCommand(Arrays.asList("mysqldump", "--host="+host, "--port="+port, "--user="+user, "--password="+password, dbname, table, "--where="+query), folder + table + ".sql");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void mysqlImport(String host, String port, String user, String password, String dbname, String table, String folder) {
System.out.println("------ Importing "+dbname+"."+table+" at "+folder+"---------------------------");
try {
String command = "mysql --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " < " + folder + table + ".sql";
System.out.println(command);
int returnValue = executeCommand(new String[]{"mysql", "--host="+host, "--port="+port, "--user=" + user, "--password=" + password, dbname, "-e", "source " + folder + table + ".sql"});
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static int executeCommand(String[] commands) throws IOException
{
System.out.println(commands.toString());
Process process = Runtime.getRuntime().exec(commands);
return dumpProcess(process);
}
public static int executeCommand(List<String> commands, String folder) throws IOException
{
ProcessBuilder builder = new ProcessBuilder(commands);
System.out.println(builder.command());
builder.redirectOutput(new File(folder));
Process process = builder.start();
return dumpProcess(process);
}
public static int dumpProcess(Process process) throws IOException
{
int returnValue = -1;
try {
String s = null;
process.waitFor();
returnValue = process.exitValue();
if (returnValue == 0) {
System.out.println("Command successful !!");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} else {
System.out.println("Command failed. Exist Status code = "+returnValue);
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
This is working code
public class Recover {
final static String filepath = "/home/shubhampanchal/Downloads/backup/configuration_files.sql";
public static void main(String[] args) throws Exception {
try {
String[] restoreCmd = new String[]{"mysql", "-uroot", "-p1", "Student", "-e", "source " + filepath};
Runtime rt =Runtime.getRuntime();
rt.exec(restoreCmd);
System.out.println("Restored successfully!");
} catch(Exception e) {
e.printStackTrace();
}
}
}