我正在尝试编写一个Python脚本来自动执行Powershell的Get-Credential方法。这是我写的东西:

import subprocess
COMMAND_LINE = 'powershell'
powershell = subprocess.Popen(COMMAND_LINE, shell=True,
                                   stdin=subprocess.PIPE,
                                   stderr=subprocess.STDOUT,
                                   stdout=subprocess.PIPE)
output = powershell.stdout.readline()
print output.rstrip()
powershell.stdin.write('$cred = Get-Credential\n')
powershell.stdin.write('Administrator\n')
powershell.stdin.write('Password')
output = powershell.stdout.readline()
print output.rstrip()
out = powershell.communicate()[0]
print(out)


但是我无法通过上述密码,我遇到了以下异常: br />
由于我是python的新手,有人可以在这里帮助我吗?

#1 楼

您的python问题是命令后的\nwrite已经添加了换行符,因此您的脚本会执行以下操作:

$cred = Get-Credential # Start the command
# This line is ignored as extraneous after Get-Credential, but you can see it in your output.
Administrator # Send proprely to the User: prompt
# Sent to the Password: prompt
Password # Send to the shell input, causing the error at end of your log.


>
$password = "mypassword" | ConvertTo-SecureString -asPlainText -Force
$username = "nwtraders\administrator" 
$credential = New-ObjectSystem.Management.Automation.PSCredential($username,$password)


#2 楼

我绝不是专家,但是除了创建包含“纯文本”密码的脚本之外,还有其他选择,这显然不是很安全。

我已根据本文编写了以下代码段你是谁?或者,通过Jeff Hicks的Get-Credential Cmdlet进行滑动,现在使用它来自动化远程会话。

# Create a secure string for the password
$Username = Read-Host "Enter Username"
$Password = Read-Host "Enter Password" -AsSecureString

# Create the PSCredential object
$Credentials = New-Object System.Management.Automation.PSCredential($Username,$Password)

# Server Variable
$Server = Read-Host "Enter Server Name"

# Create Remote Session
Enter-PSSession -ComputerName $Server -Credential $Credentials


运行此代码时,您将获得以下输出:-

PS Scripts:\> .\Snippets\Enter-SecureCreds.ps1
Enter Username: ##YOUR-USERNAME#
Enter Password: *************
Enter Server Name: 192.168.1.10


输入时,密码用*混淆。
此凭据仅在打开PowerShell会话的情况下存在
。但是要小心,因为即使密码存储为
安全字符串,但如果我可以交互式访问控制台会话,我仍然可以通过调用GetNetworkCredential()来查看密码方法:


PS S:\> $Credential.GetNetworkCredential()

UserName          Password          Domain
--------          --------          ------ 
admin             P@ssw0rd          mydomain



这不一定违反安全性,除非您走开并保持会话完全开放供任何人访问。在某些情况下,您可能有一个无法使用PSCredential的旧版应用程序,并且需要将用户名和密码之类的值传递给它。请注意。

重要说明:硬编码任何
纯文本文件中的任何密码都是安全性。理想情况下,您需要为脚本用户提供一些安全的机制,以提供必要的密码。另外,如果要保留凭据
,请不要忘记保护控制台。


我希望您发现它像我一样有用。