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


Python Transport.open_channel方法代码示例

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


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

示例1: __init__

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import open_channel [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

示例2: TransportTest

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import open_channel [as 别名]

#.........这里部分代码省略.........
        chan = self.tc.open_session()
        chan.exec_command('yes')
        schan = self.ts.accept(1.0)
        schan.send(b'Hello there.\n')
        schan.send_stderr(b'This is on stderr.\n')
        schan.close()

        chan.set_combine_stderr(True)        
        f = chan.makefile()
        self.assertEquals(b'Hello there.\n', f.readline())
        self.assertEquals(b'This is on stderr.\n', f.readline())
        self.assertEquals(b'', f.readline())

    def test_7_invoke_shell(self):
        """
        verify that invoke_shell() does something reasonable.
        """
        self.setup_test_server()
        chan = self.tc.open_session()
        chan.invoke_shell()
        schan = self.ts.accept(1.0)
        chan.send(b'communist j. cat\n')
        f = schan.makefile()
        self.assertEquals(b'communist j. cat\n', f.readline())
        chan.close()
        self.assertEquals(b'', f.readline())

    def test_8_channel_exception(self):
        """
        verify that ChannelException is thrown for a bad open-channel request.
        """
        self.setup_test_server()
        try:
            chan = self.tc.open_channel(b'bogus')
            self.fail('expected exception')
        except ChannelException as x:
            self.assert_(x.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED)

    def test_9_exit_status(self):
        """
        verify that get_exit_status() works.
        """
        self.setup_test_server()

        chan = self.tc.open_session()
        schan = self.ts.accept(1.0)
        chan.exec_command('yes')
        schan.send(b'Hello there.\n')
        self.assert_(not chan.exit_status_ready())
        # trigger an EOF
        schan.shutdown_read()
        schan.shutdown_write()
        schan.send_exit_status(23)
        schan.close()
        
        f = chan.makefile()
        self.assertEquals(b'Hello there.\n', f.readline())
        self.assertEquals(b'', f.readline())
        count = 0
        while not chan.exit_status_ready():
            time.sleep(0.1)
            count += 1
            if count > 50:
                raise Exception("timeout")
        self.assertEquals(23, chan.recv_exit_status())
        chan.close()
开发者ID:bepetersn,项目名称:paramiko,代码行数:70,代码来源:test_transport.py

示例3: TransportTest

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import open_channel [as 别名]

#.........这里部分代码省略.........
        """
        self.setup_test_server()

        with self.tc.open_session() as chan:
            with self.ts.accept(1.0) as schan:
                chan.exec_command('yes')
                schan.send('Hello there.\n')
                schan.close()

                f = chan.makefile()
                self.assertEqual('Hello there.\n', f.readline())
                self.assertEqual('', f.readline())

    def test_7_invoke_shell(self):
        """
        verify that invoke_shell() does something reasonable.
        """
        self.setup_test_server()
        chan = self.tc.open_session()
        chan.invoke_shell()
        schan = self.ts.accept(1.0)
        chan.send('communist j. cat\n')
        f = schan.makefile()
        self.assertEqual('communist j. cat\n', f.readline())
        chan.close()
        self.assertEqual('', f.readline())

    def test_8_channel_exception(self):
        """
        verify that ChannelException is thrown for a bad open-channel request.
        """
        self.setup_test_server()
        try:
            chan = self.tc.open_channel('bogus')
            self.fail('expected exception')
        except ChannelException as e:
            self.assertTrue(e.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED)

    def test_9_exit_status(self):
        """
        verify that get_exit_status() works.
        """
        self.setup_test_server()

        chan = self.tc.open_session()
        schan = self.ts.accept(1.0)
        chan.exec_command('yes')
        schan.send('Hello there.\n')
        self.assertTrue(not chan.exit_status_ready())
        # trigger an EOF
        schan.shutdown_read()
        schan.shutdown_write()
        schan.send_exit_status(23)
        schan.close()

        f = chan.makefile()
        self.assertEqual('Hello there.\n', f.readline())
        self.assertEqual('', f.readline())
        count = 0
        while not chan.exit_status_ready():
            time.sleep(0.1)
            count += 1
            if count > 50:
                raise Exception("timeout")
        self.assertEqual(23, chan.recv_exit_status())
        chan.close()
开发者ID:jaraco,项目名称:paramiko,代码行数:70,代码来源:test_transport.py

示例4: SSH

# 需要导入模块: from paramiko import Transport [as 别名]
# 或者: from paramiko.Transport import open_channel [as 别名]
class SSH(object):
    """Wrapper for Paramiko Transport and Channel for Expect-like sessions"""

    def __init__(self, user, passwd = ""):
        """initialize SSH wrapper but do not connect"""
        self.user = user
        self.passwd = passwd
        self.prompt_re = "([a-z][email protected][a-zA-Z0-9\.\-\_]+[>#%])"
        self.reset_timeout_on_newlines = True
        self._timeout_sec = 10
        self.quiet = 0
        self.received_text = ""

    def connect(self, hostname_address):
        """connect to SSH target using paramiko Transport/Channel"""
        self._transport = Transport(hostname_address)
        self._transport.connect(username=self.user, password=self.passwd)
        self.ssh_channel = self._transport.open_channel("session")
        self.pty = self.ssh_channel.get_pty()
        self.ssh_channel.invoke_shell()
        self.wait_for_prompt()
        self.ssh_channel.send("set cli screen-length 0")

    def txrx_status(self):
        """returns send and receive status as string formatted for screen"""
        chan = self.ssh_channel
        return "Send Ready: {}, Receive Ready: {}".format(chan.send_ready(), chan.recv_ready())

    @property
    def timeout(self):
        """timeout_sec getter"""
        return self._timeout_sec

    @timeout.setter
    def timeout(self, new_timeout_sec):
        """timeout_sec setter"""
        self._timeout_sec = new_timeout_sec

    def wait_for_prompt(self):
        """call self.wait_for_regex using self.prompt_re as argument"""
        return self.wait_for_regex(self.prompt_re)

    def wait_for_regex(self, expression, wait_sec=0.1):
        """
            Loop receive and wait until a regular expression is matched in output
             - raise an exception if we hit the timeout
        """
        chan = self.ssh_channel
        done = False
        start_time = time.clock()
        while ((time.clock() - start_time) <= self.timeout) and not done:
            time.sleep(wait_sec)
            if chan.recv_ready():
                while chan.recv_ready():
                    this_receive = chan.recv(1024)
                    self.received_text = self.received_text + this_receive
                    # print to screen if quiet is not set
                    if not self.quiet:
                        stdout.write(this_receive)
                        stdout.flush()
                # reset the start_time if we encounter newlines and self.reset_timeout_on_newlines is True
                if re.search("\n",self.received_text) and self.reset_timeout_on_newlines:
                    start_time = time.clock()
            #else:
                #if not chan.recv_ready, then do nothing
            done = re.search(expression, self.received_text)
        # if done is not True at this point, we consider it to be a timeout action
        if not done:
            raise NetDevError("Timeout waiting for expression match: '{}'".format(expression))
        else:
            return self.received_text

    def _sendline(self, line):
        """send a single line"""
        chan = self.ssh_channel
        if chan.send_ready():
            chan.send(line.strip() + "\n")
        else:
            raise NetDevError("Attempted to send when send not ready")

    def send(self, textblock):
        """work through a textblock and send one line at at time"""
        configtext = textblock.strip()
        for line in textblock.splitlines():
            self._sendline(line)
            self.received_text = ""
            self.wait_for_prompt()
        self.received_text = ""
开发者ID:francisluong,项目名称:python-netdev,代码行数:90,代码来源:__init__.py


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