Setup forwarding connection to given VM and pipe docker cmds over SSH.
499414
def handle(cls, vm, args):
        
        docker = Iaas.info(vm)
        if not docker:
            raise Exception('docker vm %s not found' % vm)

        if docker['state'] != 'running':
            Iaas.start(vm)

        # XXX
        remote_addr = docker['ifaces'][0]['ips'][0]['ip']

        port = unixpipe.setup(remote_addr, 'root', '/var/run/docker.sock')

        os.environ['DOCKER_HOST'] = 'tcp://localhost:%d' % port
        cls.echo('using DOCKER_HOST=%s' % os.environ['DOCKER_HOST'])

        subprocess.call(['docker'] + list(args))
311532
def connect(self):
    ""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((self.host, self.port))
    boto.log.debug("wrapping ssl socket; CA certificate file=%s",
                   self.ca_certs)
    self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
                                certfile=self.cert_file,
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=self.ca_certs)
    cert = self.sock.getpeercert()
    hostname = self.host.split(':', 0)[0]
    if not ValidateCertificateHostname(cert, hostname):
      raise InvalidCertificateException(hostname,
                                        cert,
                                        'remote hostname "%s" does not match '\
                                        'certificate' % hostname)
1260654
function dockerCommand(options) {
  const cmd = 'docker';
  const ps = spawnSync(cmd, options, { encoding: 'utf-8' });
  if (ps.error) {
    if (ps.error.code === 'ENOENT') {
      throw new Error('docker not found! Please install it.');
    }
    throw new Error(ps.error);
  } else if (ps.status !== 0) {
    throw new Error(ps.stderr);
  }
  return ps;
}
6835
def wrap_args_with_ssh_agent(self, args, ssh_key_path, ssh_auth_sock=None, silence_ssh_add=False):
        
        if ssh_key_path:
            ssh_add_command = args2cmdline('ssh-add', ssh_key_path)
            if silence_ssh_add:
                ssh_add_command = ' '.join([ssh_add_command, '2>/dev/null'])
            cmd = ' && '.join([ssh_add_command,
                               args2cmdline('rm', '-f', ssh_key_path),
                               args2cmdline(*args)])
            args = ['ssh-agent']
            if ssh_auth_sock:
                args.extend(['-a', ssh_auth_sock])
            args.extend(['sh', '-c', cmd])
        return args
200608
def connect_ssh_with_cb(ssh_cb, user, host, auth_cb, allow_new=True, 
                        verbosity=0):
    

    with connect_ssh(user, host, auth_cb, allow_new=True, verbosity=0) as ssh:
        ssh_cb(ssh)
895772
def main(args=None):
    
    parser = argparse.ArgumentParser(
        description=_("Run a command on Ubuntu Phablet"),
        epilog="""
        This tool will start ssh on your connected Ubuntu Touch device, forward
        a local port to the device, copy your ssh id down to the device (so you
        can log in without a password), and then ssh into the device through
        the locally forwarded port.

        This results in a very nice shell, which for example can display the
        output of 'top' at the correct terminal size, rather than being stuck
        at 80x25 like 'adb shell'

        Like ssh-copy-id, this script will push down the newest ssh key it can
        find in ~/.ssh/*.pub, so if you find the wrong key being pushed down,
        simply use 'touch' to make your desired key the newest one, and then
        this script will find it.
        """)
    dev_group = parser.add_argument_group(_("device connection options"))
    dev_group.add_argument(
        '-s', '--serial', action='store',
        help=_('connect to the device with the specified serial number'),
        default=None)
    if hasattr(subprocess, 'TimeoutExpired'):
        dev_group.add_argument(
            '-t', '--timeout', type=float, default=30.0,
            help=_('timeout for device discovery'))
    else:
        dev_group.add_argument(
            '-t', '--timeout', type=float, default=None,
            help=argparse.SUPPRESS)
    dev_group.add_argument(
        '-k', '--public-key', action='store', default=None,
        help=_('use the specified public key'))
    log_group = parser.add_argument_group(_("logging options"))
    log_group.add_argument(
        '--verbose', action='store_const', dest='log_level',
        const='INFO', help=_('be more verbose during connection set-up'))
    log_group.add_argument(
        '--log-level', action='store',
        help=_('set log level (for debugging)'),
        choices=[
            logging.getLevelName(level)
            for level in [
                logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
                logging.CRITICAL]])
    parser.add_argument(
        'cmd', nargs='...',
        help=_('command to run on the phablet, '
               ' if left out an interactive shell is started'))
    parser.add_argument('--version', action='version', version=__version__)
    parser.set_defaults(log_level='WARNING')
    ns = parser.parse_args(args)
    try:
        # Py3k
        level = logging._nameToLevel[ns.log_level]
    except AttributeError:
        # Py27
        level = logging._levelNames[ns.log_level]
    logging.basicConfig(
        level=level, style='{', format="[{levelname:10}] {message}")
    try:
        phablet = Phablet(ns.serial)
        return phablet.run(ns.cmd, timeout=ns.timeout, key=ns.public_key)
    except PhabletError as exc:
        _logger.critical("%s", exc)
        return 255
1335076
def ssh(
            self, machine, *,
            username=None, command=None, boot_only=False, discovered=False,
            wait=300):
        """"""
        start_time = time.monotonic()
        with utils.Spinner() as context:
            context.msg = colorized(
                "{autoblue}Determining{/autoblue} best IP for %s" % (
                    machine.hostname))
            ip_addresses = self.get_ip_addresses(
                machine, boot_only=boot_only, discovered=discovered)
            if len(ip_addresses) > 0:
                pingable_ips = self._async_get_sshable_ips(ip_addresses)
                while (len(pingable_ips) == 0 and
                        (time.monotonic() - start_time) < wait):
                    time.sleep(5)
                    pingable_ips = self._async_get_sshable_ips(ip_addresses)
                if len(pingable_ips) == 0:
                    raise CommandError(
                        "No IP addresses on %s can be reached." % (
                            machine.hostname))
                else:
                    ip = pingable_ips[0]
            else:
                raise CommandError(
                    "%s has no IP addresses." % machine.hostname)

            if username is None:
                context.msg = colorized(
                    "{autoblue}Determining{/autoblue} SSH username on %s" % (
                        machine.hostname))
                username = self._determine_username(ip)
                while (username is None and
                        (time.monotonic() - start_time) < wait):
                    username = self._determine_username(ip)
                if username is None:
                    raise CommandError(
                        "Failed to determine the username for SSH.")

            conn_str = "%s@%s" % (username, ip)
            args = [
                "ssh",
                "-o", "UserKnownHostsFile=/dev/null",
                "-o", "StrictHostKeyChecking=no",
                conn_str
            ]

            context.msg = colorized(
                "{automagenta}Waiting{/automagenta} for SSH on %s" % (
                    machine.hostname))
            check_args = args + ["echo"]
            connectable = self._check_ssh(*check_args)
            while not connectable and (time.monotonic() - start_time) < wait:
                time.sleep(5)
                connectable = self._check_ssh(*check_args)
            if not connectable:
                raise CommandError(
                    "SSH never started on %s using IP %s." % (
                        machine.hostname, ip))

        if command is not None:
            args.append(command)
        ssh = subprocess.Popen(
            args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
        ssh.wait()
        return ssh.returncode
1035973
function Forwarded(ip, port, secured) {
  this.ip = ip || '127.0.0.1';
  this.secure = !!secured;
  this.port = +port || 0;
}
773948
def cli(env, identifier, postinstall, key, image):
    """"""

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    keys = []
    if key:
        for single_key in key:
            resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
            key_id = helpers.resolve_id(resolver, single_key, 'SshKey')
            keys.append(key_id)
    if not (env.skip_confirmations or formatting.no_going_back(vs_id)):
        raise exceptions.CLIAbort('Aborted')

    vsi.reload_instance(vs_id,
                        post_uri=postinstall,
                        ssh_keys=keys,
                        image_id=image)
401572
def _connect(self):
        """"""
        self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._soc.connect((self._ipaddr, self._port))
        self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
                                       'sha': self._password}))
42260
def ssh(cls, vm_id, login, identity, args=None):
        """"""
        cmd = ['ssh']
        if identity:
            cmd.extend(('-i', identity,))

        version, ip_addr = cls.vm_ip(vm_id)
        if version == 6:
            cmd.append('-6')

        if not ip_addr:
            cls.echo('No IP address found for vm %s, aborting.' % vm_id)
            return

        cmd.append('%s@%s' % (login, ip_addr,))

        if args:
            cmd.extend(args)

        cls.echo('Requesting access using: %s ...' % ' '.join(cmd))
        return cls.execute(cmd, False)
688091
function (options, callback) {
    let me = this
    let tunnel
    let sshcfg = {
      host: this.host + ':' + (options.sshport || 22),
      user: options.username,
      remoteport: this.port
    }

    if (options.password) {
      sshcfg.password = options.password
    }

    if (options.key) {
      sshcfg.key = options.key
    }

    // Dynamically determine port by availability or via option.
    // Then open the tunnel.
    if (options.port) {
      sshcfg.port = options.port
      tunnel = new NGN.Tunnel(sshcfg)
      tunnel.on('ready', function () {
        NGN.BUS.emit('sshtunnel.create', tunnel)
        callback && callback(me.host, options.port)
      })
      tunnel.connect()
    } else {
      // Create a quick TCP server on random port to secure the port,
      // then shut it down and use the newly freed port.
      let tmp = net.createServer().listen(0, '127.0.0.1', function () {
        sshcfg.port = this.address().port
        tmp.close()
      })

      tmp.on('close', function () {
        // Launch the tunnel
        tunnel = new NGN.Tunnel(sshcfg)
        tunnel.on('ready', function () {
          callback && callback('127.0.0.1', sshcfg.port)
        })
        tunnel.connect()
      })
    }
  }
66856
function SSH(options) {
	this.options = options || {};
	console.assert(this.options.hostname, "Hostname required!");

	this.debug = !!options.debug;
	this.listener = new Listener({
		debug: options.debug
	});
}
839517
function docker(cwd, cmd) {
  console.log(cwd, chalk.blue('running docker', cmd));
  return spawn('docker', (cmd || 'build .').split(' '), {cwd, env});
}
965925
def docker(gandi, vm, args):
    
    if not [basedir for basedir in os.getenv('PATH', '.:/usr/bin').split(':')
            if os.path.exists('%s/docker' % basedir)]:
        gandi.echo("""'docker' not found in $PATH, required for this command \
to work
See https://docs.docker.com/installation/#installation to install, or use:
    # curl https://get.docker.io/ | sh""")
        return

    if vm:
        gandi.configure(True, 'dockervm', vm)
    else:
        vm = gandi.get('dockervm')

    if not vm:
        gandi.echo("""
No docker vm specified. You can create one:
    $ gandi vm create --hostname docker --image "Ubuntu 14.04 64 bits LTS (HVM)" \\
        --run 'wget -O - https://get.docker.io/ | sh'

Then configure it using:
    $ gandi docker --vm docker ps

Or to both change target vm and spawn a process (note the -- separator):
    $ gandi docker --vm myvm -- run -i -t debian bash
""")  # noqa
        return

    return gandi.docker.handle(vm, args)
1100692
def _build_ssh_client(self):
        """"""
        # Create instance of SSHClient object
        remote_conn_pre = paramiko.SSHClient()

        # Load host_keys for better SSH security
        if self.system_host_keys:
            remote_conn_pre.load_system_host_keys()
        if self.alt_host_keys and path.isfile(self.alt_key_file):
            remote_conn_pre.load_host_keys(self.alt_key_file)

        # Default is to automatically add untrusted hosts (make sure appropriate for your env)
        remote_conn_pre.set_missing_host_key_policy(self.key_policy)
        return remote_conn_pre
1210639
def connect_command(self):
        '''
        

        '''
        options = {
            "verbose": self.options["verbose"],
            "pedantic": self.options["pedantic"],
            "lang": __lang__,
            "version": __version__,
            "protocol": PROTOCOL
        }
        if "auth_required" in self._server_info:
            if self._server_info["auth_required"] == True:
                # In case there is no password, then consider handle
                # sending a token instead.
                if self.options["user"] is not None and self.options["password"] is not None:
                    options["user"] = self.options["user"]
                    options["pass"] = self.options["password"]
                elif self.options["token"] is not None:
                    options["auth_token"] = self.options["token"]
                elif self._current_server.uri.password is None:
                    options["auth_token"] = self._current_server.uri.username
                else:
                    options["user"] = self._current_server.uri.username
                    options["pass"] = self._current_server.uri.password
        if self.options["name"] is not None:
            options["name"] = self.options["name"]
        if self.options["no_echo"] is not None:
            options["echo"] = not self.options["no_echo"]

        args = json.dumps(options, sort_keys=True)
        return CONNECT_PROTO.format(CONNECT_OP, args, _CRLF_)