VMWare管理——上传文件到指定datastore

本文介绍了一种使用Python将文件上传到VMware vCenter Datastore的方法。通过oslo.vmware库中的FileWriteHandle类实现文件上传功能。文章详细展示了如何连接vCenter、获取必要的会话信息,并逐步上传文件。
部署运行你感兴趣的模型镜像

有个需求,用户通过浏览器页面上传文件到datastore(我们事先有跟VCenter建立连接),似乎Vmware Vsphere WebService SDK似乎没有提供接口。挖了下oslo.vmware的代码发现有实现。我们先看下用法:

from oslo_vmware import rw_handles
import os
from oslo_vmware import api
def upload_iso_to_datastore(session,iso_path, dest_file, ds_name,dc_name,host,port=443):
    cookies = session.vim.client.options.transport.cookiejar
    with open(iso_path, 'r') as iso_file:
        write_file_handle = rw_handles.FileWriteHandle(
            host,
            port,
            dc_name,
            ds_name,
            cookies,
            dest_file,
            os.fstat(iso_file.fileno()).st_size)

        block_size = 0x10000
        data = iso_file.read(block_size)
        while len(data) > 0:
            write_file_handle.write(data)
            data = iso_file.read(block_size)
        write_file_handle.close()
session = api.VMwareAPISession(
    '192.168.3.249',      # vSphere host endpoint
    'administrator@vsphere.local', # vSphere username
    '123456$xx',      # vSphere password
    10,              # Number of retries for connection failures in tasks
    0.1              # Poll interval for async tasks (in seconds)
)

upload_iso_to_datastore(session,"/opt/test.iso","test.iso","datastore1","192.168.3.254")

很容易搞明白,跟VCenter连接连接,获取cookies,然后调用rw_handles的FileWriteHandle类实现。

我看下该类的实现:

class FileWriteHandle(FileHandle):
    """Write handle for a file in VMware server."""

    def __init__(self, host, port, data_center_name, datastore_name, cookies,
                 file_path, file_size, scheme='https', cacerts=False,
                 thumbprint=None):
        """Initializes the write handle with given parameters.

        :param host: ESX/VC server IP address or host name
        :param port: port for connection
        :param data_center_name: name of the data center in the case of a VC
                                 server
        :param datastore_name: name of the datastore where the file is stored
        :param cookies: cookies to build the vim cookie header
        :param file_path: datastore path where the file is written
        :param file_size: size of the file in bytes
        :param scheme: protocol-- http or https
        :param cacerts: CA bundle file to use for SSL verification
        :param thumbprint: expected SHA1 thumbprint of server's certificate
        :raises: VimConnectionException, ValueError
        """
        soap_url = self._get_soap_url(scheme, host, port)
        param_list = {'dcPath': data_center_name, 'dsName': datastore_name}
        self._url = '%s/folder/%s' % (soap_url, file_path)
        self._url = self._url + '?' + urlparse.urlencode(param_list)

        self._conn = self._create_write_connection('PUT',
                                                   self._url,
                                                   file_size,
                                                   cookies=cookies,
                                                   cacerts=cacerts,
                                                   ssl_thumbprint=thumbprint)
        FileHandle.__init__(self, self._conn)

    def write(self, data):
        """Write data to the file.

        :param data: data to be written
        :raises: VimConnectionException, VimException
        """
        try:
            self._file_handle.send(data)
        except requests.RequestException as excep:
            excep_msg = _("Connection error occurred while writing data to"
                          " %s.") % self._url
            LOG.exception(excep_msg)
            raise exceptions.VimConnectionException(excep_msg, excep)
        except Exception as excep:
            # TODO(vbala) We need to catch and raise specific exceptions
            # related to connection problems, invalid request and invalid
            # arguments.
            excep_msg = _("Error occurred while writing data to"
                          " %s.") % self._url
            LOG.exception(excep_msg)
            raise exceptions.VimException(excep_msg, excep)

    def close(self):
        """Get the response and close the connection."""
        LOG.debug("Closing write handle for %s.", self._url)
        try:
            self._conn.getresponse()
        except Exception:
            LOG.warning(_LW("Error occurred while reading the HTTP response."),
                        exc_info=True)
        super(FileWriteHandle, self).close()

    def __str__(self):
        return "File write handle for %s" % self._url

可以看到就是上传文件到某个url,一般形式是:

https://192.168.3.249:443/folder/{路径/文件名}?dsName={存储器ing}&dcPath={数据中心名}

是不是很简单?




您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

VMware ESXi 7.0 中上传或传输文件,主要可以通过以下几种方式实现: ### 使用 SCP 命令在 ESXi 主机之间传输文件 SCP(Secure Copy Protocol)是一种基于 SSH 的协议,用于在本地和远程主机之间安全地复制文件。在 ESXi 环境中,可以通过启用 SSH 服务,使用 SCP 命令在不同 ESXi 主机之间传输文件。具体步骤如下: 1. **启用 SSH 访问**:通过 ESXi 的直接控制台用户界面(DCUI)或 vSphere Client 启用 SSH 访问。 2. **使用 SCP 命令**:在源 ESXi 主机上执行 SCP 命令,将文件文件夹复制到目标 ESXi 主机。例如: ```bash scp /vmfs/volumes/datastore1/source_folder user@target_esxi_ip:/vmfs/volumes/datastore1/target_folder ``` 其中 `user` 是目标 ESXi 主机上的用户名,`target_esxi_ip` 是目标 ESXi 主机的 IP 地址[^1]。 ### 使用 vSphere Client 上传文件 vSphere Client 提供了一个图形界面,可以直接上传文件到 ESXi 主机上的数据存储中。具体步骤如下: 1. **连接到 vSphere Client**:打开 vSphere Client 并连接到 ESXi 主机。 2. **导航到数据存储**:在左侧导航栏中选择目标 ESXi 主机,然后点击“配置” > “存储” > “数据存储”。 3. **上传文件**:右键点击目标数据存储,选择“浏览数据存储”,然后点击“上传”按钮,选择要上传文件并开始上传过程[^2]。 ### 使用命令行工具(如 vCLI 或 PowerCLI) VMware 提供了多种命令行工具,如 vCLI 和 PowerCLI,可以用于自动化日常任务,包括文件传输。这些工具可以通过脚本编写,实现批量文件传输。 1. **安装 vCLI 或 PowerCLI**:根据操作系统下载并安装相应的工具。 2. **使用命令行工具**:使用命令行工具连接到 ESXi 主机,并执行文件传输命令。例如,在 PowerCLI 中可以使用 `Copy-VMGuestFile` 命令将文件从本地系统复制到虚拟机中。 ### 相关问题 1. 如何在 ESXi 7.0 中启用 SSH 访问? 2. 如何使用 vSphere Client 浏览和管理数据存储? 3. 如何使用 PowerCLI 进行文件传输? 4. 在 ESXi 7.0 中使用 SCP 命令时遇到权限问题该如何解决? 5. 如何确保在 ESXi 7.0 中使用 SCP 命令传输文件的安全性?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值