Java - 使用 PowerShell 远程连接到服务器并绕过密码提示

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

我需要帮助在 JAVA 中使用 PowerShell 连接到远程服务器。我希望连接在后台完成,无需提示输入密码并导航到服务器上的所需位置 (C:\Events\rootdir\),我将从本地计算机上传目录到该位置。

目前,我正在使用以下查询:

 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();

但是,这样做会提示我输入密码:

我需要做什么才能在命令字符串中包含密码调用,以便我直接连接到 C:\Events\rootdir\,绕过此密码提示?

您需要先创建一个包含您的用户名和密码的凭据。仅使用 exec 会很痛苦。使用此库:https://github.com/profesorfalken/jPowerShell 您可以在其中启动 PowerShell 会话并执行多个命令。

或者构建一个 .ps1 并执行它。

创建凭证对象:

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

然后你可以使用$Cred作为参数传递给-Credential开关。

这是工作代码:

public class PowerShellSession {
    private static String subModule = "PowerShellSession";
    String targetIpAddress;
    String username;
    String password;

    public static Object connectPShellLock = new Object();

    public PowerShellSession() {}


    public void exec(String cmd, String credentials)  { 

        String ex = credentials +" Invoke-Command -ScriptBlock {" + cmd + "} -ComputerName " + targetIpAddress +" -Credential $mycred";

        String[] args = new String[] { "powershell", ex};
        try {
            execRemote(args);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        String command = "Exit-PSSession";
        String[] args = new String[] { "powershell", command};
        try {
            execRemote(args);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String getCredentials(String domain, String userName,
            String password) throws IOException {
        String creds = "$Username = '"+userName+"';$PlainPassword ='" + password
                + "'; $SecurePassword = ConvertTo-SecureString -AsPlainText $PlainPassword -Force;"
                + "$mycred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword;";
        //creds += "$session = New-PSSession -ComputerName " + domain + " -Credential $mycred;";

        String[] args = new String[] { "powershell", creds};
        execRemote(args);
        return creds;
    }

    private void execRemote(String[] arguments) throws IOException {
        ProcessBuilder builder = new ProcessBuilder(arguments);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        doProcessIO(process);
    }

    // Do the IO for a passed process
    private void doProcessIO(Process p) throws IOException {
        p.getOutputStream().close();
        String line;
        System.out.println("Output:");
        BufferedReader stdout = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        while ((line = stdout.readLine()) != null) {
            System.out.println(line);
        }
        stdout.close();
        System.out.println("Error:");
        BufferedReader stderr = new BufferedReader(new InputStreamReader(
                p.getErrorStream()));
        while ((line = stderr.readLine()) != null) {
            System.out.println(line);
        }
        stderr.close();
        System.out.println("Done");
    }

    public static void main(String[] args) throws IOException {
        PropertiesFileReader propReader = new PropertiesFileReader(System.getProperty("user.dir")+"/cred.properties");

        String user = propReader.getPropertyData("user");
        String pass = propReader.getPropertyData("pass");
        String ip_add = propReader.getPropertyData("ip");

        PowerShellSession psSession = new PowerShellSession();
        String credentials = psSession.getCredentials(ip_add, user, pass);
        psSession.targetIpAddress = ip_add;//;



        String cmdd = propReader.getPropertyData("command");//"Get-Culture";
        if(!credentials.equals("")) {


            psSession.exec(cmdd, credentials);

            System.out.println("Finished PowerShell remote session.");

        }
        psSession.close();
    }    
}