当前位置: 首页>>代码示例>>Python>>正文


Python Transport.connect方法代码示例

本文整理汇总了Python中paramiko.Transport.connect方法的典型用法代码示例。如果您正苦于以下问题:Python Transport.connect方法的具体用法?Python Transport.connect怎么用?Python Transport.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在paramiko.Transport的用法示例。


在下文中一共展示了Transport.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sftp_server

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
def sftp_server():
    """
    Set up an in-memory SFTP server thread. Yields the client Transport/socket.

    The resulting client Transport (along with all the server components) will
    be the same object throughout the test session; the `sftp` fixture then
    creates new higher level client objects wrapped around the client
    Transport, as necessary.
    """
    # Sockets & transports
    socks = LoopSocket()
    sockc = LoopSocket()
    sockc.link(socks)
    tc = Transport(sockc)
    ts = Transport(socks)
    # Auth
    host_key = RSAKey.from_private_key_file(_support("test_rsa.key"))
    ts.add_server_key(host_key)
    # Server setup
    event = threading.Event()
    server = StubServer()
    ts.set_subsystem_handler("sftp", SFTPServer, StubSFTPServer)
    ts.start_server(event, server)
    # Wait (so client has time to connect? Not sure. Old.)
    event.wait(1.0)
    # Make & yield connection.
    tc.connect(username="slowdive", password="pygmalion")
    yield tc
开发者ID:gaudenz,项目名称:paramiko,代码行数:30,代码来源:conftest.py

示例2: __init__

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
class SshConnection:
    """ tsc ssh connection """

    def __init__(self, name, host, port=22, user=None, password=None):
        """ init """

        self.connection = None
        self.session = None
        self.host = host
        self.port = port
        self.loginAccount = {
            'user': user,
            'pass': password
        }
        self.name = name
        self.timeout = 4

        self.nbytes = 4096

        try:
            self.connection =  Transport((self.host, self.port))
            self.connection.connect(username=self.loginAccount['user'],
                                    password=self.loginAccount['pass'])
            self.connection.set_keepalive(self.timeout)
            self.session = self.connection.open_channel(kind='session')

            print('ssh connection created!')
        except Exception, e:
            self.__del__()
            print('ssh connection failed: {er}'.format(er=e))
开发者ID:TMCUSER,项目名称:twister.github.io,代码行数:32,代码来源:TscSshLib.py

示例3: write_redirects_to_sftp

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
    def write_redirects_to_sftp(self, from_path, to_path, cron):
        try:
            ssh_key_object = RSAKey(filename=app.config['SFTP_SSH_KEY_PATH'],
                                    password=app.config['SFTP_SSH_KEY_PASSPHRASE'])

            remote_server_public_key = HostKeyEntry.from_line(app.config['SFTP_REMOTE_HOST_PUBLIC_KEY']).key
            # This will throw a warning, but the (string, int) tuple will automatically be parsed into a Socket object
            remote_server = Transport((app.config['SFTP_REMOTE_HOST'], 22))
            remote_server.connect(hostkey=remote_server_public_key, username=app.config['SFTP_USERNAME'], pkey=ssh_key_object)

            sftp = SFTPClient.from_transport(remote_server)
            sftp.put(from_path, to_path)
            if cron:
                return 'SFTP publish from %s to %s succeeded' % (from_path, to_path)
            else:
                return fjson.dumps({
                    'type': 'success',
                    'message': 'Redirect updates successful'
                })
        except:
            if cron:
                return 'SFTP publish from %s to %s failed' % (from_path, to_path)
            else:
                return fjson.dumps({
                    'type': 'danger',
                    'message': 'Redirect updates failed'
                })
开发者ID:betheluniversity,项目名称:tinker,代码行数:29,代码来源:tinker_controller.py

示例4: TransportTest

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
class TransportTest(ParamikoTest):
    def setUp(self):
        self.socks = LoopSocket()
        self.sockc = LoopSocket()
        self.sockc.link(self.socks)
        self.tc = Transport(self.sockc)
        self.ts = Transport(self.socks)

    def tearDown(self):
        self.tc.close()
        self.ts.close()
        self.socks.close()
        self.sockc.close()

    def setup_test_server(self, client_options=None, server_options=None):
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')

        public_host_key = RSAKey(data=bytes(host_key))
        self.ts.add_server_key(host_key)
        
        if client_options is not None:
            client_options(self.tc.get_security_options())
        if server_options is not None:
            server_options(self.ts.get_security_options())
        
        event = threading.Event()
        self.server = NullServer()
        self.assert_(not event.isSet())
        self.ts.start_server(event, self.server)

        self.tc.connect(hostkey=public_host_key,
                        username='slowdive', password='pygmalion')

        event.wait(1.0)
        self.assert_(event.isSet())
        self.assert_(self.ts.is_active())

    def test_1_security_options(self):
        o = self.tc.get_security_options()
        self.assertEquals(type(o), SecurityOptions)
        self.assert_((b'aes256-cbc', b'blowfish-cbc') != o.ciphers)
        o.ciphers = (b'aes256-cbc', b'blowfish-cbc')
        self.assertEquals((b'aes256-cbc', b'blowfish-cbc'), o.ciphers)
        try:
            o.ciphers = (b'aes256-cbc', b'made-up-cipher')
            self.assert_(False)
        except ValueError:
            pass
        try:
            o.ciphers = 23
            self.assert_(False)
        except TypeError:
            pass
            
    def test_2_compute_key(self):
        self.tc.K = 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929
        self.tc.H = unhexlify(b'0C8307CDE6856FF30BA93684EB0F04C2520E9ED3')
        self.tc.session_id = self.tc.H
        key = self.tc._compute_key(b'C', 32)
        self.assertEquals(b'207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995',
                          hexlify(key).upper())

    def test_3_simple(self):
        """
        verify that we can establish an ssh link with ourselves across the
        loopback sockets.  this is hardly "simple" but it's simpler than the
        later tests. :)
        """
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = RSAKey(data=bytes(host_key))
        self.ts.add_server_key(host_key)
        event = threading.Event()
        server = NullServer()
        self.assert_(not event.isSet())
        self.assertEquals(None, self.tc.get_username())
        self.assertEquals(None, self.ts.get_username())
        self.assertEquals(False, self.tc.is_authenticated())
        self.assertEquals(False, self.ts.is_authenticated())
        self.ts.start_server(event, server)
        self.tc.connect(hostkey=public_host_key,
                        username='slowdive', password='pygmalion')
        event.wait(1.0)
        self.assert_(event.isSet())
        self.assert_(self.ts.is_active())
        self.assertEquals('slowdive', self.tc.get_username())
        self.assertEquals('slowdive', self.ts.get_username())
        self.assertEquals(True, self.tc.is_authenticated())
        self.assertEquals(True, self.ts.is_authenticated())

    def test_3a_long_banner(self):
        """
        verify that a long banner doesn't mess up the handshake.
        """
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = RSAKey(data=bytes(host_key))
        self.ts.add_server_key(host_key)
        event = threading.Event()
        server = NullServer()
        self.assert_(not event.isSet())
        self.socks.send(LONG_BANNER)
#.........这里部分代码省略.........
开发者ID:bepetersn,项目名称:paramiko,代码行数:103,代码来源:test_transport.py

示例5: __init__

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
class SFTPCopy:
    def __init__(self, host, port, username, password):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.t = Transport((self.host, self.port))
        self.t.connect(username=self.username, password=self.password)   # 注意:此处需要用默认传参方式传参
        self.sftp = SFTPClient.from_transport(self.t)

    def copyData(self, localdir, remotedir):

        for (root, dirs, files) in walk(localdir):
            for dir in dirs:
                dest = path.join(remotedir, root[len(localdir):][1:], dir)
                try:
                    self.sftp.mkdir(dest)
                except Exception as e:
                    print('ERROR: make directory %s %s' % (dest, e))
            for file in files:
                src = path.join(root, file)
                dest = path.join(remotedir, root[len(localdir):][1:], file)
                try:
                    self.sftp.put(src, dest)
                except Exception as e:
                    print('ERROR: touch file %s %s' % (dest, e))
开发者ID:movekj,项目名称:library-study,代码行数:28,代码来源:test.py

示例6: scp

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
 def scp(self, srcFile, destPath):
     transport = Transport((self.host, int(self.port)))
     transport.connect(username=self.user, password=self.passwd)
     sftp = SFTPClient.from_transport(transport)
     try:
         sftp.put(srcFile, destPath)
     except IOError as e:
         raise e
开发者ID:MountHuang,项目名称:cloudstack,代码行数:10,代码来源:sshClient.py

示例7: sftpOpenConnection

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
 def sftpOpenConnection(self, target):
     """ opens an sftp connection to the given target host;
         credentials are taken from /etc/ssh/sftp_passwd """
     from paramiko import Transport, SFTPClient
     from paramiko.util import load_host_keys
     hostname, username, password = self.getCredentials(target)
     hostkeys = load_host_keys('/etc/ssh/ssh_known_hosts')
     hostkeytype, hostkey = hostkeys[hostname].items()[0]
     trans = Transport((hostname, 22))
     trans.connect(username=username, password=password, hostkey=hostkey)
     return SFTPClient.from_transport(trans)
开发者ID:a25kk,项目名称:mp-bbb,代码行数:13,代码来源:TT_NewsletterTool.py

示例8: _createConnection

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
    def _createConnection(self):
        """
        @see: L{_createConnection<datafinder.persistence.common.connection.pool.ConnectionPool._createConnection>}
        """

        try:
            connection = Transport((self._configuration.hostname, DEFAULT_SSH_PORT))
            connection.connect(username=self._configuration.username, password=self._configuration.password)
            return connection
        except (SSHException, socket.error, socket.gaierror), error:
            errorMessage = u"Unable to establish SSH connection to TSM host '%s'! " \
                           % (self._configuration.hostname) + "\nReason: '%s'" % str(error)
            raise PersistenceError(errorMessage)
开发者ID:DLR-SC,项目名称:DataFinder,代码行数:15,代码来源:connection_pool.py

示例9: sftpOpen

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
 def sftpOpen(self, target):
     """ opens an sftp connection to the given target host;
         credentials are taken from /etc/ssh/sftp_passwd """
     from paramiko import Transport, SFTPClient
     #from paramiko.util import load_host_keys
     print '>>> sftpOpen self.username: ', self.username
     print '             self.password: ', self.password
     print '             self.hostkey: ', self.password
     print '             self.hostname: ', self.hostname
     trans = Transport((self.hostname, 22))
     trans.banner_timeout = 120
     trans.connect(username=self.username,
                   password=self.password,
                   hostkey=self.hostkey)
     return SFTPClient.from_transport(trans)
开发者ID:a25kk,项目名称:mp-bbb,代码行数:17,代码来源:TT_NewsletterTool.py

示例10: listdir

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
def listdir(hostname, path="/var/tmp", filter="", port=1035, username="", password=""):
    """
        paramiko sftp listdir wrapper, with option to filter files
    """
    # Paramiko client configuration

    t = Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = SFTPClient.from_transport(t)

    try:
        rex = re.compile(filter)
    except:
        print "Invalid regular expression: " + filter
        sys.exit(1)

    return [x for x in sftp.listdir(path) if rex.match(x)]
开发者ID:stonefury,项目名称:devops,代码行数:19,代码来源:gatherlogs.py

示例11: upload_report_to_sftp

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
    def upload_report_to_sftp(self, client_id, report_date, absolute_filename):
        """
        Upload the given file, using SFTP, to the configured FTP server. The
        file should be uploaded to the appropriate directory for the specified
        client and the date of the report.
        """
        try:
            client = Clients.objects.get(id=client_id)
        except Clients.DoesNotExist:
            logger.exception(u'No configuration for client {0}.'.format(client_id))
            raise

        filename = basename(absolute_filename)
        base_folder, env_folder, year_folder, month_folder = self._get_sftp_dirs(client, report_date)

        try:
            logger.debug(u'SFTP logging on to {0} as {1}'.format(settings.SFTP_SERVER, settings.SFTP_USERNAME))
            transport = Transport((settings.SFTP_SERVER, settings.SFTP_PORT))
            transport.connect(username=settings.SFTP_USERNAME, password=settings.SFTP_PASSWORD)
            sftp = SFTPClient.from_transport(transport)

            logger.debug(u'SFTP dir {0}/{1}/{2}/{3}'.format(base_folder, env_folder, year_folder, month_folder))
            sftp.chdir(base_folder)
            self._make_or_change_sftp_dir(sftp, env_folder)
            self._make_or_change_sftp_dir(sftp, year_folder)
            self._make_or_change_sftp_dir(sftp, month_folder)

            logger.debug(u'SFTP uploading {0}'.format(filename))
            sftp.put(absolute_filename, filename)
        except Exception:
            logger.exception(u'Unrecoverable exception during SFTP upload process.')
            raise
        finally:
            logger.debug(u'SFTP logging off')

            try:
                sftp.close()
            except Exception:
                logger.exception(u'SFTP exception while closing SFTP session.')

            try:
                transport.close()
            except Exception:
                logger.exception(u'SFTP exception while closing SSH connection.')
开发者ID:simonchapman1986,项目名称:ripe,代码行数:46,代码来源:build_csv.py

示例12: sftp_connect

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
def sftp_connect(config):
    try:
        hostname = config["hostname"]
        port = int(config["port"])
        username = config["username"]
        pkeyfile = config["privatekey_file"]
        pkeypassword = config["privatekey_passphrase"]
        host_keys = load_host_keys(config["hostkeys_file"])
        hostkeytype, hostkey = get_hostkeytype_and_hostkey(host_keys,
                                                           config["hostname"])
        t = Transport((hostname, port))
        pkey = get_privatekey_from_file(pkeyfile, pkeypassword) 
        t.connect(username=username, pkey=pkey, hostkey=hostkey)

        return SFTPClient.from_transport(t)

    except SSHException, e:
        print " [*] " + str(e)
        sys.exit(1)
开发者ID:marant,项目名称:hackcam,代码行数:21,代码来源:hackcam.py

示例13: SFTP

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
class SFTPConnection:
  """
  Handle a SFTP (SSH over FTP) Connection
  """

  def __init__(self, url, user_name, password=None, private_key=None):
    self.url = url
    self.user_name = user_name
    if password and private_key:
      raise SFTPError("Password and private_key cannot be defined simultaneously")
    self.password = password
    self.private_key = private_key

  def connect(self):
    """ Get a handle to a remote connection """
    # Check URL
    schema = urlparse(self.url)
    if schema.scheme == 'sftp':
      self.transport = Transport((schema.hostname, int(schema.port)))
    else:
      raise SFTPError('Not a valid sftp url %s, type is %s' %(self.url, schema.scheme))
    # Add authentication to transport
    try:
      if self.password:
        self.transport.connect(username=self.user_name, password=self.password)
      elif self.private_key:
        self.transport.connect(username=self.user_name,
                               pkey=RSAKey.from_private_key(StringIO(self.private_key)))
      else:
        raise SFTPError("No password or private_key defined")
      # Connect
      self.conn = SFTPClient.from_transport(self.transport)
    except (socket.gaierror,error), msg:
      raise SFTPError(str(msg) + ' while establishing connection to %s' % (self.url,))
    # Go to specified directory
    try:
      schema.path.rstrip('/')
      if len(schema.path):
        self.conn.chdir(schema.path)
    except IOError, msg:
      raise SFTPError(str(msg) + ' while changing to dir -%r-' % (schema.path,))
开发者ID:klebergraciasoares,项目名称:erp5,代码行数:43,代码来源:SFTPConnection.py

示例14: RemoteFileManager

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
class RemoteFileManager(object):
    def __init__(self, host, user, password, port=22):
        self._host = host
        self._port = port
        self._user = user
        self._pass = password

    def connect(self):
        self._transport = Transport((self._host, self._port))
        self._transport.connect(username=self._user, password=self._pass)
        self._client = SFTPClient.from_transport(self._transport)

    def files(self, path=None):
        path = '' if path is None else path
        return self._client.listdir(path)

    def file_text(self, path):
        return self._client.open(path, 'r').readlines()

    def lock_wait(self, path, sleep_time=3):
        while True:
            try:
                self._client.open(path, 'r')
                print('Waiting for lock on sums file to be released...')
                sleep(sleep_time)
            except Exception:
                ## No lock file present on remote
                break

    def file_iter(self, path):
        try:
            self._client.stat(path)
        except IOError:
            with self._client.open(path, 'w') as remote_file:
                remote_file.close()

        for line in self._client.open(path, 'r'):
            yield line
开发者ID:briancline,项目名称:siphon,代码行数:40,代码来源:manager.py

示例15: get_sftp_conn

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import connect [as 别名]
def get_sftp_conn(config):
    """Make a SFTP connection, returns sftp client and connection objects"""
    remote = config.get('remote_location')
    parts = urlparse(remote)

    if ':' in parts.netloc:
        hostname, port = parts.netloc.split(':')
    else:
        hostname = parts.netloc
        port = 22
    port = int(port)

    username = config.get('remote_username') or getuser()
    luser = get_local_user(username)
    sshdir = get_ssh_dir(config, luser)
    hostkey = get_host_keys(hostname, sshdir)

    try:
        sftp = None
        keys = get_ssh_keys(sshdir)
        transport = Transport((hostname, port))
        while not keys.empty():
            try:
                key = PKey.from_private_key_file(keys.get())
                transport.connect(
                    hostkey=hostkey,
                    username=username,
                    password=None,
                    pkey=key)
                sftp = SFTPClient.from_transport(transport)
                break
            except (PasswordRequiredException, SSHException):
                pass
        if sftp is None:
            raise SaChannelUpdateTransportError("SFTP connection failed")
        return sftp, transport
    except BaseException as msg:
        raise SaChannelUpdateTransportError(msg)
开发者ID:akissa,项目名称:sachannelupdate,代码行数:40,代码来源:transports.py


注:本文中的paramiko.Transport.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。