PowerShell批量配置VM端点

我们可以通过PowerShell脚本批量添加VM端点。请您参考以下方案。

准备工作 – PowerShell连接China Azure

 

1. 从官网下载页面,下载并安装Windows Azure PowerShell: http://www.windowsazure.cn/zh-cn/downloads/#cmd-line-tools

2. 安装完毕后以管理员身份运行,右键点击PowerShell图标然后选择以管理员身份运行;

3. 执行命令Get-AzurePublishSettingsFile -Environment "AzureChinaCloud",通过打开的页面下载您的Windows Azure Subscription的发布配置文件;

clip_image001

4. 在PowerShell中执行Import-AzurePublishSettingsFile “发布配置文件本地存放路径”;

clip_image002

方案一:批量添加自定义的端点

备注:该例子针对一个虚拟机,添加了三个端口:

端口名称

协议

公用端口

私有端口

MyPort1

tcp

5001

5001

MyPort2

tcp

5002

5002

MyPort3

udp

5003

5003

该例子中,云服务名称与虚拟机名称均为:JohnsonLinux。如果需要添加更多的端口,那么可以按照相应格式,将端口配置添加到$newVmEndpoints。格式为:(“端口名称”,”协议”,”公用端口”,”私有端口”)

$serviceName = "JohnsonLinux"
$name = "JohnsonLinux"

$newVmEndpoints = ("MyPort1","tcp",5001,5001) ,("MyPort2","tcp",5002,5002) ,("MyPort3","udp",5003,5003)

$myVm = Get-AzureVM -ServiceName $serviceName -Name $name

foreach ($endpointConfig in $newVmEndpoints)
{
$myVm | Add-AzureEndpoint -Name $endpointConfig[0] -Protocol $endpointConfig[1] -PublicPort $endpointConfig[2] -LocalPort $endpointConfig[3]
}

$myVm | Update-AzureVM

方案二:批量添加某一范围的端点

 

下面是脚本中的一些参数说明,请您相应的替换。

$serviceName – VM所属的云服务名称

$name – VM名称

$portFrom – 起始端口号

$portTo – 终止端口号

$protocal – 协议名称

下面的例子中:

1. 我们添加了1-150号TCP端点,共150个。

2. 公共端口和私有端口的值一致。

3. 端点的名称的格式为:协议名称+端口号。

4. 如果已经添加了某一个端口,则该脚本会略过该端口。

5. 同时,我们测试的过程中发现,目前我们最多只能开放150个端口。

$serviceName = "JohnsonLinux"
$name = "JohnsonLinux"
$protocol = "tcp"
$portFrom = 1
$portTo = 150

$myVm = Get-AzureVM -ServiceName $serviceName -Name $name 

$existingPublicPorts = New-Object System.Collections.ArrayList
$existingLocalPorts = New-Object System.Collections.ArrayList


foreach($endpoint in $myVm | Get-AzureEndpoint)
{
    if($protocal.Equals($endpoint.Protocol))
    {
        $existingPublicPorts.Add($endpoint.Port)
        $existingLocalPorts.Add($endpoint.LocalPort)
    }
}

for($index = $portFrom; $index -le $portTo; $index++)
{
    if(!$existingPublicPorts.Contains($index) -and !$existingLocalPorts.Contains($index))
    {
        $portName = $protocol + $index
        $myVm | Add-AzureEndpoint -Name $portName -Protocol $protocol -PublicPort $index -LocalPort $index
    }

}

$myVm | Update-AzureVM

 

下面是运行该脚本以后的部分结果截图:

clip_image003

 

批量删除VM下的所有端点:

$serviceName = "JohnsonLinux"
$name = "JohnsonLinux"

$myVm = Get-AzureVM -ServiceName $serviceName -Name $name 

foreach($endpoint in $myVm | Get-AzureEndpoint)
{
    $myVm | Remove-AzureEndpoint -Name $endpoint.Name
}

$myVm | Update-AzureVM
posted @ 2014-07-28 21:34  Jonathan.Lim  阅读(482)  评论(0编辑  收藏  举报