Python paramiko.SSHClient() Examples

The following are 30 code examples of paramiko.SSHClient(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module paramiko , or try the search function .
Example #1
Source File: docker.py    From pywren-ibm-cloud with Apache License 2.0 29 votes vote down vote up
def _ssh_run_remote_command(self, cmd):
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=self.host,
                           username=self.config['ssh_user'],
                           password=self.config['ssh_password'])
        stdin, stdout, stderr = ssh_client.exec_command(cmd)

        out = stdout.read().decode().strip()
        error = stderr.read().decode().strip()
        if self.log_level:
            logger.info(out)
        if error:
            raise Exception('There was an error pulling the runtime: {}'.format(error))
        ssh_client.close()

        return out 
Example #2
Source File: RemoteCrashFetcher.py    From LuckyCAT with GNU General Public License v3.0 11 votes vote down vote up
def fetch_remote_crashes(self):
        """
        some exception handling code is taken from https://www.programcreek.com/python/example/105570/scp.SCPClient
        """
        try:
            ssh = SSHClient()
            ssh.load_system_host_keys()
            ssh.connect(hostname=config.remote_system_ip)
            self.copy_crashes_dir_with_scp(ssh)
        except AuthenticationException:
            print("Authentication failed, please verify your credentials: %s")
        except SSHException as sshException:
            print("Unable to establish SSH connection: %s" % sshException)
        except BadHostKeyException as badHostKeyException:
            print("Unable to verify server's host key: %s" % badHostKeyException)
        finally:
            ssh.close() 
Example #3
Source File: ex1_paramiko.py    From pynet with Apache License 2.0 11 votes vote down vote up
def main():
    '''
    Use Paramiko to retrieve the entire 'show version' output.
    '''
    ip_addr = raw_input("Enter IP address: ")
    username = 'pyclass'
    password = getpass()
    port = 22

    remote_conn_pre = paramiko.SSHClient()
    remote_conn_pre.load_system_host_keys()

    remote_conn_pre.connect(ip_addr, port=port, username=username, password=password,
                            look_for_keys=False, allow_agent=False)
    remote_conn = remote_conn_pre.invoke_shell()

    time.sleep(1)
    clear_buffer(remote_conn)
    disable_paging(remote_conn)

    output = send_command(remote_conn, cmd='show version')
    print '\n>>>>'
    print output
    print '>>>>\n' 
Example #4
Source File: ssh.py    From JetPack with Apache License 2.0 10 votes vote down vote up
def ssh_edit_file(adress, user, passw, remotefile, regex, replace):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        trans = paramiko.Transport((adress, 22))
        trans.connect(username=user, password=passw)
        sftp = paramiko.SFTPClient.from_transport(trans)
        f_in = sftp.file(remotefile, "r")
        c_in = f_in.read()
        pattern = re.compile(regex, re.MULTILINE | re.DOTALL)
        c_out = pattern.sub(replace, c_in)
        f_out = sftp.file(remotefile, "w")
        f_out.write(c_out)
        f_in.close()
        f_out.close()
        sftp.close()
        trans.close() 
Example #5
Source File: installInsightAgent.py    From InsightAgent with Apache License 2.0 9 votes vote down vote up
def sshInstall(retry,hostname):
    global user
    global password
    global userInsightfinder
    global licenseKey
    global samplingInterval
    global reportingInterval
    global agentType
    if retry == 0:
        print "Install Fail in", hostname
        q.task_done()
        return
    print "Start installing agent in", hostname, "..."
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        session.exec_command("sudo rm -rf insightagent* InsightAgent* \n \
        wget --no-check-certificate https://github.com/insightfinder/InsightAgent/archive/master.tar.gz -O insightagent.tar.gz && \
        tar xzvf insightagent.tar.gz && \
        cd InsightAgent-master && deployment/checkpackages.sh -env\n")
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Install Succeed in", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshInstall(retry-1,hostname) 
Example #6
Source File: test_ssh.py    From poseidon with MIT License 9 votes vote down vote up
def test_exec_command(client, mock):
    def my_mock(*args):
        return None, None, None

    mock.patch.object(paramiko.SSHClient, 'connect')
    mock.patch.object(paramiko.SSHClient, 'exec_command', my_mock)
    stdin, stdout, stderr = client.exec_command('yes')


# def test_wait(pair):
#     # TODO: fix unit test here
#     client, server = pair
#     client.con
#     server.stdout('ok', delay=True)
#     output = client.wait('yes')
#     assert output == 'ok' 
Example #7
Source File: sftp.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 9 votes vote down vote up
def __init__(self, host, **ssh_kwargs):
        """

        Parameters
        ----------
        host: str
            Hostname or IP as a string
        temppath: str
            Location on the server to put files, when within a transaction
        ssh_kwargs: dict
            Parameters passed on to connection. See details in
            http://docs.paramiko.org/en/2.4/api/client.html#paramiko.client.SSHClient.connect
            May include port, username, password...
        """
        if self._cached:
            return
        super(SFTPFileSystem, self).__init__(**ssh_kwargs)
        self.temppath = ssh_kwargs.pop("temppath", "/tmp")
        self.host = host
        self.ssh_kwargs = ssh_kwargs
        self._connect() 
Example #8
Source File: network.py    From LiMEaide with GNU General Public License v3.0 9 votes vote down vote up
def connect(self):
        """Call to set connection with remote client."""

        try:
            self.paramiko_session = paramiko.SSHClient()
            self.paramiko_session.set_missing_host_key_policy(
                paramiko.AutoAddPolicy())

            self.paramiko_session.connect(
                self.client.ip, username=self.client.user,
                password=self.client.pass_, key_filename=self.client.key,
                allow_agent=True, compress=self.client.compress)

        except (paramiko.AuthenticationException,
                paramiko.ssh_exception.NoValidConnectionsError) as e:
            self.logger.error(e)
            sys.exit(colored("> {}".format(e), 'red'))

        except paramiko.SSHException as e:
            self.logger.error(e)
            sys.exit(colored("> {}".format(e), 'red'))

        self.transfer = network.Network(
            self.paramiko_session, self.client.ip, self.client.port)
        self.transfer.open() 
Example #9
Source File: tunnel.py    From Computable with MIT License 8 votes vote down vote up
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True 
Example #10
Source File: ex2_paramiko.py    From python_course with Apache License 2.0 8 votes vote down vote up
def main():
    """Use Paramiko to change 'logging buffered <size>' configuration."""
    try:
        ip_addr = raw_input("Enter IP address: ")
    except NameError:
        ip_addr = input("Enter IP address: ")
    username = 'pyclass'
    password = getpass()
    port = 22

    remote_conn_pre = paramiko.SSHClient()
    remote_conn_pre.load_system_host_keys()

    remote_conn_pre.connect(ip_addr, port=port, username=username, password=password,
                            look_for_keys=False, allow_agent=False)
    remote_conn = remote_conn_pre.invoke_shell()

    time.sleep(1)
    clear_buffer(remote_conn)
    disable_paging(remote_conn)

    send_command(remote_conn, cmd='conf t')
    send_command(remote_conn, cmd='logging buffered 20010')
    send_command(remote_conn, cmd='end')

    output = send_command(remote_conn, cmd='show run | inc logging', delay=2)
    print('\n>>>>')
    print(output)
    print('>>>>\n') 
Example #11
Source File: test_ssh.py    From poseidon with MIT License 8 votes vote down vote up
def pair(request):
    server = SSHClientFixture()
    thread = threading.Thread(target=server.run)
    thread.daemon = True
    thread.start()

    client = S.SSHClient(server.addr, port=server.port,
                         username='slowdive',
                         password='pygmalion')

    def fin():
        server.tearDown()
        client.close()
    request.addfinalizer(fin)

    return client, server 
Example #12
Source File: tunnel.py    From vnpy_crypto with MIT License 8 votes vote down vote up
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavailable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True 
Example #13
Source File: ssh.py    From ARC with MIT License 8 votes vote down vote up
def check_connections(function: Callable[..., Any]) -> Callable[..., Any]:
    """
    A decorator designned for ``SSHClient``to check SSH connections before
    calling a method. It first checks if ``self._ssh`` is available in a 
    SSHClient instance and then checks if you can send ``ls`` and get response
    to make sure your connection still alive. If connection is bad, this
    decorator will reconnect the SSH channel, to avoid connection related
    error when executing the method.
    """
    def decorator(*args, **kwargs) -> Any:
        self = args[0]
        if self._ssh is None:  # not sure if some status may cause False
            self._sftp, self._ssh = self.connect()
        # test connection, reference:
        # https://stackoverflow.com/questions/
        # 20147902/how-to-know-if-a-paramiko-ssh-channel-is-disconnected
        # According to author, maybe no better way
        try:
            self._ssh.exec_command('ls')
        except Exception as e:
            logger.debug(f'The connection is no longer valid. {e}')
            self.connect()
        return function(*args, **kwargs)
    return decorator 
Example #14
Source File: python多线程ssh爆破.py    From fuzzdb-collect with GNU General Public License v3.0 8 votes vote down vote up
def run(self):
        print("Start try ssh => %s" % self.ip)
        username = "root"
        try:
            password = open(self.dict).read().split('\n')
        except:
            print("Open dict file `%s` error" % self.dict)
            exit(1)
        for pwd in password:
            try:
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(self.ip, self.port, username, pwd, timeout = self.timeout)
                print("\nIP => %s, Login %s => %s \n" % (self.ip, username, pwd))
                open(self.LogFile, "a").write("[ %s ] IP => %s, port => %d, %s => %s \n" % (time.asctime( time.localtime(time.time()) ), self.ip, self.port, username, pwd))
                break
            except:
                print("IP => %s, Error %s => %s" % (self.ip, username, pwd))
                pass 
Example #15
Source File: ssh-brute-force-threded.py    From Effective-Python-Penetration-Testing with MIT License 7 votes vote down vote up
def attempt(Password):

    IP = "127.0.0.1"
    USER = "rejah"
    PORT=22
      
    try:

        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
 
        try:
            ssh.connect(IP , port=PORT, username=USER, password=Password)
            print "Connected successfully. Password = "+Password
        except paramiko.AuthenticationException, error:
            print "Incorrect password: "+Password
            pass
        except socket.error, error:
            print error
            pass 
Example #16
Source File: ssh.py    From JetPack with Apache License 2.0 7 votes vote down vote up
def execute_command_readlines(address, usr, pwd, command):
        try:
            logger.debug("ssh " + usr + "@" + address + ", running : " +
                         command)
            client = paramiko.SSHClient()
            client.load_system_host_keys()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            client.connect(address, username=usr, password=pwd)
            _, ss_stdout, ss_stderr = client.exec_command(command)
            r_out, r_err = ss_stdout.readlines(), ss_stderr.read()
            logger.debug(r_err)
            if len(r_err) > 5:
                logger.error(r_err)
            else:
                logger.debug(r_out)
            client.close()
        except IOError:
            logger.warning(".. host " + address + " is not up")
            return "host not up", "host not up"

        return r_out, r_err 
Example #17
Source File: remote_host_helper.py    From Zopkio with Apache License 2.0 7 votes vote down vote up
def better_exec_command(ssh, command, msg):
  """Uses paramiko to execute a command but handles failure by raising a ParamikoError if the command fails.
  Note that unlike paramiko.SSHClient.exec_command this is not asynchronous because we wait until the exit status is known

  :Parameter ssh: a paramiko SSH Client
  :Parameter command: the command to execute
  :Parameter msg: message to print on failure

  :Returns (paramiko.Channel)
   the underlying channel so that the caller can extract stdout or send to stdin

  :Raises  SSHException: if paramiko would raise an SSHException
  :Raises  ParamikoError: if the command produces output to stderr
  """
  chan = ssh.get_transport().open_session()
  chan.exec_command(command)
  exit_status = chan.recv_exit_status()
  if exit_status != 0:
    msg_str = chan.recv_stderr(1024)
    err_msgs = []
    while len(msg_str) > 0:
      err_msgs.append(msg_str)
      msg_str = chan.recv_stderr(1024)
    err_msg = ''.join(err_msgs)
    logger.error(err_msg)
    raise ParamikoError(msg, err_msg)
  return chan 
Example #18
Source File: stopcron.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def sshStopCron(retry,hostname):
    global user
    global password
    if retry == 0:
        print "Stop Cron Failed in", hostname
        q.task_done()
        return
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        command = "sudo mv /etc/cron.d/ifagent InsightAgent-master/ifagent."+time.strftime("%Y%m%d%H%M%S")+"\n"
        session.exec_command(command)
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Stopped Cron in ", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshStopCron(retry-1,hostname) 
Example #19
Source File: export.py    From ectou-export with MIT License 6 votes vote down vote up
def connect_ssh(username, host, private_key_file):
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())  # TODO: Configure host key fingerprint.
    while not ssh_client.get_transport():
        try:
            ssh_client.connect(host,
                               username=username,
                               key_filename=private_key_file,
                               allow_agent=False,
                               look_for_keys=False,
                               compress=True)
        except socket.error:
            print "wait ssh agent"
            time.sleep(POLL_SECONDS)

    return ssh_client 
Example #20
Source File: test_ssh.py    From poseidon with MIT License 5 votes vote down vote up
def test_top(client, mock):
    mock.patch.object(S.SSHClient, 'ps')
    client.top()
    client.ps.assert_called_with('o', S.TOP_OPTIONS) 
Example #21
Source File: dhcp_thread.py    From openmano with Apache License 2.0 5 votes vote down vote up
def ssh_connect(self):
        try:
            #Connect SSH
            self.ssh_conn = paramiko.SSHClient()
            self.ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh_conn.load_system_host_keys()
            self.ssh_conn.connect(self.dhcp_params["host"], port=self.dhcp_params.get("port",22),
                                  username=self.dhcp_params["user"], password=self.dhcp_params.get("password"), pkey=self.dhcp_params.get("key"),
                                  timeout=2)
        except paramiko.ssh_exception.SSHException as e:
            text = e.args[0]
            print self.name, ": ssh_connect ssh Exception:", text 
Example #22
Source File: auxiliary_functions.py    From openmano with Apache License 2.0 5 votes vote down vote up
def get_ssh_connection(machine, user=None, password=None):
    """Stablishes an ssh connection to the remote server. Returns (True, paramiko_ssh) in case of success or (False, <error message>) in case of error"""
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        s.load_system_host_keys()
        s.connect(machine, 22, user, password, timeout=10)
    except Exception,e:
        return (False, 'It was not possible to connect to '+machine+str(e)) 
Example #23
Source File: __init__.py    From lokey with GNU General Public License v3.0 5 votes vote down vote up
def ssh(ctx, domain_name):
    """Get the public key for a SSH server.

    Example:

        $ lokey fetch ssh chat.shazow.net
    """

    class FetchKeyPolicy(paramiko.MissingHostKeyPolicy):
        def __init__(self):
            self.key = None

        def missing_host_key(self, client, hostname, key):
            self.key = key

    fetch_key_policy = FetchKeyPolicy()
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(fetch_key_policy)
    try:
        client.connect(domain_name, username='lokey', timeout=5)
        key = fetch_key_policy.key.public_numbers
        key = ErisPublic(e=key.e, n=key.n)
        print key.to('ssh')
    except Exception as e:
        msg = ('Got "{message}" when attempting '
               'to connect to {domain_name}').format(
            domain_name=domain_name,
            message=str(e))
        raise click.ClickException(msg) 
Example #24
Source File: ssh_util.py    From makemework with MIT License 5 votes vote down vote up
def connect(self):
        "Login to the remote server"
        try:
            #Paramiko.SSHClient can be used to make connections to the remote server and transfer files
            print("Establishing ssh connection...")
            self.client = paramiko.SSHClient()
            #Parsing an instance of the AutoAddPolicy to set_missing_host_key_policy() changes it to allow any host.
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            #Connect to the server
            if (self.password == ''):
                private_key = paramiko.RSAKey.from_private_key_file(self.pkey)
                self.client.connect(hostname=self.host, port=self.port, username=self.username,pkey=private_key ,timeout=self.timeout, allow_agent=False, look_for_keys=False)
                print("Connected to the server",self.host)
            else:
                self.client.connect(hostname=self.host, port=self.port,username=self.username,password=self.password,timeout=self.timeout, allow_agent=False, look_for_keys=False)    
                print("Connected to the server",self.host)
        except paramiko.AuthenticationException:
            print("Authentication failed, please verify your credentials")
            result_flag = False
        except paramiko.SSHException as sshException:
            print("Could not establish SSH connection: %s" % sshException)
            result_flag = False
        except socket.timeout as e:
            print("Connection timed out")
            result_flag = False
        except Exception as e:
            print('\nException in connecting to the server')
            print('PYTHON SAYS:',e)
            result_flag = False
            self.client.close()
        else:
            result_flag = True
        
        return result_flag 
Example #25
Source File: ssh.py    From django-webssh with Apache License 2.0 5 votes vote down vote up
def connect(self, host, user, password=None, ssh_key=None, port=22, timeout=30,
                term='xterm', pty_width=80, pty_height=24):
        try:
            ssh_client = paramiko.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            if ssh_key:
                key = get_key_obj(paramiko.RSAKey, pkey_obj=ssh_key, password=password) or \
                      get_key_obj(paramiko.DSSKey, pkey_obj=ssh_key, password=password) or \
                      get_key_obj(paramiko.ECDSAKey, pkey_obj=ssh_key, password=password) or \
                      get_key_obj(paramiko.Ed25519Key, pkey_obj=ssh_key, password=password)

                ssh_client.connect(username=user, hostname=host, port=port, pkey=key, timeout=timeout)
            else:
                ssh_client.connect(username=user, password=password, hostname=host, port=port, timeout=timeout)

            transport = ssh_client.get_transport()
            self.channel = transport.open_session()
            self.channel.get_pty(term=term, width=pty_width, height=pty_height)
            self.channel.invoke_shell()

            for i in range(2):
                recv = self.channel.recv(1024).decode('utf-8')
                self.message['status'] = 0
                self.message['message'] = recv
                message = json.dumps(self.message)
                self.websocker.send(message)
        except socket.timeout:
            self.message['status'] = 1
            self.message['message'] = 'ssh 连接超时'
            message = json.dumps(self.message)
            self.websocker.send(message)
            self.close()
        except:
            self.close() 
Example #26
Source File: tunnel.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
    """Function for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    """
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    try:
        client.connect(server, port, username=username, key_filename=keyfile,
                       look_for_keys=True, password=password)
#    except paramiko.AuthenticationException:
#        if password is None:
#            password = getpass("%s@%s's password: "%(username, server))
#            client.connect(server, port, username=username, password=password)
#        else:
#            raise
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server, port, e))
        sys.exit(1)

    # Don't let SIGINT kill the tunnel subprocess
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    try:
        forward_tunnel(lport, remoteip, rport, client.get_transport())
    except KeyboardInterrupt:
        print('SIGINT: Port forwarding stopped cleanly')
        sys.exit(0)
    except Exception as e:
        print("Port forwarding stopped uncleanly: %s"%e)
        sys.exit(255) 
Example #27
Source File: remote_shell.py    From margaritashotgun with MIT License 5 votes vote down vote up
def __init__(self, max_async_threads=2):
        """
        :type args: int
        :param args: maximun number of async command executors
        """

        self.jump_host_ssh = None
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.executor = ThreadPoolExecutor(max_workers=max_async_threads)
        self.futures = [] 
Example #28
Source File: ssh.py    From ARC with MIT License 5 votes vote down vote up
def _send_command_to_server(self, 
                                command: Union[str, list], 
                                remote_path: str = '',
                                ) -> Tuple[list, list]:
        """
        A wrapper for exec_command in paramiko.SSHClient. Send commands to the server. 

        Args:
            command (Union[str, list]): A string or an array of string commands to send.
            remote_path (Optional[str]): The directory path at which the command will be executed.

        Returns:
            Tuple[list, list]:
                - A list of lines of standard output stream.
                - A list of lines of the standard error stream.
        """
        if isinstance(command, list):
            command = '; '.join(command)
        if remote_path != '':
            # execute command in remote_path directory.
            # Check remote path existence, otherwise the cmd will be invalid
            # and even yield different behaviors.
            # Make sure to change directory back after the command is executed
            if self._check_dir_exists(remote_path):
                command = f'cd "{remote_path}"; {command}; cd '
            else:
                raise InputError(
                    f'Cannot execute command at given remote_path({remote_path})')
        try:
            _, stdout, stderr = self._ssh.exec_command(command)
        except Exception as e:  # SSHException: Timeout opening channel.
            logger.debug(f'ssh timed-out in the first trial. Got: {e}')
            try:  # try again
                _, stdout, stderr = self._ssh.exec_command(command)
            except Exception as e:
                logger.debug(f'ssh timed-out after two trials. Got: {e}')
                return ['', ], ['ssh timed-out after two trials', ]
        stdout = stdout.readlines()
        stderr = stderr.readlines()
        return stdout, stderr 
Example #29
Source File: test_ssh.py    From poseidon with MIT License 5 votes vote down vote up
def test_ps(client, mock):
    mock.patch.object(S.SSHClient, 'wait')
    client.ps()
    client.wait.assert_called_with('ps -Af', raise_on_error=True) 
Example #30
Source File: host_thread.py    From openmano with Apache License 2.0 5 votes vote down vote up
def ssh_connect(self):
        try:
            #Connect SSH
            self.ssh_conn = paramiko.SSHClient()
            self.ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh_conn.load_system_host_keys()
            self.ssh_conn.connect(self.host, username=self.user, timeout=10) #, None)
        except paramiko.ssh_exception.SSHException as e:
            text = e.args[0]
            print self.name, ": ssh_connect ssh Exception:", text