How to request elevation with the 'run as' verb in Java - java

I tried to run this Java app:
public class Run_Process {
public static void main(String[] args) {
String myCommandIp = "netsh interface ip set address name=\"Ethernet\" static 192.168.0.4 255.255.255.0 192.168.0.1 1";
String myCommand2Dns = "netsh interface ipv4 add dnsserver \"Ethernet\" address=192.168.0.1 index=1";
runCommand(myCommandIp);
runCommand(myCommand2Dns);
}
static void runCommand(String command) {
try {
new ProcessBuilder(command.split(" ")).redirectError(ProcessBuilder.Redirect.INHERIT)
.redirectOutput(ProcessBuilder.Redirect.INHERIT).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
but I get:
The requested operation requires elevation(Run as administrator)
How to launch my app again, requesting elevation with the 'run as' verb? This is how I did it in Python. However, I need help to do it in Java.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes, sys, subprocess
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
subprocess.call(['wmic', '/output:usracc.txt', 'useraccount', 'list', 'full', '/format:csv'])
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
This has been asked so many times, but I need a concrete example for my case because I'm noob.
I will explain why this is not a duplicate of linked question. Using a shortcut is not an option. I have to assume that the user doesn't know how to create a shortcut. JNA and wizmo solutions are not explained. Here it says that:
So, in the Java world, you just have to do exactly what everyone else
has to do: launch your app again, requesting elevation. There are
several ways to launch elevated, the 'run as' verb probably being the
easiest.
So, I ask for help how to use a solution with 'run as' verb and ShellExecute in Java.

Ok, this is an answer to my question. I will leave this here for future reference. Firstly, I downloaded JNA from here. Run them with java -jar jna.jar and imported in my Eclipse project.
This will open cmd as admin if you answer yes in UAC and then it will run netsh command. It's the runas which starts UAC. You can use open to start cmd as normal user.
This SO answer helped me a lot with jna, a this one too with passing arguments in ShellExecute. Here you can read what /S and /C do.
import com.sun.jna.*;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.win32.*;
public class Main {
public interface Shell32 extends ShellAPI, StdCallLibrary {
Shell32 INSTANCE = (Shell32)Native.loadLibrary("shell32", Shell32.class);
WinDef.HINSTANCE ShellExecuteA(WinDef.HWND hwnd,
String lpOperation,
String lpFile,
String lpParameters,
String lpDirectory,
int nShowCmd);
}
public static void main(String[] args) {
WinDef.HWND h = null;
Shell32.INSTANCE.ShellExecuteA(h, "runas", "cmd.exe", "/S /C \"netsh interface ip set address name=\"Wi-Fi\" static 192.168.88.189 255.255.255.0 192.168.88.1 1\"", null, 1);

Related

Error running RMI application in Visual Studio Code [duplicate]

I'm programming a simple rmi application, and I have a problem.
If I run the registry in the same directory, it works; but if I change the directory from which I run the registry, it does not.
The registry would work generically from another host, but only the change of directory stop his functionality.
I'm working on this problem by 3 days without solution, I change also every possible configuration of the codebase parameter but nothing.
I describe the situation and code with the directory:
fileserver.java :
`package testrmi2;
import java.rmi.*;
public interface fileserver extends Remote {
public void scrivifile(String nomefile, String arg) throws RemoteException;
}
`
fileserverimpl.java:
package testrmi2;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class fileserverimpl extends UnicastRemoteObject implements fileserver{
public fileserverimpl() throws RemoteException {
super();
}
public void scrivifile(String nomefile, String arg) throws RemoteException {
try {
FileWriter myfile = new FileWriter(nomefile);
myfile.write(arg);
myfile.close(); }
catch (Exception e) {System.out.println(e);}
}
public static void main (String arg[]) {
try {
fileserverimpl s = new fileserverimpl();
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
String codebase = System.getProperty("classpath");
System.out.println("Trying to access code base: " + codebase+"\n\nuse is "+System.getProperty("useCodebaseOnly"));
Naming.rebind("//127.0.0.1:2005/fileserverimpl", s);
System.out.println("Server attivato.");
} catch (Exception e) {System.out.println("errore inizializzazione server\n\n"+e.getMessage()+"\n\n\n");
}}}
client.java:
package testrmi2;
import java.rmi.*;
import java.io.*;
public class client {
public static void main (String arg[]) {
fileserver myserver;
String nomefile=" ";
String testo=" ";
System.out.println("Scrivi il nome del file");
nomefile=ReadString();
System.out.println("Scrivi il testo");
testo=ReadString();
try {
myserver = (fileserver) Naming.lookup("//127.0.0.1:2005/fileserverimpl");
myserver.scrivifile(nomefile, testo);
} catch (Exception e) {System.out.println(e);}
}
public static String ReadString() {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(System.in));
String s=" ";
try{
s=stdIn.readLine();
}
catch(IOException e) {System.out.println(e.getMessage()); }
return s;
}
}
and the policy file is:
grant {
// Allow everything for now
permission java.security.AllPermission;
};
all this files are on the directory:
/Users/franco/Desktop/prova
to compiling it I goes in the /Users/franco/Desktop/prova directory and do in terminal :
javac -cp . -d . *.java
rmic rmic testrmi2.fileserverimpl
jar cvf testrmi2.jar testrmi2/fileserver.class testrmi2/fileserverimpl_Stub.class
after I run registry in another terminal with the following commands but in another directory:
export classpath=""
rmiregistry 2005 &
Finally I would to run the filesereveimpl.class goes with terminal in the /Users/franco/Desktop/prova directory and write :
java -classpath /Users/franco/Desktop/prova/ -Djava.rmi.server.codebase=file:/Users/franco/Desktop/prova/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
But the results are:
Trying to access code base: null
use is null
errore inizializzazione server
RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub
I also try to public he jar on a local webserver xampp and try to run with the following:
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2/ -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
or with :
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
but I have the same results.
Try to set the classpath var before to execute the rmregistry:
export classpath="/Users/franco/Desktop/prova/"
rmiregistry 2005 &
There are three cases.
You got that exception in the server when exporting/constructing the remote object. Solution: run rmic to generate the stub.
You got it in the server when binding/rebinding. Solution: make the stub class available to the Registry's CLASSPATH, or run the Registry in the server JVM via LocateRegistry.createRegistry().
You got it in the client, in lookup(). Solution: make the stub class available to the client's CLASSPATH.
These also apply to the remote interface itself, and any application classes it depends on, and so on recursively until closure.
Solution for stubs to all three: take the measures outlined in the Javadoc preamble to UnicastRemoteObject, so you don't need a stub at all.

Open a URL in Chrome using Java in Linux and MAC

How to start chrome using Java?
For Windows the code is just as simple as below.
Runtime.getRuntime().exec(new String[]{"cmd", "/c", "start chrome http://localhost:8080"});
Is there something like above?
In Linux you can use like this:
Runtime.getRuntime().exec(new String[]{"bash", "-c", "/path/to/chrome http://yourwebsite.com"});
Replace the /path/to/chrome with the path in your system. Generally Google Chrome is installed at /opt/google/chrome/chrome
Or you can use google-chrome like this:
Runtime.getRuntime().exec(new String[]{"bash", "-c", "google-chrome http://yourwebsite.com"});
If you want to open up in chromium browser in Linux use it like this:
Runtime.getRuntime().exec(new String[]{"bash", "-c", "chromium-browser http://yourwebsite.com"});
For MAC OS try like this:
Runtime.getRuntime().exec(new String[]{"/usr/bin/open", "-a", "/Applications/Google Chrome.app", "http://yourwebsite.com/"});
You can use Selenium.
import org.openqa.selenium.chrome.ChromeDriver;
public class App
{
public static void main(String[] args) throws Throwable
{
ChromeDriver driver = new ChromeDriver();
System.setProperty("webdriver.chrome.driver", "/usr/bin/google-chrome");
// And now use this to visit Google
driver.get("http://www.google.com");
}
this should work fine for ubuntu 15.10 or higher
String[] cmd = {"bash","-c","google-chrome www.yourUrl.com"};
Process p = Runtime.getRuntime().exec(cmd);
Hope it helps.
>>> Check here (Note: Java File is Compiled and run by commands on Terminal)
File name: Test.java
public class Test {
public static void main(String[] args) {
try {
System.out.println("Executing command to open a chrome tab with terminal command!");
Runtime.getRuntime().exec(new String[]{"bash", "-c", "google-chrome https://stackoverflow.com/"});
System.out.println("A New tab or window should get opened in your Chrome Browser with Stack Overflow website!");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**here
google-chrome https://stackoverflow.com/ -> terminal command to open a new chrome tab or window with the stack-overflow website.
**/

Calling java function from .py file in Pydev

I have a file.py as follows :
import unittest
from com.bahmanm import Greeter
class A(unittest.TestCase, Greeter):
def test_A(self):
self.greet("Bahman")
if __name__ == "__main__":
unittest.main()
In above case, Greeter is a java file as:
package com.bahmanm;
public class Greeter
{
private String msg;
public Greeter()
{
msg = "Hello, ";
}
public void greet(String name)
{
System.out.println(msg + name);
}
}
The code executes successfully, but I am not able to navigate from python code to java code (in PyDev) at line self.greet("Bahman") in the file.py code.
Though, I am able to view the contents of Greeter file from line
from com.bahmanm import Greeter. But unable to check the code flow at the function call.
I am using jython interpreter (grammar 2.5, default interpreter,jython.jar 2.5.3). I have also added the Java src path to PYTHONPATH in Eclipse. Also I have added Java project in the
PYTHON PROJECT->RIGHT CLICK->PROPERTIES-> PROJECT REFERENCES
Any suggestion regarding the above navigation will be of great help.

Run Non GUI Jar Files

I know that I can run non GUI jar files from the command line. Is there any way that can do so by clicking or something and not writing the commands again and again.? Is there any software to do so. ( I am talking about a compiled jar and don't want to run from any ide)
public static final String TITLE = "CONSOLE title";
public static final String FILENAME = "myjar.jar";
public static void main(String[] args) throws InterruptedException, IOException {
if(args.length==0 || !args[args.length-1].equals("terminal")) {
String[] command;
if(System.getProperty("os.name").toLowerCase().contains("win")) {
command = new String[]{"cmd", "/c", "start \"title \\\""+TITLE+"\\\" & java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
} else {
command =new String[]{"sh", "-c", "gnome-terminal -t \""+TITLE+"\" -x sh -c \"java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
}
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
} catch(Throwable t){
t.printStackTrace();
}
} else {
//THERE IS YOUR CONSOLE PROGRAM:
System.out.println("Hey! What's your name?");
String read = new BufferedReader(new InputStreamReader(System.in)).readLine();
System.out.println("Hey, "+read+"!");
Thread.sleep(10000);
}
}
You can run it with double clicking on .jar file. Don't forget about MANIFEST.MF! :) (working on linux, also!)
Example (I only double clicked on jar file):
The way intended by Java is that you call java -jar XXXX.jar on the jars you need. Drawback is that you can't specify a classpath so all classes should be there.
A cooler way to package an application is by using Java WebStart. With that the user installs the application jut by clicking on a web browser. Check here http://docs.oracle.com/javase/8/docs/technotes/guides/javaws/developersguide/contents.html

Java command to show the processus

hi i want to show the jboss 7 as process information and the database sessions information in java code...
i try this code:
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
and this code:
Process p = Runtime.getRuntime().exec
("C:\\Users\\user\\Downloads\\PSTools\\pslist.exe -s 2");
and it works good but it works only on windows operating system .
so i want to a java code which work on each operating system, and not only on windows or linux ...
can u help me please?
thanks for everybody.
Finding java processes on the same host is fairly straight forward (some caveats listed later). Connecting to their JMX interfaces is also achievable. As far as tracking database sessions, you can conceptually acquire any data you want, as long as it is published through an accessible MBean.
The process requires using the Java Attach API. Here's a simple example where I will list all the JVM's running on my host, attempt to attach to them and list their heap usage.
First off, here's the imports:
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.util.List;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
The com.sun.tools.attach classes are in your JVM's tools.jar. Here's the code:
public class AttachAPIExample {
/**
* Uses the attach API to locate all JVMs accessible on this machine.
* #param args None
*/
public static void main(String[] args) {
// Get my PID
final String MYPID = ManagementFactory.getRuntimeMXBean().getName().split("#")[0];
log("Scanning for JVMs...");
// List all the Virtual Machine Descriptors
List<VirtualMachineDescriptor> descriptors = VirtualMachine.list();
for(VirtualMachineDescriptor vmd: descriptors) {
VirtualMachine vm = null;
// Do this in a catch block in case we run into a JVM that is not the same "bit" as we are
try {
vm = vmd.provider().attachVirtualMachine(vmd.id());
String display = vmd.displayName().trim().isEmpty() ? "Unknown" : vmd.displayName();
log("JVM%sPID: %s Display: %s", vmd.id().equals(MYPID) ? " (Me) " : " ", vmd.id(), display);
String connectorAddress = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress", null);
if(connectorAddress!=null) {
log("\tConnector Found Installed at [%s]", connectorAddress);
} else {
String javaHome = vm.getSystemProperties().getProperty("java.home");
File agentJarFile = new File(javaHome + File.separator + "lib" + File.separator + "management-agent.jar");
if(agentJarFile.exists()) {
log("I think we can find this JVM's management agent here: [%s]", agentJarFile.toString());
vm.loadAgent(agentJarFile.getAbsolutePath());
connectorAddress = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress", null);
log("\tConnector Installed at [%s]", connectorAddress);
} else {
log("Cannot find the agent jar for JVM [%s] at [%s]", vmd.id(), javaHome);
}
}
// Now lets try and connect and read some MBean values
if(connectorAddress!=null) {
log("Attaching to JVM [%s]...", vmd.id());
JMXServiceURL jmxUrl = new JMXServiceURL(connectorAddress);
JMXConnector connector = null;
try {
connector = JMXConnectorFactory.connect(jmxUrl);
MBeanServerConnection conn = connector.getMBeanServerConnection();
MemoryUsage heap = MemoryUsage.from((CompositeData)conn.getAttribute(new ObjectName(ManagementFactory.MEMORY_MXBEAN_NAME), "HeapMemoryUsage"));
log("Heap Usage: %s", heap);
} finally {
if(connector!=null) {
try { connector.close(); } catch (Exception ex) {/* No Op */}
}
}
}
} catch (Exception ex) {
/* No Op */
} finally {
if(vm!=null) try { vm.detach(); } catch (Exception ex) {/* No Op */}
log("======================================");
}
}
}
public static void log(String fmt, Object...args) {
System.out.println(String.format(fmt, args));
}
}
And here's some sample output:
Scanning for JVMs...
JVM PID: 27928 Display: sun.tools.jconsole.JConsole
Connector Found Installed at [service:jmx:rmi://127.0.0.1/stub/rO0ABXNyAC5qYXZheC5tYW5hZ2VtZW50LnJlbW90ZS5ybWkuUk1JU2VydmVySW1wbF9TdHViAAAAAAAAAAICAAB4cgAaamF2YS5ybWkuc2VydmVyLlJlbW90ZVN0dWLp/tzJi+FlGgIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHc3AAtVbmljYXN0UmVmMgAADDEwLjEyLjExNC4zNwAA9bhcC21U1Z9PMPLlR/0AAAFAxsF5moACAHg=]
Attaching to JVM [27928]...
Heap Usage: init = 8388608(8192K) used = 40242696(39299K) committed = 44236800(43200K) max = 5726666752(5592448K)
======================================
JVM PID: 25028 Display: org.jboss.Main -c ecseu -b 0.0.0.0
I think we can find this JVM's management agent here: [c:\java\jdk1.6.0_30\jre\lib\management-agent.jar]
Connector Installed at [service:jmx:rmi://127.0.0.1/stub/rO0ABXNyAC5qYXZheC5tYW5hZ2VtZW50LnJlbW90ZS5ybWkuUk1JU2VydmVySW1wbF9TdHViAAAAAAAAAAICAAB4cgAaamF2YS5ybWkuc2VydmVyLlJlbW90ZVN0dWLp/tzJi+FlGgIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHc4AAtVbmljYXN0UmVmMgAADVBQLVdLLU5XSEktMDEAAPjJTzYbxtjrUKazaPTEAAABQMuKX+6ABAB4]
Attaching to JVM [25028]...
Heap Usage: init = 1073741824(1048576K) used = 173876432(169801K) committed = 982581248(959552K) max = 982581248(959552K)
======================================
Caveats
JMVs can only attach to like bit JVMs (i.e. 32bit to 32bit, 64bit to 64bit)
The OS user launching the attach must have the OS authorization to access other processed. So same user, no problem. Other user... you should be root.
The attach api has mixed results when used across different JVM vendor implementations. ie. if it's Sun/Oracle/OpenJDK, you're probably good. If it's those, and you're trying to connect to an IBM JVM (or vice-versa) then I have no idea what will happen, although JRockit seems to be fairly friendly in this regard.
I don't know all the caveats.

Categories

Resources