Using Channels with Paramiko

泄露秘密 提交于 2019-11-30 21:02:28

问题


I am working on converting a tool from Ruby to Python, and the Ruby version uses Net::SSH to connect to a remote host, and send commands and retrieve responses/data. I have been using paramiko in the Python counterpart, but I'm confused as to the purpose of Channels in paramiko. From what I've read so far, it seems to me that a channel (which uses a paramiko Transport) is used to keep a persistent connection to SSH rather than executing a command and then terminating the connection.

Is a Channel required? What is the stack required to open a persistent SSH connection to a host as to send and receive multiple commands sequentially and get the responses, then when finished manually close the connection?

These are the two main lines I'm having trouble translating into Python, because I'm not sure if a Ruby "Channel" directly maps to a paramiko "Channel":

@ssh_connection = Net::SSH.start(@linux_server_name, 
                        @server_user_name, 
                        :password => @password, 
                        :paranoid => false)

and later on in the code

@channel = @ssh_connection.open_channel do |new_channel|

Edit: To further explain my question, I was able to connect to a remote host using paramiko and execute multiple sequential commands and get their results without using a transport or a channel, so again, what are the reasons for using a Channel in paramiko?

def connect(self):
    ssh_connection = paramiko.SSHClient()
    ssh_connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_connection.connect(self.linux_server_name)
    stdin, stdout, stderr = ssh_connection.exec_command("ls -l")
    print(stdout.readlines())
    stdin, stdout, stderr = ssh_connection.exec_command("ls -l /tmp")
    print(stdout.readlines())
    ssh_connection.close()

回答1:


exec_command() is enough if the SSH server supports running commands (like ssh user@host "cmd; cmd; ...". But some SSH servers (e.g. network devices like switches, routers, ...) only supports starting an interactive session. Then you need to use invoke_shell() which returns a Channel.

Transport and Channel are all SSH terms (other than Paramiko's). See following RFCs for more info:

  • rfc4251 - The SSH Protocol Architecture
  • rfc4252 - The SSH Authentication Protocol
  • rfc4253 - The SSH Transport Layer Protocol
  • rfc4254 - The SSH Connection Protocol


来源:https://stackoverflow.com/questions/45508213/using-channels-with-paramiko

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!