search
HomeBackend DevelopmentPython Tutorial使用Python脚本来控制Windows Azure的简单教程

inux开发人员经常使用 Python 完成小块的工作,因为你可以编写脚本的情况很容易。它已经成为完成配置和部署等小任务的一个流行方式。Windows Azure,微软的云,也没有什么不同。通过 Python SDK 所提供的可用性,Python 成为 Windows Azure 的头等公民。让我们看看我们如何能够使用Python无需其它而只需一个Windows Azure订阅就可以用编程方式从 vmdepot 部署一个映像到 Windows Azure上。
建立一个管理证书

任何与 Windows Azure 的交互都需要两个东西:

我们假设你使用 Linux 运行这个脚本(如果不是,请和我联系,我会告诉你如何使用 Windows 来做同样的事情)。 如果没有安装OpenSSL,请从root提示使用如下命令:

yum install openssl

以下将创建一个 .pem 文件,之后可被翻译成一个 .cer 文件,并导出和上传到Windows Azure。

openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout elasta.pem -out elasta.pem

用下面命令导出 .cer:

openssl x509 -inform pem -in elasta.pem -outform der -out elasta.cer

这样你就得到它了,一个可以上传到你的 Windows Azure 订阅的管理证书。当做完这个时,你应该已经能够以编程方式使用 Windows Azure 了。

用你的微软帐户或者 Windows Azure 活动目录凭据登录到 Windows Azure。管理门户位于https://manage.windowsazure.com 。

选择设置标签:

2015416150149846.png (800×600)

从菜单中选择管理证书:

2015416150220027.png (886×169)

下方的应用工具条包含一个上传按钮:

2015416150255515.png (1561×80)

选择这个按钮,上传前面导出的 .cer 文件:

2015416150332525.png (677×480)

在“结果”面板中你应该会看到类似这样的证书入口。

2015416150413342.png (1219×49)
为了有助于解释这篇文章,我已经写了一个Python脚本,可在这里下载:

https://github.com/elastacloud/python-vmdepot-deploy


你可以阅读安装说明获知如何使用脚本。本文的目的是带你领略 Windows Azure 的 Python API 的一些能够帮你开发完全自动化部署的关键功能。

要使用 Windows Azure 中的任何服务管理功能,我们需要一个服务管理对象:
 

self.sms = ServiceManagementService(vars.subscription_id, vars.certificate_path)

这对我们接下来要做的很有用。正如你能看到的,这需要一个证书和订阅ID作为参数。
构造一个虚拟机

虚拟机映像是一个模板,我们可以用它建立虚拟机。在本例中,我们将使用一个 CentOS 映像,它是从一个由微软的全资子公司 MS Open Tech 持有的称为 vmdepot 的位置拷贝过来的。


我们可以通过列出我们的订阅中所有命名的映像来检查我们是否之前已经复制过指定的映像和注册过现存的。
 

def _image_by_name(self, name):
  # return the first one listed, which should be the most stable
  for i in self.sms.list_os_images():
   if name in i.name:
    return True
  return False

如果没有,我们可以继续我们的工作流程了。

下面演示了一个创建一个存储帐户(需要一个名称和位置)的简洁过程。因为我在伦敦,所以我会使用“北欧”数据中心(位于都柏林),但在世界各地有超过10个数据中心而且还有一堆正在建设。当存储帐户创建完,它允许最多 200 TB 的blob数据被存储,并由2512位的AES保护,可以用它来访问帐户。存储数据的逻辑单元被称为是一个容器,所以我们需要创建这样的一个容器来让我们存储我们复制的映像。
 

self._create_storage_account_if_not_exists(vars.storage_account_name, vars.deploy_location)
account_key = self._get_primary_account_key(vars.storage_account_name)
self._create_container_if_not_exists()

我们现在应该能够从远程位置复制blob。这是通过使用 Windows Azure 提供的一个被称为 copyblob 的 API 完成的。实现代码如下:
 

 self.blob_service.copy_blob(container_name=Constants.storage_container_name, blob_name=Constants.vhd_blob_name, x_ms_copy_source=Constants.centos_minimal_image)
self._wait_for_async_copy(Constants.storage_container_name, Constants.vhd_blob_name)


你可以看到,这是一个异步方法,允许从远程位置复制任何 blob。这个 API 的伟大是,你可以用它来从 Windows Azure 的内部或外部复制任何 HTTP 端点,并且使用它没有任何成本。缺点是,它没有 SLA(译者注:Service-Level Agreement的缩写,服务等级协议,是网络服务供应商和客户间的合同)。

然后 blob 就可以在你的 Windows Azure 订阅中注册为一个映像,你可以使用这个来创建多个虚拟机。

self.sms.add_os_image(label=Constants.image_name, media_link=storageimage_uri, name=Constants.image_name, os='Linux')

这个脚本将创建一个“云服务”的包含虚拟机的公共端点,然后设置一个公共端点转发到虚拟机的端口,这样你就可以通过 SSH 进入他们。脚本是这样写的,如果你每次选择相同的云服务,它将从端口22向上递增来添加另一个准备给SSH进入的开放端口来作为云服务的虚拟机。


我们正在从含有映像的 vmdepot 复制映像。通过它,我正在我的订阅中复制和注册 CentOS 迷你映像。

https://vmdepotneurope.blob.core.windows.net/linux-community-store/community-32167-508624a5-01d1-4d57-b109-df2af5b4b232-1.vhd

你可以从这个地址浏览 vmdepot:

http://vmdepot.msopentech.com/List/Index

最后,我们将使用一个非常简单的算法来确定虚拟机已经部署到云服务上,即通过查看存储账户中相关的blob,每个虚拟机都有一个虚拟硬盘(.vhd)。
 

index = -1
blob_exists = True
while blob_exists:
 index += 1
   blob_exists = self._blob_exists(Constants.storage_container_name, "elastavm" + str(index) + ".vhd")
 
vm_media_link = self._make_blob_url(vars.storage_account_name, Constants.storage_container_name, "elastavm" + str(index) + ".vhd")
 
self._create_vm_linux(vars.storage_account_name, vars.storage_account_name, "elastavm" + str(index), vm_media_link, vars.deploy_location, index, vars.username, vars.password)

结果是,我们可以为我们的云服务添加多个虚拟机。

以上都是从 Setup.py 文件完成的。你可以在下面地址的文件中看到上面所有代码:

https://github.com/elastacloud/python-vmdepot-deploy/blob/master/elastacloud/pyvms/Setup.py

根据 readme.md 中的指示启用脚本,你就可以准备开始了。

你可以在下面地址克隆 Windows Azure 的 Python SDK: :

https://github.com/WindowsAzure/azure-sdk-for-python

乐之!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),