最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Java ProcessBuilder execute PowerShell Script as Admin - Stack Overflow

programmeradmin8浏览0评论

I have a Java application which is started with non admin rights. From my Java application I want to start different PowerShell scripts. The PowerShell scrips have input and output parameter. Inside the scripts PSRemoting commands are executed in order to control other Windows PCs. I need to start the PowerShell scripts from Java as admin. In my Java application the admin user and admin password is known.

Starting the PowerShell script, passing the arguments and returning the return values, does work so far. But I have not managed to start the script as admin.

      List<String> cmd = new ArrayList<>();
      cmd.add("powershell.exe");
      cmd.add("-ExecutionPolicy");
      cmd.add("Bypass");
      cmd.add("-File");
      cmd.add(tempScriptPath.toString());

      // Add the arguments for the PowerShell file
      Iterator<Map.Entry<String, JsonNode>> fields = jsonArgs.fields();
      while (fields.hasNext()) {
        Map.Entry<String, JsonNode> field = fields.next();
        String key = field.getKey();
        String value = field.getValue().asText(); // Get value as text

        // Add the key and value to the list
        cmd.add("-" + key);
        cmd.add(value);
      }

      ProcessBuilder pb = new ProcessBuilder(cmd);
      pb.redirectErrorStream(true); // Combine stdout and stderr

      // Start the process
      Process process = pb.start();

This is a dummy PowerShell script:

param (
    [string]$ip
)
Write-Output "PS INFO: Check if ps remoting is active"

$hostname = Invoke-Command -ComputerName 127.0.0.1 -ScriptBlock { hostname }

Write-Output "PS INFO: Hostname is $hostname"

$result = @{
    PsErrorCode = 0
    Hostname = $hostname
}

$result | ConvertTo-Json -Depth 10

I guess I have to add the runAs option and the user and password to the cmd but until now I have not managed it.

Maybe someone does know how to start the script as admin.

Update: I fot to mention that the pc has to users. A standard user and an admin user. The java application is started by the standard user. For executing the power shell commands I need elevated privileges which are only available by the admin user.

I have a Java application which is started with non admin rights. From my Java application I want to start different PowerShell scripts. The PowerShell scrips have input and output parameter. Inside the scripts PSRemoting commands are executed in order to control other Windows PCs. I need to start the PowerShell scripts from Java as admin. In my Java application the admin user and admin password is known.

Starting the PowerShell script, passing the arguments and returning the return values, does work so far. But I have not managed to start the script as admin.

      List<String> cmd = new ArrayList<>();
      cmd.add("powershell.exe");
      cmd.add("-ExecutionPolicy");
      cmd.add("Bypass");
      cmd.add("-File");
      cmd.add(tempScriptPath.toString());

      // Add the arguments for the PowerShell file
      Iterator<Map.Entry<String, JsonNode>> fields = jsonArgs.fields();
      while (fields.hasNext()) {
        Map.Entry<String, JsonNode> field = fields.next();
        String key = field.getKey();
        String value = field.getValue().asText(); // Get value as text

        // Add the key and value to the list
        cmd.add("-" + key);
        cmd.add(value);
      }

      ProcessBuilder pb = new ProcessBuilder(cmd);
      pb.redirectErrorStream(true); // Combine stdout and stderr

      // Start the process
      Process process = pb.start();

This is a dummy PowerShell script:

param (
    [string]$ip
)
Write-Output "PS INFO: Check if ps remoting is active"

$hostname = Invoke-Command -ComputerName 127.0.0.1 -ScriptBlock { hostname }

Write-Output "PS INFO: Hostname is $hostname"

$result = @{
    PsErrorCode = 0
    Hostname = $hostname
}

$result | ConvertTo-Json -Depth 10

I guess I have to add the runAs option and the user and password to the cmd but until now I have not managed it.

Maybe someone does know how to start the script as admin.

Update: I fot to mention that the pc has to users. A standard user and an admin user. The java application is started by the standard user. For executing the power shell commands I need elevated privileges which are only available by the admin user.

Share Improve this question edited Jan 26 at 8:36 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Dec 5, 2024 at 15:57 cProgrammer1992cProgrammer1992 614 bronze badges 2
  • 1 This is the command I use to launch another Java app in elevated mode via powershell: "powershell.exe Start-Process -verb RunAs java.exe -ArgumentList " + argList + " -Wait", so I guess it's the tag RunAs that you need to add. – JayC667 Commented Dec 5, 2024 at 16:08
  • learn.microsoft/en-us/powershell/module/… – Slaw Commented Dec 6, 2024 at 9:38
Add a comment  | 

1 Answer 1

Reset to default 0

I have found a solution that works for me.

My java application runs under user A which has no admin rights. From java I start a new power shell process. I use -Credentials argument to run the power shell script as user B which has admin rights.

In the power shell script I check first if the script is executed with elevated privileges. Since this is never the case I restart the script with elevated privileges (-Verb "runas"). Then the script runs under user B with elevated privileges.

These are my problems and how i solved them. If someone knows better solutions please let me know.

Starting a powershell script from java (running under user A) with elevated privileges is not possible -> Start a power shell with normal privileges but as user B and then restart the script with elevated privileges.

Returning values from a powershell script with elevated privileges to its caller (power shell script with non elevated privileges) is not possible. stdout is not avaiable -> I used a logfile to geht the return values.

Starting a power shell script with elevated privileges is only possible when the user accepts the UAC concent prompt. Bypassing the UAC concent prompt is not possible. -> I accept this. So far I have not found a solution for this. Changing the notification level is no option for me.

# This example can be used to execute powershell commands with elevated privileges
param (
    [string]$logFile, # The logfile is used for logging and returning to the calling process
    [string]$ip
)

# Get the current user
$currentActiveUser = whoami
# Get the complete path to this power shell file
$currentScriptPath = $MyInvocation.MyCommand.Definition

# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator


# Check to see if we are currently running "as Administrator" = elevated privileges
if ($myWindowsPrincipal.IsInRole($adminRole)) {
  Write-Output "PS INFO: Script $currentScriptPath is called by $currentActiveUser in elevated mode" >> $logFile

  # This is a PS remoting command to the the hostname of a remote pc
  # TODO: Add here the credentials of the remote pc
  $hostname = Invoke-Command -ComputerName $ip -ScriptBlock { hostname }
  $hostname = $hostname | Out-String  # Convert object to string
  $hostname = $hostname.Trim()        # Remove \r\n

  Write-Output "PS INFO: Hostname is $hostname" >> $logFile

  # Create a result hash table
  $result = @{
    PsErrorCode = 0
    Hostname = $hostname
  }

  # Write the result to the log file
  $result | ConvertTo-Json -Depth 10 | Out-File -FilePath $logFile -Append
  exit
  }
else
  {
  # This is the entry point because the initial time the script is executed with non elevated privileges
  Write-Output "PS INFO: Script $currentScriptPath is called by $currentActiveUser not in elevated mode" >> $logFile

  # Create a new process object that starts PowerShell
  $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

  # Specify the current script path and name as a parameter
  $newProcess.Arguments = "$($myInvocation.MyCommand.Definition) -logFile '$logFile' -ip '$ip'"

  # Indicate that the process should be elevated
  $newProcess.Verb = "runas";

  # Start the process and wait for it to finish
  Start-Process -FilePath $newProcess.FileName -ArgumentList $newProcess.Arguments -Verb $newProcess.Verb -PassThru -Wait

  Write-Output "PS INFO: Exit non elevated mode" >> $logFile
  # Exit from the current, unelevated, process
  exit
  }
发布评论

评论列表(0)

  1. 暂无评论