【问题标题】:PowerShell Script - Get account information from an outside filePowerShell 脚本 - 从外部文件获取帐户信息
【发布时间】:2015-06-29 02:51:24
【问题描述】:

我目前有一个脚本,成功使用这种方法远程连接到服务器,并使用 Invoke-Command 运行一些任务:

$c = Get-Credential 
$computername = "server.fqdn"
    $session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $c

执行此操作时,系统会提示我输入要运行的帐户的用户名和密码。我输入它,它就可以工作。

我希望能够做的不是在脚本执行时提示输入凭据,而是希望它自动使用我存储在某个文本文件中的凭据(或至少使用密码这种方式)。这是因为我需要安排脚本从服务器外部运行。

还有另一个thread 似乎与我想要做的非常接近。使用文本文件和转换安全字符串。我不太明白如何使用 New-PSSession 使用此方法。也许还有另一种方式。

到目前为止,我有以下代码。

  $username = "domain\username"
    $password  = cat C:\scripts\password.txt | convertto-securestring
    $c = new-object -typename System.Management.Automation.PSCredential `
             -argumentlist $username, $password 
    $computername = "server.fqdn"
    $session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $c 

我仍然提示输入用户名和密码并收到错误:

convertto-securestring : Input string was not in a correct format

我的密码在文本文件中。它就像密码123。在我尝试使用文本文件之前,密码有效。

【问题讨论】:

    标签: powershell scripting credentials windows-server


    【解决方案1】:

    我不会更正您的代码,但这是我用来在某些服务器上存储密码的方式。代码第一次运行时,它要求输入密码,然后将其加密存储在文件中,下一次从文件中读取密码。 小心密码可以从文件内容中找到,我们无法读取,但可能存在安全问题。

    $passwordFile = "C:\scripts\password.txt"
    $username = "domain\username"
    
    # First time create password file
    if (! (Test-Path $passwordFile))
    {
      Read-Host -AsSecureString | convertfrom-securestring | out-file $passwordFile
    }
    
    $password = Get-Content $passwordFile | convertto-securestring
    $credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
    

    【讨论】:

    • 多亏了你,我走得更远了。使用 New-PSSession 时仍然出现一个错误。你能看出我哪里出错了吗? $username = "domain\username" $passcontent = Get-Content "c:\scripts\password.txt" $password = ConvertTo-SecureString -String $passcontent -AsPlainText -Force $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password $computername = "server.fqdn" $session = New-PSSession -ComputerName $computername -Authentication CredSSP -Credential $cred
    • New-PSSession : [server.fqdn] 连接到远程服务器 server.fqdn 失败并显示以下错误消息:参数不正确。有关详细信息,请参阅 about_Remote_Troubleshooting 帮助主题。在 line:1 char:12 $session = New-PSSession -ComputerName $computername -Authentication CredSSP -Cr ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~ + CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException + FullyQualifiedErrorId : 87,PSSessionOpenFailed`
    • 您创建密码文件的方式出错了,请查看并测试我的代码。
    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多