如何登录远程服务器?

时间:2016-02-27 16:09:54

标签: powershell vbscript

我目前有一个VBScript,它读取服务器列表,并尝试验证特定用户标识的密码。 userid在本地服务器上。我正在检查密码未设置为默认值(我想确保将其更改为其他内容)。

“服务器列表”可以是IP地址,主机名(如Rocky)或完全限定的DNS名称(如rocky.bigcompany.com)的混合体。服务器是物理和虚拟设备的混合体,可能存在也可能不存在于域中。

我编写的现有VBScript处理所有这些,并且工作正常。我试图在Powershell中重写这个相同的程序,但它无法正常工作。

这是我在VBScript中执行的功能,它可以实现我想要的功能:

Function LoginToServer(Computer, username, password)
    'this function will log into a server

    On Error Resume next

    Set locator = CreateObject("WbemScripting.SWbemLocator")
    Set wmi = locator.ConnectServer(computer, "root\cimv2", username, password)

    'check the error code and see if we logged in successfully
    LoginRC = Err.Number

    If LoginRC <> 0 Then
        msg = "Could not log into server: " & CStr(computer) & " With ID: " & CStr(username)
        lfo.lmsg "B", "WARN", msg
    Else
        msg = "Server: " & CStr(computer) & " Logged in successfully as: " & CStr(username)
        lfo.lmsg "B", "INFO", msg
    End If

    wmi.Security_.ImpersonationLevel = 3

    'return the code back to calleer
    LoginToServer = LoginRC
End Function

...这就是我在PowerShell中尝试做的事情:

Param($ComputerName = "LocalHost")

$ErrorActionPreference = "Stop"

# Actual Code starts here
Write-Host "Attempting to ping server: $ComputerName"
$IPResult = Test-Connection -ComputerName $ComputerName -Quiet

if ($IPResult -eq "TRUE") {
    Write-Host "Ping OK - now attempting to log in"

    try {
        $ID = "userid"
        $PSW = "password"

        $password = ConvertTo-SecureString $PSW -AsPlainText -Force
        $cred = New-Object System.Management.Automation.PSCredential ($ID, $password)
        $sesh = New-PSSession -ComputerName $ComputerName -Credential $cred
    } catch {
        Write-Host "Error caught"
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName
    } finally {
        $Time = Get-Date
        "$Time Computer: $ComputerName ERROR: $ErrorMessage ITEM: $FailedItem" |
            Out-File c:\temp\TestCredScript.log -Append
    }
} else {
    Write-Host "Could not ping server"
}

如何使用PowerShell使用ID和密码登录这些远程计算机?

1 个答案:

答案 0 :(得分:2)

您的两个代码示例执行不同的操作。 VBScript代码通过WMI连接,而PowerShell代码尝试建立PowerShell会话。对于后者,您需要启用PowerShell Remoting,这可能是您没有的。

虽然您可能想要启用PSRemoting,但您也可以使用PowerShell中的WMI。 Get-WmiObject cmdlet允许您提供凭据和模拟级别,因此您不需要首先建立连接,就像您需要使用VBScript一样(如果您想使用显式凭据)。

查询远程计算机上的Win32_Process类的示例:

$computer = '...'
$username = 'userid'
$password = 'password'

$pw   = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $pw)

Get-WmiObject -Computer $computer -Namespace 'root\cimv2' -Class Win32_Process -Impersonation 3 -Credential $cred

有关详细信息,请参阅here