github.com/vmware/govmomi@v0.51.0/cli/vm/guest/run.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package guest 6 7 import ( 8 "bytes" 9 "context" 10 "flag" 11 "os" 12 "os/exec" 13 14 "github.com/vmware/govmomi/cli" 15 ) 16 17 type run struct { 18 *GuestFlag 19 20 data string 21 dir string 22 vars env 23 } 24 25 func init() { 26 cli.Register("guest.run", &run{}) 27 } 28 29 func (cmd *run) Register(ctx context.Context, f *flag.FlagSet) { 30 cmd.GuestFlag, ctx = newGuestProcessFlag(ctx) 31 cmd.GuestFlag.Register(ctx, f) 32 33 f.StringVar(&cmd.data, "d", "", "Input data string. A value of '-' reads from OS stdin") 34 f.StringVar(&cmd.dir, "C", "", "The absolute path of the working directory for the program to start") 35 f.Var(&cmd.vars, "e", "Set environment variables") 36 } 37 38 func (cmd *run) Usage() string { 39 return "PATH [ARG]..." 40 } 41 42 func (cmd *run) Description() string { 43 return `Run program PATH in VM and display output. 44 45 The guest.run command starts a program in the VM with i/o redirected, waits for the process to exit and 46 propagates the exit code to the govc process exit code. Note that stdout and stderr are redirected by default, 47 stdin is only redirected when the '-d' flag is specified. 48 49 Note that vmware-tools requires program PATH to be absolute. 50 If PATH is not absolute and vm guest family is Windows, 51 guest.run changes the command to: 'c:\\Windows\\System32\\cmd.exe /c "PATH [ARG]..."' 52 Otherwise the command is changed to: '/bin/bash -c "PATH [ARG]..."' 53 54 Examples: 55 govc guest.run -vm $name ifconfig 56 govc guest.run -vm $name ifconfig eth0 57 cal | govc guest.run -vm $name -d - cat 58 govc guest.run -vm $name -d "hello $USER" cat 59 govc guest.run -vm $name curl -s :invalid: || echo $? # exit code 6 60 govc guest.run -vm $name -e FOO=bar -e BIZ=baz -C /tmp env 61 govc guest.run -vm $name -l root:mypassword ntpdate -u pool.ntp.org 62 govc guest.run -vm $name powershell C:\\network_refresh.ps1` 63 } 64 65 func (cmd *run) Run(ctx context.Context, f *flag.FlagSet) error { 66 if f.NArg() == 0 { 67 return flag.ErrHelp 68 } 69 name := f.Arg(0) 70 71 c, err := cmd.Toolbox(ctx) 72 if err != nil { 73 return err 74 } 75 76 ecmd := &exec.Cmd{ 77 Path: name, 78 Args: f.Args()[1:], 79 Env: cmd.vars, 80 Dir: cmd.dir, 81 Stdout: os.Stdout, 82 Stderr: os.Stderr, 83 } 84 85 switch cmd.data { 86 case "": 87 case "-": 88 ecmd.Stdin = os.Stdin 89 default: 90 ecmd.Stdin = bytes.NewBuffer([]byte(cmd.data)) 91 } 92 93 return c.Run(ctx, ecmd) 94 }