我正在尝试连接到一个Windows EC2实例,并使用pywinrm对它运行一些命令。我正在使用以下代码创建一个会话:session = winrm.Session(ec2_instance.public_dns_name, auth=(user_name, password)),它工作得很好。
现在,当我使用上面创建的session对象运行像:session.run_ps("hostname")或session.run_cmd("hostname") ->这样的命令时,它会失败,因为WinRM端口、5985和5986的防火墙规则没有配置( AWS端的安全组打开了端口,但VM没有)。
将端口5985和5986的入站规则配置在EC2实例上后,运行任何命令都会失败,出现以下错误:Exception has occurred: InvalidCredentialsError the specified credentials were rejected by the server
我知道错误信息是误导的,因为凭证是正确的。我之所以说凭据是正确的,是因为当我从EC2实例运行以下内容时:
Set-Item -Force WSMan:\localhost\Service\auth\Basic $true
Set-Item -Force WSMan:\localhost\Service\AllowUnencrypted $true然后使用我的代码运行命令,一切都很好。
现在,我想要找到的是,通过我的python代码启用AllowUnencrypted值的方法。我已经考虑过使用Kerberos,但是我似乎需要创建一个AWS管理的Microsoft目录,这将给我的组织带来成本。
我也尝试过像这样使用NTLM:
protocol = Protocol(
endpoint=f"https://{ec2_instance.public_dns_name}:5985/wsman",
transport="ntlm",
username="Administrator",
password="Password",
server_cert_validation="ignore",
)
shell_id = protocol.open_shell()但我得到了以下错误:
HTTPSConnectionPool(host='ec2-x-x-x-x.us-west-2.compute.amazonaws.com', port=5985): Max retries exceeded with url: /wsman (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)')))任何帮助都是非常感谢的。
谢谢
发布于 2022-10-24 15:33:41
"HTTPSConnectionPool(host='ec2-x-x-x-x.us-west-2.compute.amazonaws.com',port=5985):最大重试超过url: /wsman (由SSLError(SSLError(1,'SSL: WRONG_VERSION_NUMBER错误版本号(_ssl.c:1129)‘)引起)“
从您的错误来看,端口5985是HTTP侦听器,因为HTTPS应该是端口5986。
将端点端口更改为5986,并尝试“endpoint=f”姓名}:5986/wsman“,
对不起,我还不能添加评论。
发布于 2022-10-25 23:49:43
以下是对我有效的解决方案:
步骤1:使用AWS在EC2实例上运行命令。这些命令
WMan属性Basic Authentication设置为True,将AllowUnencrypted设置为True。5985和5986创建Windows防火墙规则。Set-Item -Force WSMan:\localhost\Service\auth\Basic $true
Set-Item -Force WSMan:\localhost\Service\AllowUnencrypted $true
New-NetFirewallRule -DisplayName "Allow WinRM Ports" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 5985-5986我从这里得到帮助:如何使用Boto3在AWS实例上执行命令
预装SSM的AMI:https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-ssm-win.html
注意:只有当EC2实例具有与其相关联的IAM概要文件时,命令才能运行: ARN =
arn:aws:iam::<your_aws_account_id>:instance-profile/AmazonSSMRoleForInstancesQuickSetupName =AmazonSSMRoleForInstancesQuickSetup--一旦IAM与EC2实例相关联,就可以使用boto3 EC2client方法associate_iam_instance_profile()执行命令,这样做需要一到两分钟才能达到这个效果,并在boto3ssmclient的describe_instance_information()方法下列出。在尝试运行任何命令之前,请确保添加一个等待方法,以便在上述方法的输出中列出您的EC2实例。
步骤2:使用WinRM python库将EBS磁盘联机、初始化、分区和格式化磁盘。
注意:我本可以使用SSM运行上述命令,但是
WinRM提供了更好的输出,可以转换为JSON并用于进一步的验证。
步骤3:解密登录密码的代码:
from winrm.protocol import Protocol
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
with open(private_key_file_path, "r") as key_file:
key_text = key_file.read()
key = RSA.importKey(key_text)
cipher = PKCS1_v1_5.new(key)
password = cipher.decrypt(base64.b64decode(password_data),None).decode("utf-8")https://stackoverflow.com/questions/74102099
复制相似问题