github.com/teknogeek/dnscontrol@v0.2.8/providers/activedir/getzones_windows.go (about)

     1  package activedir
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"strconv"
     7  	"strings"
     8  	"sync"
     9  
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  var checkPS sync.Once
    14  var psAvailible = false
    15  
    16  func (c *adProvider) getRecords(domainname string) ([]byte, error) {
    17  
    18  	// If we are using PowerShell, make sure it is enabled
    19  	// and then run the PS1 command to generate the adzonedump file.
    20  
    21  	if !c.fake {
    22  		checkPS.Do(func() {
    23  			psAvailible = c.isPowerShellReady()
    24  			if !psAvailible {
    25  				fmt.Printf("\n\n\n")
    26  				fmt.Printf("***********************************************\n")
    27  				fmt.Printf("PowerShell DnsServer module not installed.\n")
    28  				fmt.Printf("See http://social.technet.microsoft.com/wiki/contents/articles/2202.remote-server-administration-tools-rsat-for-windows-client-and-windows-server-dsforum2wiki.aspx\n")
    29  				fmt.Printf("***********************************************\n")
    30  				fmt.Printf("\n\n\n")
    31  			}
    32  		})
    33  		if !psAvailible {
    34  			return nil, errors.Errorf("powershell module DnsServer not installed")
    35  		}
    36  
    37  		_, err := c.powerShellExec(c.generatePowerShellZoneDump(domainname), true)
    38  		if err != nil {
    39  			return []byte{}, err
    40  		}
    41  	}
    42  	// Return the contents of zone.*.json file instead.
    43  	return c.readZoneDump(domainname)
    44  }
    45  
    46  func (c *adProvider) isPowerShellReady() bool {
    47  	query, _ := c.powerShellExec(`(Get-Module -ListAvailable DnsServer) -ne $null`, true)
    48  	q, err := strconv.ParseBool(strings.TrimSpace(string(query)))
    49  	if err != nil {
    50  		return false
    51  	}
    52  	return q
    53  }
    54  
    55  func (c *adProvider) powerShellDoCommand(command string, shouldLog bool) error {
    56  	if c.fake {
    57  		// If fake, just record the command.
    58  		return c.powerShellRecord(command)
    59  	}
    60  	_, err := c.powerShellExec(command, shouldLog)
    61  	return err
    62  }
    63  
    64  func (c *adProvider) powerShellExec(command string, shouldLog bool) ([]byte, error) {
    65  	// log it.
    66  	err := c.logCommand(command)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  
    71  	// Run it.
    72  	out, err := exec.Command("powershell", "-NoProfile", command).CombinedOutput()
    73  	if err != nil {
    74  		// If there was an error, log it.
    75  		c.logErr(err)
    76  	}
    77  	if shouldLog {
    78  		err = c.logOutput(string(out))
    79  		if err != nil {
    80  			return []byte{}, err
    81  		}
    82  	}
    83  
    84  	// Return the result.
    85  	return out, err
    86  }