我需要获取具有不受限制的 SSH 的虚拟机列表。
我一直在浏览适用于 Python 的 Azure SDK 文档。计算模块中有一个 SshConfiguration 类,但它只有关于公钥的信息。批处理 AI 模块中有一个不同的 SshConfiguration 类,可用于获取允许连接的公共 IP 列表,这就是我想要的。但我没有使用批量AI。
如何以编程方式获取所需的信息?
您必须为此绕道而行,因为计算模块中没有直接提供此信息的直接方法。
使用计算和网络模块中的方法,我编写了以下脚本,以列出订阅中具有不受限制的 SSH 访问权限的所有 VM,即列出允许通过端口 22 从 Internet 访问 VM 的所有入站规则。
# Imports
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute import ComputeManagementClient
# Set subscription ID
SUBSCRIPTION_ID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
def get_credentials():
credentials = ServicePrincipalCredentials(
client_id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
secret='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
tenant='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
)
return credentials
# Get credentials
credentials = get_credentials()
# Initialize management client
network_client = NetworkManagementClient(
credentials,
SUBSCRIPTION_ID
)
# Initialize management client
compute_client = ComputeManagementClient(
credentials,
SUBSCRIPTION_ID
)
def get_unrestricted_ssh_rules():
print('nListing all VMs in Subscription with unrestricted SSH access:')
for vm in compute_client.virtual_machines.list_all():
# Get the VM Resource Group name
vm_rg_name = vm.id.split('/')[4]
# Loop through NICs
for nic in vm.network_profile.network_interfaces:
# Get the NIC name and Resource Group
nic_name = nic.id.split('/')[-1]
nic_rg_name = nic.id.split('/')[4]
# Get the associated NSG and its Resource Group
nsg = network_client.network_interfaces.get(
nic_rg_name, nic_name).network_security_group
nsg_name = nsg.id.split('/')[-1]
nsg_rg_name = nsg.id.split('/')[4]
# Get the associated Security Rules
for rule in network_client.security_rules.list(nsg_rg_name, nsg_name):
# Conditions:
# Rule direction: Inbound
# Rule Access: Allow
# Port: 22
# Source Address Prefix: 'Internet' or '*'
unrestricted = (rule.direction == 'Inbound' and rule.access == 'Allow' and ('22' in (rule.destination_port_ranges, rule.destination_port_range)
or rule.destination_port_range == '*') and (rule.source_address_prefix == '*' or rule.source_address_prefix == 'Internet'))
# Print all the Inbound rules allowing access to the VM over port 22 from the Internet
if unrestricted:
print "nVM Name: ", vm.name, "nResource Group Name: ", vm_rg_name, "nRule Name: ", rule.name
# List all VMs in the Subscription with unrestricted SSH access
get_unrestricted_ssh_rules()
如果 NSG 与子网而不是 NIC 关联,也可以对子网重复相同的操作。
引用:
- azure-mgmt-compute
- 虚拟机操作类
- azure-mgmt-network
- 安全规则操作类
- 网络接口操作类
希望这有帮助!