Hello guys i want to add an autostart entry in windows registry with java:
String cmd[] = { "regex.exe add ","\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\"", " /v ","\"Test\"", " /t ", "REG_SZ", " /d ", value };
Runtime.getRuntime().exec(cmd);
sysout(value): "javaw -jar C:\Users\name\eclipse-workspace\project\myjar.jar"
sysout(cmd): [regex.exe add , "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", /v , "Test", /t , REG_SZ, /d , "javaw -jar C:\Users\name\eclipse-workspace\project\myjar.jar"]
If i run my code i get some errors:
*Cannot run program "regex.exe add ": CreateProcess error=2, Cannot find your file
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at java.base/java.lang.Runtime.exec(Runtime.java:589)
at java.base/java.lang.Runtime.exec(Runtime.java:448)
at Logger.log.main(log.java:23)
Caused by: java.io.IOException: CreateProcess error=2,
at java.base/java.lang.ProcessImpl.create(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:483)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:158)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 4 more*
What did i wrong? I just want to add my jar into windows startup/autostart
Code example of my advice to start cmd.exe and use the OutputStream to send in the regex command:
Process proc = Runtime.getRuntime().exec("runas /Marcel/user:Administrator cmd.exe");
PrintStream ps = new PrintStream(proc.getOutputStream());
String cmd = "regex.exe add " + " \"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\","
+" /v , \"Test\", /t , REG_SZ, /d , \"javaw -jar " + "C:\Users\name\eclipse-workspace\project\myjar.jar\" ";
ps.println(cmd);
//you should probably also listen for results of the above from the output and error streams
Related
I'm new to java with Talend Open Studio.
I would like to know if it is possible to execute powershell.exe with "Import-Module ActiveDirectory", and then to launch dynamics commands without reloading powershell with "Import-Module ...".
I know this will not work, but my idea could be translated like this :
Runtime.getRuntime().Exec("powershell.exe");
Runtime.getRuntime().Exec("Import-Module ActiveDirectory");
Runtime.getRuntime().Exec("Get-ADUser TestLogin1");
Runtime.getRuntime().Exec("Set-ADUser -Identity TestLogin1 -Company MyCompany1");
Runtime.getRuntime().Exec("Get-ADUser TestLogin2");
Runtime.getRuntime().Exec("Set-ADUser -Identity TestLogin2 -Company MyCompany2");
For this to work, I have to do ...
Runtime.getRuntime().Exec("powershell.exe /c Import-Module ActiveDirectory ; Get-ADUser TestLogin");
Runtime.getRuntime().Exec("powershell.exe /c Import-Module ActiveDirectory ; Set-ADUser -Identity TestLogin1 -Company MyCompany1");
Runtime.getRuntime().Exec("powershell.exe /c Import-Module ActiveDirectory ; Get-ADUser TestLogin_2");
Runtime.getRuntime().Exec("powershell.exe /c Import-Module ActiveDirectory ; Set-ADUser -Identity TestLogin2 -Company MyCompany2");
I don't want to go through a script file because a first update command (Set-ADUser) can have an impact on the next update command.
Thanks.
I found a solution with the jPowerShell library from profesorfalken
https://github.com/profesorfalken/jPowerShell
//Creates PowerShell session (we can execute several commands in the same session)
try (PowerShell powerShell = PowerShell.openSession()) {
//Execute a command in PowerShell session
PowerShellResponse response = powerShell.executeCommand("Import-Module ActiveDirectory");
//Get an ADUser
PowerShellResponse response = powerShell.executeCommand("Get-ADUser TestLogin1");
//Print results ADUser
System.out.println("PS : " + response.getCommandOutput());
//Set an ADUser
PowerShellResponse response = powerShell.executeCommand("Set-ADUser -Identity TestLogin1 -Company MyCompany1");
//Get an ADUser
PowerShellResponse response = powerShell.executeCommand("Get-ADUser TestLogin2");
//Print results ADUser
System.out.println("PS : " + response.getCommandOutput());
//Set an ADUser
PowerShellResponse response = powerShell.executeCommand("Set-ADUser -Identity TestLogin2 -Company MyCompany2");
} catch(PowerShellNotAvailableException ex) {
//Handle error when PowerShell is not available in the system
//Maybe try in another way?
}
I want to use ProcessBuilder to create an environment that I can reuse for multiple batch files, in order to automate some testing I repeatedly perform. Specifically, I need to run vcvars64.bat (x64 Native Tools Command Prompt for VS 2019) to set up the system environment, before I run my tests.
To manually run the tests, I would bring up a command prompt, run vcvars64.bat, and then manually run a number of batch files.
I have been able to use ProcessBuilder to launch my test batch files, but they return the error that I see if I forgot to run vcvars64.bat before running the tests.
My attempts so far have been to instantiate a ProcessBuilder using vcvars64.bat as the command, .start() it, .waitFor() the Process to finish, then reuse that same ProcessBuilder for Test1.bat then Test2.bat etc, in the hopes it would retain the environment settings.
Here is the relevant section of my code:
ProcessBuilder processBuilder = new ProcessBuilder();
Process process;
Map<String, String> envMap = processBuilder.environment();
for( Map.Entry<String, String> entry : envMap.entrySet() )
{
System.out.println( "1 - Key: \"" + entry.getKey() + "\", Value: \"" + entry.getValue() + "\"" );
}
try
{
process = processBuilder.command( "C:\\Windows\\system32\\cmd.exe", "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\VC\\Auxiliary\\Build\\vcvars64.bat" )
.directory( new File( "C:\\bat\\" ) )
.redirectInput( new File( "C:\\bat\\", "cr4.txt" ) )
.redirectOutput( new File( edgePath, "tempFile.txt" ) )
.start();
MAIN_LOGGER.log( Level.INFO, "Waiting for the CMD process to finish..." );
process.waitFor();
envMap = processBuilder.environment();
for( Map.Entry<String, String> entry : envMap.entrySet() )
{
System.out.println( "2 - Key: \"" + entry.getKey() + "\", Value: \"" + entry.getValue() + "\"" );
}
// Now try to run my batch file that requires parameters normally set by vcvars64.bat
process = processBuilder.command( "C:\\bat\\TestBatch.bat" )
.directory( new File( "C:\\bat\\" ) )
.redirectInput( new File( "C:\\bat\\", "cr4.txt" ) )
.redirectOutput( new File( "C:\\bat\\", "tempFile.txt" ) )
.start();
}
catch( IOException | InterruptedException e )
{
System.out.println( e.getLocalizedMessage() );
}
Is my plan correct, and my implementation buggy? Or do I need a new plan?
Unfortunately processBuilder.environment() won't pick up any changes inside the VC bat file so your double launch won't help. However depending on what vcvars64.bat looks like you may be able to package up your own launch.cmd file which you call passing two parameters: path to VC batch, and the path to your actual script to run. Then your ProcessBuilder command is just something like:
String launch = "C:\\bat\\launch.cmd";
String vcenv = "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\VC\\Auxiliary\\Build\\vcvars64.bat";
String task = "C:\\bat\\TestBatch.bat";
String[] cmd = new String[] {"cmd.exe", "/c", launch, vcenv, task};
process = processBuilder.command(cmd);
Example launch.cmd:
call %1
call %2
exit /b %errorlevel%
Example task.bat:
echo RUNNING TASK %0
I am trying to run Appium Serve on my Windows 7 machine using a simple command:
D:\Appium\node.exe D:\Appium\node_modules\appium\bin\Appium.js -g C:\Users\vdopia\AppData\Local\Temp\applog_12232015_110310.txt --no-reset
in command prompt, it shows that Appium is started. When I browse the url http://127.0.0.1:4723, I get the message below in my command prompt and because of this I am not able initialize remotedriver also. Surprisingly, the same thing works well in MAC.
Logs:
> info: --> GET / {}
> info: [debug] Responding to client that we did not find a valid resource
> info: <-- GET / 404 0.712 ms - 47
> info: <-- GET /favicon.ico 200 0.535 ms - 1150
I am pasting code here to start appium server, first I am writing command in a sh or bat file then executing the bat file.
public static boolean startAppiumServer()
{
//Kill any Existing Appium Before Starting new session
logger.info("Stopping any running instance of appium. ");
try{SDKCommonUtils.killAppiumServer();}catch(Exception e){}
boolean flag = false;
File logFile = null;
String commandFile = null;
if(System.getProperty("os.name").matches("^Windows.*"))
{
//Getting temp dir
String tempDir = System.getProperty("java.io.tmpdir").toString();
logFile = new File(tempDir+"\\applog"+"_"+MobileTestClass_Methods.DateTimeStamp()+".txt");
commandFile = System.getenv("AUTOMATION_HOME").concat("\\tpt\\appium_commands.bat");
String appiumCmdLocation_Windows = MobileTestClass_Methods.propertyConfigFile.getProperty("appiumCmdLocationForWindows").toString();
String nodeExe = appiumCmdLocation_Windows.concat("\\node.exe");
String appiumJs = appiumCmdLocation_Windows.concat("\\node_modules\\appium\\bin\\Appium.js");
String strText = "start /B " + nodeExe + " " + appiumJs + " -g " + logFile.toString() + " --full-reset --command-timeout 60 ";
FileLib.WriteTextInFile(commandFile, strText);
}
else
{
logFile = new File("/tmp/applog"+"_"+MobileTestClass_Methods.DateTimeStamp()+".txt");
commandFile = System.getenv("AUTOMATION_HOME").concat("/tpt/appium_commands.sh");
String strText = "export PATH=$PATH:/usr/local/bin; /usr/local/bin/appium -g " + logFile.toString() + " --full-reset --command-timeout 60 " ;
FileLib.WriteTextInFile(commandFile, strText);
}
try
{
logger.info("Executing Command File: "+ commandFile +" to start appium service. ");
Runtime.getRuntime().exec(commandFile);
/** wait until appium server is started */
flag = waitForAppiumServer();
}
catch(Exception e)
{
flag = false;
logger.error("There were some issues while executing command to launch appium service. ",e);
}
return flag;
}
If you do not provide server address then it will be used as 0.0.0.0 from command prompt in windows as
info: Appium REST http interface listener started on 0.0.0.0:4723.
Please provide --address 127.0.0.1 --port 4723 parameter from command line and try to use same address and port while initializing driver object in your script.
I tried to ban an ip-adress temporarly if someone tryes to not join over the proxy to the minecraft server.
String st = e.getRealAddress() + "";
if(!st.startsWith("/x.x.x.x")) {
Runtime runtime = Runtime.getRuntime();
runtime.exec("iptables -A INPUT -s " + st.replace("/","") + " -j DROP");
runtime.exec("sleep 180 ; iptables -D INPUT -s " + st.replace("/","") + " -j DROP");
}
But for some reason to only executes the -A command and after I've waited three minutes I wasn't able to connect. What did I have done wrong?
you can:
decompose yourself the orders in java: iptables , wait, sleep, iptables, ...
then you must wait first iptables to finish:
use waitFor :
Process p = Runtime.getRuntime().exec("your command iptables");
p.waitFor();
I am trying to make a java program that will launch minecraft in offline mode with whatever username i want so i can have usernames like Notch and deadmau5 and i am using this code to launch it on mac and windows (Currently Testing on mac):
public void startMacMinecraft(String username) throws IOException,
InterruptedException {
System.out.println(defaultDirectory());
String sysUser = System.getProperty("user.name");
String commandString = "java -cp "
+ defaultDirectory()
+ "/minecraft/bin/minecraft.jar:"
+ defaultDirectory()
+ "/minecraft/bin/lwjgl.jar:"
+ defaultDirectory()
+ "/minecraft/bin/lwjgl_util.jar:"
+ defaultDirectory()
+ "/minecraft/bin/jinput.jar: -Djava.library.path="
+ defaultDirectory()
+ "/minecraft/bin/natives -Xmx1024M -Xms512M net.minecraft.client.Minecraft '"
+ username + "'";
CommandLine command = CommandLine.parse(commandString);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(command);
System.out.println(exitValue);
System.out.println("\nTry Two:\n");
String javaExe = System.getProperty("java.home") + "/bin/java";
}
public void startWinMinecraft(String username) throws IOException,
InterruptedException {
String sysUser = System.getProperty("user.name");
String commandString = "Java -Xms512m -Xmx1024m -cp \"%APPDATA%\\.minecraft\\bin\\*\" -Djava.library.path=\"%APPDATA%\\.minecraft\\bin\\natives net.minecraft.client.Minecraft \""
+ username + "\"";
CommandLine command = CommandLine.parse(commandString);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(command);
System.out.println(exitValue);
}
private static String defaultDirectory() {
String OS = System.getProperty("os.name").toUpperCase();
if (OS.contains("WIN"))
return System.getenv("APPDATA");
else if (OS.contains("MAC"))
return System.getProperty("user.home") + "/Library/Application "
+ "Support";
else if (OS.contains("NUX"))
return System.getProperty("user.home");
return System.getProperty("user.dir");
}
Which i am trying to adapt from this applescript which i have run before and got from https://gaming.stackexchange.com/questions/46608/how-can-i-run-minecraft-in-offline-mode-on-os-x-and-still-have-my-name that i will paste right here:
property user_name : "Player"
display dialog "Enter A User Name" default answer "" buttons {"Cancel", "Continue"} default button 2
set the user_name to text returned of the result
set UsrApp to (path to current user folder)
set UsrApp_unx to POSIX path of UsrApp
set MineScript to "java -cp " & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/minecraft.jar:" & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/lwjgl.jar:" & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/lwjgl_util.jar:" & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/jinput.jar: -Djava.library.path=" & UsrApp_unx & "Library/Application\\ Support/minecraft/bin/natives -Xmx1024M -Xms512M net.minecraft.client.Minecraft '" & user_name & "'"
do shell script MineScript
When i run the applescript it works perfectly fine but when i run my adapted version it gives me a class not found error:
Logging in as: Player
/Users/Connor/Library/Application Support
Exception in thread "main" java.lang.NoClassDefFoundError: Support/minecraft/bin/minecraft/jar:/Users/Connor/Library/Application
Caused by: java.lang.ClassNotFoundException: Support.minecraft.bin.minecraft.jar:.Users.Connor.Library.Application
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:377)
at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:160)
at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:147)
at info.connorbp.GUIApp.LoginPanel.startMacMinecraft(LoginPanel.java:137)
at info.connorbp.GUIApp.LoginPanel$1.actionPerformed(LoginPanel.java:82)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6375)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6140)
at java.awt.Container.processEvent(Container.java:2083)
at java.awt.Component.dispatchEventImpl(Component.java:4737)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Component.dispatchEvent(Component.java:4565)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
at java.awt.Container.dispatchEventImpl(Container.java:2127)
at java.awt.Window.dispatchEventImpl(Window.java:2482)
at java.awt.Component.dispatchEvent(Component.java:4565)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:684)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:643)
at java.awt.EventQueue$1.run(EventQueue.java:641)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:657)
at java.awt.EventQueue$2.run(EventQueue.java:655)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:654)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
does anyone know what i am doing wrong or how to fix it?
EDIT:
Even stranger yet, I went into the events area of the applescript area and found the exact command the applescript was running:
java -cp /Users/Connor/Library/Application\\ Support/minecraft/bin/minecraft.jar:/Users/Connor/Library/Application\\ Support/minecraft/bin/lwjgl.jar:/Users/Connor/Library/Application\\ Support/minecraft/bin/lwjgl_util.jar:/Users/Connor/Library/Application\\ Support/minecraft/bin/jinput.jar: -Djava.library.path=/Users/Connor/Library/Application\\ Support/minecraft/bin/natives -Xmx1024M -Xms512M net.minecraft.client.Minecraft 'username'
and even when a tried running the script that came directly from the applescript i got another java.lang.NoClassDefFoundError error, even though i took the command directly from the applescript that is working.
In the default launcher, whatever username you provide gets used for offline mode, so writing a separate launcher is pointless.
In any case, decompiling the launcher should give us a pretty good idea of how to launch the game.
There is a lot of code so I recommend decompiling it yourself. For mac, JD-GUI does an alright job. For windows, I can't recommend a decompiler, but thats what google is for :)
After you get the launcher source code, have a peek at public void login(String userName, String password) in net.minecraft.LauncherFrame. Also relevant is net.minecraft.Launcher.
Reading through that should give you a pretty good idea of how to launch minecraft.
Oops, forgot about this question. I was actually just missing some of the code that was needed in order to launch minecraft.