从Java运行远程powershell执行时的奇怪行为
我有一个带有WSUS的Windows服务器,我正在尝试激活该计算机上的一些powershell脚本
首先,当我试图通过powershell管理shell激活它时,脚本可以工作。 脚本如下所示:
Enable-PSRemoting
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force
$secpasswd = ConvertTo-SecureString "p@`$`$w0rd" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("1.1.2.3\administrator", $secpasswd)
$s = New-PSSession -ComputerName 1.1.2.3 -Credential $creds
Invoke-Command -Session $s -Scriptblock {Get-Hotfix}
我通过Java使用了两种不同的方法:
public static void run2() throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = new ProcessBuilder()
.inheritIO()
.command("powershell", "invoke-command",
"-Computer", "1.1.2.3",
"-Scriptblock" ,"{&C:\\install-patch-ocomputer.ps1}").start();
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
proc.getOutputStream().close();
}
public static void run6() throws IOException {
Runtime runtime = Runtime.getRuntime();
BufferedReader reader = null;
Process proc = runtime.exec("powershell Invoke-Command -Computer 1.1.2.3 -Scriptblock {&C:\\install-patch-computer.ps1}");
try {
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e){
e.printStackTrace();
} finally {
reader.close();
proc.getOutputStream().close();
}
}
当我运行run2方法时,我得到:
[1.1.2.3] Connecting to remote server 1.1.2.3 failed with the following error message : The WinRM client
cannot process the request. Default authentication may be used with an IP address under the following conditions: the
transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use
winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more
information on how to set TrustedHosts run the following command: winrm help config. For more information, see the
运行run6时: 没有错误,但脚本也没有输出
请帮忙
共 (0) 个答案