Exit or check ssh mux
19888
def _ssh_master_cmd(addr, user, command, local_key=None):
    """"""
    ssh_call = ['ssh', '-qNfL%d:127.0.0.1:12042' % find_port(addr, user),
                '-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' %
                       find_port(addr, user),
                '-O', command, '%s@%s' % (user, addr,)]

    if local_key:
        ssh_call.insert(1, local_key)
        ssh_call.insert(1, '-i')

    return subprocess.call(ssh_call)
1275147
def tunnel(self, local_port, remote_port=None, remote_host="localhost"):
        
        tunnel_host = "{0}:{1}:{2}".format(local_port, remote_host, remote_port)
        proc = self.Popen(
            # cat so we can shut down gracefully by closing stdin
            ["-L", tunnel_host, "echo -n ready && cat"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
        )
        # make sure to get the data so we know the connection is established
        ready = proc.stdout.read(5)
        assert ready == b"ready", "Didn't get ready from remote echo"
        yield  # user code executed here
        proc.communicate()
        assert proc.returncode == 0, "Tunnel process did an unclean exit (returncode %s)" % (proc.returncode,)
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)
852828
def _complete_exit(self, cmd, args, text):
        """"""
        if args:
            return
        return [ x for x in { 'root', 'all', } \
                if x.startswith(text) ]
771727
def cli(ctx, project_dir):
    """"""
    exit_code = SCons(project_dir).clean()
    ctx.exit(exit_code)
210538
def exec_command(self):
        
        if not self.original_command_string:
            raise SSHEnvironmentError('no SSH command found; '
                                      'interactive shell disallowed.')

        command_info = {'from': self.get_client_ip(),
                        'keyname': self.keyname,
                        'ssh_original_comand': self.original_command_string,
                        'time': time.time()}

        os.environ['AUTHPROGS_KEYNAME'] = self.keyname

        retcode = 126
        try:
            match = self.find_match()
            command_info['command'] = match.get('command')
            self.logdebug('find_match returned "%s"\n' % match)

            command = match['command']
            retcode = subprocess.call(command)
            command_info['code'] = retcode
            self.log('result: %s\n' % command_info)
            sys.exit(retcode)
        except (CommandRejected, OSError) as err:
            command_info['exception'] = '%s' % err
            self.log('result: %s\n' % command_info)
            sys.exit(retcode)
679829
def cleanup(self):
        
        if self.local_port is not None:
            logger.debug(("Stopping ssh tunnel {0}:{1}:{2} for "
                          "{3}@{4}".format(self.local_port,
                                           self.remote_address,
                                           self.remote_port,
                                           self.username,
                                           self.address)))
            if self.forward is not None:
                self.forward.stop()
                self.forward.join()
            if self.transport is not None:
                self.transport.close()
233658
def loop_misc(self):
        """"""
        if self._sock is None and self._ssl is None:
            return MQTT_ERR_NO_CONN

        now = time.time()
        self._check_keepalive()
        if self._last_retry_check+1 < now:
            # Only check once a second at most
            self._message_retry_check()
            self._last_retry_check = now

        if self._ping_t > 0 and now - self._ping_t >= self._keepalive:
            # client->ping_t != 0 means we are waiting for a pingresp.
            # This hasn't happened in the keepalive time so we should disconnect.
            if self._ssl:
                self._ssl.close()
                self._ssl = None
            elif self._sock:
                self._sock.close()
                self._sock = None

            self._callback_mutex.acquire()
            if self._state == mqtt_cs_disconnecting:
                rc = MQTT_ERR_SUCCESS
            else:
                rc = 1
            if self.on_disconnect:
                self._in_callback = True
                self.on_disconnect(self, self._userdata, rc)
                self._in_callback = False
            self._callback_mutex.release()
            return MQTT_ERR_CONN_LOST

        return MQTT_ERR_SUCCESS
1068167
def is_ssh_available(host, port=22):
    
    s = socket.socket()
    try:
        s.connect((host, port))
        return True
    except:
        return False
1018786
def ssh_command(ip, command)
      configure_ssh_command(ip, command) do |ch, success|
        return 1 unless success

        if_debug(2) do
          ch.on_data do |ch, data|
            $stderr.puts data
          end
        end

        ch.on_request("exit-status") do |ch, data|
          return data.read_long
        end
      end
    end
507913
def checkPortIsOpen(remoteServerHost=ServerHost, port = Port):
    '''
    
    '''
    remoteServerIP  = socket.gethostbyname(remoteServerHost)
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((remoteServerIP, int(port)))
        if result == 0:
            return True
        else :
            return False
        sock.close()
        #FIXME: the above line is unreachable

    except KeyboardInterrupt:
        print("You pressed Ctrl+C")
        sys.exit()

    except socket.gaierror:
        print('Hostname could not be resolved. Exiting')
        sys.exit()

    except socket.error:
        print("Couldn't connect to server")
        sys.exit()
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
490188
def cli(ctx, project_dir):
    """"""
    exit_code = SCons(project_dir).verify()
    ctx.exit(exit_code)
359627
def _authenticate_ssh(org):
    """"""
    # Try to get username from git config
    username = os.environ.get(f"{org.upper()}_USERNAME")
    # Require ssh-agent
    child = pexpect.spawn("ssh -T git@github.com", encoding="utf8")
    # GitHub prints 'Hi {username}!...' when attempting to get shell access
    i = child.expect(["Hi (.+)! You've successfully authenticated",
                      "Enter passphrase for key",
                      "Permission denied",
                      "Are you sure you want to continue connecting"])
    child.close()

    if i == 0:
        if username is None:
            username = child.match.groups()[0]
    else:
        return None

    return User(name=username,
                repo=f"git@github.com:{org}/{username}")
458805
def exec_command(self, cmd, tmp_path, sudo_user,sudoable=False, executable='/bin/sh'):
        '''  '''

        ssh_cmd = self._password_cmd()
        ssh_cmd += ["ssh", "-tt", "-q"] + self.common_args + [self.host]

        if not self.runner.sudo or not sudoable:
            if executable:
                ssh_cmd.append(executable + ' -c ' + pipes.quote(cmd))
            else:
                ssh_cmd.append(cmd)
        else:
            sudocmd, prompt = utils.make_sudo_cmd(sudo_user, executable, cmd)
            ssh_cmd.append(sudocmd)

        vvv("EXEC %s" % ssh_cmd, host=self.host)
        try:
            # Make sure stdin is a proper (pseudo) pty to avoid: tcgetattr errors
            import pty
            master, slave = pty.openpty()
            p = subprocess.Popen(ssh_cmd, stdin=slave,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdin = os.fdopen(master, 'w', 0)
        except:
            p = subprocess.Popen(ssh_cmd, stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdin = p.stdin

        self._send_password()

        if self.runner.sudo and sudoable and self.runner.sudo_pass:
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            sudo_output = ''
            while not sudo_output.endswith(prompt):
                rfd, wfd, efd = select.select([p.stdout], [],
                                              [p.stdout], self.runner.timeout)
                if p.stdout in rfd:
                    chunk = p.stdout.read()
                    if not chunk:
                        raise errors.AnsibleError('ssh connection closed waiting for sudo password prompt')
                    sudo_output += chunk
                else:
                    stdout = p.communicate()
                    raise errors.AnsibleError('ssh connection error waiting for sudo password prompt')
            stdin.write(self.runner.sudo_pass + '\n')
            fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)

        # We can't use p.communicate here because the ControlMaster may have stdout open as well
        stdout = ''
        stderr = ''
        while True:
            rfd, wfd, efd = select.select([p.stdout, p.stderr], [], [p.stdout, p.stderr], 1)
            if p.stdout in rfd:
                dat = os.read(p.stdout.fileno(), 9000)
                stdout += dat
                if dat == '':
                    p.wait()
                    break
            elif p.stderr in rfd:
                dat = os.read(p.stderr.fileno(), 9000)
                stderr += dat
                if dat == '':
                    p.wait()
                    break
            elif p.poll() is not None:
                break
        stdin.close() # close stdin after we read from stdout (see also issue #848)

        if p.returncode != 0 and stderr.find('Bad configuration option: ControlPersist') != -1:
            raise errors.AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ansible_ssh_args in the config file) before running again')

        return (p.returncode, '', stdout, stderr)
313694
def check_output(cmd):
    """"""
    popen = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    out = popen.communicate()[0].strip()
    if not isinstance(out, str):
        out = out.decode(sys.stdout.encoding)
    return out
488437
def ssh(self, *command):
        """"""
        if self.args.user:
            ssh_spec = '{0}@{1}'.format(self.args.user, self.args.server)
        else:
            ssh_spec = self.args.server

        return self.sh('ssh', ssh_spec, *command)