简体   繁体   中英

How to read windows registry data on remote machine using java

I am trying to read some user-defined windows registry data on remote machine using java.
I am able to read my local machine registry data using jna and even update it back.
Can anybody help on how to read/write data to remote machine using java.

WinAPI has a function named RegConnectRegistry which may be what you're looking for:

Establishes a connection to a predefined registry key on another computer

LONG WINAPI RegConnectRegistry(
    _In_opt_ LPCTSTR lpMachineName,
    _In_     HKEY    hKey,
    _Out_    PHKEY   phkResult
);

In Java , the function may look like the following, granted that you've added the jna-platform library as a dependency which provides ready-made API types and functions:

import com.sun.jna.Native;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.platform.win32.WinReg.HKEY;
import com.sun.jna.platform.win32.WinReg.HKEYByReference;
import com.sun.jna.platform.win32.WinReg.HKEY_LOCAL_MACHINE;
import com.sun.jna.win32.W32APIOptions;

interface MyAdvapi32 extends StdCallLibrary {
    MyAdvapi32 INSTANCE = (MyAdvapi32) Native.loadLibrary(
        "advapi32",
        MyAdvapi32.class,
        W32APIOptions.DEFAULT_OPTIONS
    );

    int RegConnectRegistry(String machineName, HKEY hKey, HKEYByReference result);
    int RegCloseKey(HKEY key);
}

You might notice the W32APIOptions.DEFAULT_OPTIONS used in the library load. The Windows API provides two different implementations for functions which use strings: one for Unicode strings and one for ANSI strings. While the function is named RegConnectRegistry , the implementations which JNA finds in the DLL are named RegConnectRegistryW (Unicode) and RegConnectRegistryA (ANSI). However, these probably are not your concern since you're not writing native code.

Passing the default options in lets JNA use the correct function names, avoiding a confusing-at-best UnsatisfiedLinkError .

Usage might look like this:

HKEYByReference result = new HKEYByReference();
int returnCode = MyAdvapi32.INSTANCE.RegConnectRegistry(
    "\\\\server-name",
    HKEY_LOCAL_MACHINE,
    result
);

if (returnCode != 0) {
    throw new Win32Exception(returnCode);
}

HKEY key = result.getValue();

// ... use the key, then once done with it ...

MyAdvapi32.INSTANCE.RegCloseKey(key);

By the way, jna-platform library does provide mappings for the Advapi32 library, but RegConnectRegistry seems to be missing. Ideally, you'd probably create a pull request and add it in, but YMMV as to how quickly they roll out a new release with the addition.

EDIT: I've created a pull request to JNA to get this function added in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM