github.phpd.cn/hashicorp/packer@v1.3.2/builder/virtualbox/common/step_configure_vrdp.go (about) 1 package common 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "math/rand" 8 "net" 9 10 "github.com/hashicorp/packer/helper/multistep" 11 "github.com/hashicorp/packer/packer" 12 ) 13 14 // This step configures the VM to enable the VRDP server 15 // on the guest machine. 16 // 17 // Uses: 18 // driver Driver 19 // ui packer.Ui 20 // vmName string 21 // 22 // Produces: 23 // vrdp_port unit - The port that VRDP is configured to listen on. 24 type StepConfigureVRDP struct { 25 VRDPBindAddress string 26 VRDPPortMin uint 27 VRDPPortMax uint 28 } 29 30 func (s *StepConfigureVRDP) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 31 driver := state.Get("driver").(Driver) 32 ui := state.Get("ui").(packer.Ui) 33 vmName := state.Get("vmName").(string) 34 35 log.Printf("Looking for available port between %d and %d on %s", s.VRDPPortMin, s.VRDPPortMax, s.VRDPBindAddress) 36 var vrdpPort uint 37 portRange := int(s.VRDPPortMax - s.VRDPPortMin) 38 39 for { 40 if portRange > 0 { 41 vrdpPort = uint(rand.Intn(portRange)) + s.VRDPPortMin 42 } else { 43 vrdpPort = s.VRDPPortMin 44 } 45 46 log.Printf("Trying port: %d", vrdpPort) 47 l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.VRDPBindAddress, vrdpPort)) 48 if err == nil { 49 defer l.Close() 50 break 51 } 52 } 53 54 command := []string{ 55 "modifyvm", vmName, 56 "--vrdeaddress", fmt.Sprintf("%s", s.VRDPBindAddress), 57 "--vrdeauthtype", "null", 58 "--vrde", "on", 59 "--vrdeport", 60 fmt.Sprintf("%d", vrdpPort), 61 } 62 if err := driver.VBoxManage(command...); err != nil { 63 err := fmt.Errorf("Error enabling VRDP: %s", err) 64 state.Put("error", err) 65 ui.Error(err.Error()) 66 return multistep.ActionHalt 67 } 68 69 state.Put("vrdpIp", s.VRDPBindAddress) 70 state.Put("vrdpPort", vrdpPort) 71 72 return multistep.ActionContinue 73 } 74 75 func (s *StepConfigureVRDP) Cleanup(state multistep.StateBag) {}