【发布时间】:2023-04-01 23:04:01
【问题描述】:
我一直在尝试让pywinrm 模块远程运行New-Mailbox Powershell cmdlet。这是我目前所拥有的:
import winrm
ps_text = "$pass = ConvertTo-SecureString -String '%s' -AsPlainText -Force; \
Add-PSSnapIn Microsoft.Exchange.Management.Powershell.E2010; \
New-Mailbox -UserPrincipalName '%s@contoso.lan' \
-Alias '%s' -Name '%s' -Password $pass \
-Firstname '%s' \
-Lastname '%s' \
-DisplayName '%s' \
-PrimarySmtpAddress '%s'" % \
('password123',
'jfd',
'john.doe',
'John Doe',
'John',
'Doe',
'John Doe',
'john.doe@contoso.co.uk')
remote = winrm.Session('https://contoso.co.uk:5986', auth=('ps_remote', 'irrelevant'))
r = remote_session.run_cmd("powershell", ["-version", "2.0", "-c", ps_text])
这是我得到的输出:
New-Mailbox : 值不能为空。参数名称:serverSettings At 行:1 字符:147 + $pass = ConvertTo-SecureString -String 'password123' -AsPlainText -Force;添加-PSSnapIn Microsoft.Exchange.Management.Powershell.E2010;新邮箱
我认为它不喜欢 $pass 不被引用,所以我将它用单引号括起来并得到:
新邮箱:无法绑定参数“密码”。无法转换 要键入的“System.String”类型的“$pass”值 "System.Security.SecureString".At line:1 char:231 + $pass = ConvertTo-SecureString -String 'password123' -AsPlainText -Force;添加-PSSnapIn Microsoft.Exchange.Management.Powershell.E2010;新邮箱 -UserPrincipalName 'jfd@contoso.lan' -Alias 'john.doe' -Name 'John Doe' -Password -Firstname 'John' -Lastname 'Doe' -DisplayName 'John Doe' -PrimarySmtpAddress 'john.doe@contoso.co.uk' + CategoryInfo : InvalidArgument: (:) [New-Mailbox], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Exchange.Management.RecipientTasks.NewMailbox
强调我的。现在它按字面意思解释它,而不是扩展 $pass 变量。有什么办法可以正确执行吗?
一些注意事项:
- 我没有使用记录在案的
run_ps方法winrm.Session,因为它不能针对远程端正确版本的 Powershell 运行(此处需要版本 2.0,因为这是 Exchange 管理管理单元所需要的) . - 我已尝试使用软件包页面上详述的 pywinrm 的低级 API,但效果不佳。
- 如果我在 Powershell 的第一行之后插入
$pass;,标准输出实际上会返回System.Security.SecureString,这更奇怪的是它会在第一个示例中抱怨 null 参数。 - 我尝试过用三重引号括起来,并交换引号样式。没有骰子。
- 我尝试了各种其他方法,包括对本地 Powershell 进行子进程调用以运行
New-PSSession以导入远程会话,但这实际上无法访问我需要的 cmdlet。我还尝试使用Invoke-Command远程运行脚本块,但即使据说成功导入了管理单元,它也不会运行实际的 cmdlet。 - 最好使用纯 Python 解决方案(因此使用 pywinrm),但现阶段我对任何事情都持开放态度。远程运行
New-Mailbox的例子很少,或者我的Google-fu 在这种情况下很弱。
【问题讨论】:
标签: python powershell automation powershell-remoting exchange-server-2010