Example #1
0
// UploadBinaries is intended to create a temporary directory on a remote server,
// upload binaries to the temporary location and return path to the directory.
// The tempoary directory will be removed before the program exits
func UploadBinaries(conf *sshconf.Config, pathbins ...string) (string, error) {
	c, err := ssh.NewSshConn(conf)
	if err != nil {
		return "", FormatError(err)
	}
	defer c.ConnClose()

	dir, errout, err := c.Run("mktemp -d --suffix _deployer_bin")
	if err != nil {
		return "", FormatError(fmt.Errorf("%s [%v]", errout, err))
	}

	dir = strings.TrimSpace(dir)

	for _, src := range pathbins {
		dst := filepath.Join(dir, filepath.Base(src))
		if err := c.Upload(src, dst); err != nil {
			return "", FormatError(err)
		}
		if _, errout, err := c.Run("chmod 755 " + dst); err != nil {
			return "", FormatError(fmt.Errorf("%s [%v]", errout, err))
		}
	}
	return dir, nil
}
Example #2
0
// RunFunc is a generic solution for running appropriate commands
// on local or remote host
func RunFunc(config *sshconf.Config) func(string) (string, error) {
	if config == nil {
		return func(command string) (string, error) {
			var stderr bytes.Buffer
			var stdout bytes.Buffer
			c := exec.Command("/bin/bash", "-c", command)
			c.Stderr = &stderr
			c.Stdout = &stdout
			if err := c.Start(); err != nil {
				return "", FormatError(err)
			}
			if err := c.Wait(); err != nil {
				return "", fmt.Errorf("executing %s  : %s [%s]", command, stderr.String(), err)
			}
			return strings.TrimSpace(stdout.String()), nil
		}
	}
	return func(command string) (string, error) {
		c, err := ssh.NewSshConn(config)
		if err != nil {
			return "", FormatError(err)
		}
		defer c.ConnClose()

		var cmd string
		if strings.TrimSpace(config.User) == "root" {
			cmd = command
		} else {
			//IMPORTANT! Make sure that "Defaults !requiretty" is set in sudoers on remote system
			cmd = "sudo " + command
		}

		outstr, errstr, err := c.Run(cmd)
		if err != nil {
			return "", fmt.Errorf("executing %s : %s [%s]", cmd, errstr, err)
		}
		return strings.TrimSpace(outstr), nil
	}
}