python-3.xservervmwarevspherepyvmomi

How to get a file from a server in a cluster in Vsphere using pyVmomi to remote(host) pc


I am able to execute a command inside the server but I want to get that output in my local pc. I don't want want to use ssh keys. I want to use just the host's username and password as well as vm's(server's) username and password. I couldn't find a direct method to get the shell output of server in my pc, but this method seems half done like generate and save the output in server and then get the file from server. I am finding it difficult to get file(sample.txt) from server to local host(pc).

[EDIT: I am able to do this using via via method(Store the output to server and then get it back into local pc, is there a direct method ?) ]

from pyVim import connect
from config import *
from pyVmomi import vim, vmodl
import ssl

service_instance = connect.SmartConnect(host="yyyyyyy", port=some_number,user="xxx" , pwd=pwd,sslContext=ssl._create_unverified_context())
content = service_instance.RetrieveContent()

vm = searcher.FindByIp(ip="zzzzzz", vmSearch=True)

creds = vim.vm.guest.NamePasswordAuthentication(username='root', password=vmpwd)

pm = service_instance.content.guestOperationsManager.processManager

#checks python version and stores in sample.txt in server
ps = vim.vm.guest.ProcessManager.ProgramSpec(programPath='/usr/bin/python', arguments='--version  &> sample.txt') 
res = pm.StartProgramInGuest(vm, creds, ps)
print(res) #Prints pid

Solution

  • This does the job but I would appreciate if someone knows how to directly get the output of shell command from server to my local pc. This code makes a file with the output of cmd inside the server and it gets copied into my local pc

    from pyVim import connect
    from config import *
    from pyVmomi import vim, vmodl
    import ssl
    import os
    import requests
    
    service_instance = connect.SmartConnect(host="xxxx", port=aaa,user="yyy" , pwd=pwd,sslContext=ssl._create_unverified_context())
    
    content = service_instance.RetrieveContent()
    
    # # Find a VM
    vm = searcher.FindByIp(ip="aaaa", vmSearch=True)
    
    creds = vim.vm.guest.NamePasswordAuthentication(username='root', password=vmpwd)
    
    pm = service_instance.content.guestOperationsManager.processManager
    
    
    #executes and saves sample.txt into server
    ps = vim.vm.guest.ProcessManager.ProgramSpec(programPath='/usr/bin/python', arguments='--version  &> sample.txt')
    res = pm.StartProgramInGuest(vm, creds, ps)
    
    dest="/Users/username/Desktop/vcenter/sample.txt" #My local pc
    
    src="/root/sample.txt" #Server's directory
    fti = content.guestOperationsManager.fileManager.InitiateFileTransferFromGuest(vm, creds, src)
    
    resp=requests.get(fti.url, verify=False)
    
    #Writes into file
    with open(dest, 'wb') as f:
            f.write(resp.content)