Search code examples
javapowershellremote-server

Java - Remotely Connect to a Server using PowerShell and bypass the password prompt


I need help connecting to a remote server using PowerShell in JAVA. I want the connection to be done in the background, without having a prompt for the password and navigate to the desired location on the server (C:\Events\rootdir\), where I will upload a directory from my local machine.

Currently, I am using the following query:

 String command = "powershell.exe Invoke-Command -Credential myusername -ComputerName 192.x.x.x -FilePath C:\\Events\\rootdir\\
 Process powerShellProcess = Runtime.getRuntime().exec(command);
 powerShellProcess.getOutputStream().close();

However, by doing this I am getting a prompt for the password:

enter image description here

What do I need to do to include the password call in the command string, so that I connect directly to C:\Events\rootdir\, bypassing this password prompt?


Solution

  • You need to create a credential which has your username and password first. This will be a pain by just using exec. Use this library: https://github.com/profesorfalken/jPowerShell where you can start a PowerShell session and execute multiple commands.

    Or build a .ps1 and execute that.

    To create a credential object:

    $Username = 'labuser'
    $Password = 'labuser'
    $pass = ConvertTo-SecureString -AsPlainText $Password -Force
    $Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
    

    Then you can use $Cred to pass as parameter to the -Credential switch.