U
    3d9                     @   s   d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ G dd deZG dd deZG d	d
 d
eZdd ZdddZdS )a   
The cmdshell module uses the paramiko package to create SSH connections
to the servers that are represented by instance objects. The module has
functions for running commands, managing files, and opening interactive
shell sessions over those connections.
    )interactive_shellN)StringIOc                   @   s~   e Zd ZdZd"ddZd#dd	Zd
d Zdd Zdd Zd$ddZ	dd Z
dd Zdd Zdd Zdd Zdd Zd d! ZdS )%	SSHClientae  
    This class creates a paramiko.SSHClient() object that represents
    a session with an SSH server. You can use the SSHClient object to send
    commands to the remote host and manipulate files on the remote host. 
    
    :ivar server: A Server object or FakeServer object.
    :ivar host_key_file: The path to the user's .ssh key files.
    :ivar uname: The username for the SSH connection. Default = 'root'.
    :ivar timeout: The optional timeout variable for the TCP connection.
    :ivar ssh_pwd: An optional password to use for authentication or for
                    unlocking the private key.
    ~/.ssh/known_hostsrootNc                 C   sp   || _ || _|| _|| _tjj|j|d| _t	 | _
| j
  | j
tj| | j
t  |   d S )N)password)serverhost_key_fileuname_timeoutparamikoZRSAKeyZfrom_private_key_filessh_key_file_pkeyr   _ssh_clientZload_system_host_keysZload_host_keysospath
expanduserZset_missing_host_key_policyZAutoAddPolicyconnect)selfr   r	   r
   timeoutssh_pwd r   8/tmp/pip-unpacked-wheel-d7dsrkjd/boto/manage/cmdshell.py__init__3   s    


zSSHClient.__init__   c              
   C   s   d}||k rz$| j j| jj| j| j| jd W dS  tjk
r } z4|j	\}}|dkrrt
d td |d7 }n W 5 d}~X Y q tjk
r   t
d| jj  t
d	 td
 |d7 }Y q tk
r   t
d td |d7 }Y qX qt
d dS )z
        Connect to an SSH server and authenticate with it.
        
        :type num_retries: int
        :param num_retries: The maximum number of connection attempts.
        r   )usernameZpkeyr   N)3   =   o   z/SSH Connection refused, will retry in 5 secondsr      z:%s has an entry in ~/.ssh/known_hosts and it doesn't matchzCEdit that file to remove the entry and then hit return to try againzHit Enter when readyz8Unexpected Error from SSH Connection, retry in 5 secondsz"Could not establish SSH connection)r   r   r   hostnamer
   r   r   socketerrorargsprinttimesleepr   ZBadHostKeyException	raw_inputEOFError)r   Znum_retriesretryZxxx_todo_changemevaluemessager   r   r   r   B   s4    



zSSHClient.connectc                 C   s
   | j  S )z
        Open an SFTP session on the SSH server.
        
        :rtype: :class:`paramiko.sftp_client.SFTPClient`
        :return: An SFTP client object.
        )r   	open_sftpr   r   r   r   r,   d   s    zSSHClient.open_sftpc                 C   s   |   }||| dS )a  
        Open an SFTP session on the remote host, and copy a file from
        the remote host to the specified path on the local host.
        
        :type src: string
        :param src: The path to the target file on the remote host.
        
        :type dst: string
        :param dst: The path on your local host where you want to
                    store the file.
        N)r,   getr   srcdstsftp_clientr   r   r   get_filem   s    zSSHClient.get_filec                 C   s   |   }||| dS )a  
        Open an SFTP session on the remote host, and copy a file from
        the local host to the specified path on the remote host.
        
        :type src: string
        :param src: The path to the target file on your local host.
        
        :type dst: string
        :param dst: The path on the remote host where you want to store
                    the file.
        N)r,   putr/   r   r   r   put_file|   s    zSSHClient.put_filerc                 C   s   |   }||||S )a  
        Open an SFTP session to the remote host, and open a file on
        that host.
        
        :type filename: string
        :param filename: The path to the file on the remote host.
        
        :type mode: string
        :param mode: The file interaction mode.
        
        :type bufsize: integer
        :param bufsize: The file buffer size.
        
        :rtype: :class:`paramiko.sftp_file.SFTPFile`
        :return: A paramiko proxy object for a file on the remote server.
        )r,   open)r   filenamemodebufsizer2   r   r   r   r8      s    zSSHClient.openc                 C   s   |   }||S )a=  
        List all of the files and subdirectories at the specified path
        on the remote host.
        
        :type path: string
        :param path: The base path from which to obtain the list.
          
        :rtype: list
        :return: A list of files and subdirectories at the specified path.
        )r,   listdir)r   r   r2   r   r   r   r<      s    zSSHClient.listdirc                 C   s$   |  d| }|d dr dS dS )a  
        Check the specified path on the remote host to determine if
        it is a directory.
        
        :type path: string
        :param path: The path to the directory that you want to check.
        
        :rtype: integer
        :return: If the path is a directory, the function returns 1.
                If the path is a file or an invalid path, the function
                returns 0.
        z[ -d %s ] || echo "FALSE"r   FALSEr   run
startswithr   r   statusr   r   r   isdir   s    zSSHClient.isdirc                 C   s$   |  d| }|d dr dS dS )aX  
        Check the remote host for the specified path, or a file
        at the specified path. This function returns 1 if the
        path or the file exist on the remote host, and returns 0 if
        the path or the file does not exist on the remote host.
        
        :type path: string
        :param path: The path to the directory or file that you want to check.
        
        :rtype: integer
        :return: If the path or the file exist, the function returns 1.
                If the path or the file do not exist on the remote host,
                the function returns 0.
        z[ -a %s ] || echo "FALSE"r   r=   r   r>   rA   r   r   r   exists   s    zSSHClient.existsc                 C   s   | j  }t| dS )zJ
        Start an interactive shell session with the remote host.
        N)r   Zinvoke_shellr   )r   channelr   r   r   shell   s    
zSSHClient.shellc                 C   s   t jd|| jjf  d}z| j|}W n tjk
rF   d}Y nX |d 	 }|d 	 }|d 
  |d 
  |d 
  t jd|  t jd|  |||fS )a^  
        Run a command on the remote host.
        
        :type command: string
        :param command: The command that you want to send to the remote host.

        :rtype: tuple
        :return: This function returns a tuple that contains an integer status,
                the stdout from the command, and the stderr from the command.

        running:%s on %sr   r      z
stdout: %sz
stderr: %s)botologdebugr   instance_idr   exec_commandr   ZSSHExceptionreadclose)r   commandrB   tZstd_outZstd_errr   r   r   r?      s    
zSSHClient.runc                 C   s<   t jd|| jjf  | j  }|  |	| |S )a8  
        Request a pseudo-terminal from a server, and execute a command on that
        server.

        :type command: string
        :param command: The command that you want to run on the remote host.
        
        :rtype: :class:`paramiko.channel.Channel`
        :return: An open channel object.
        rG   )
rI   rJ   rK   r   rL   r   get_transportZopen_sessionZget_ptyrM   )r   rP   rE   r   r   r   run_pty   s
    
zSSHClient.run_ptyc                 C   s    | j  }|  | j  dS )zQ
        Close an SSH session and any open channels that are tied to it.
        N)r   rR   rO   r   Zreset_cmdshell)r   	transportr   r   r   rO     s    
zSSHClient.close)r   r   NN)r   )r6   r7   )__name__
__module____qualname____doc__r   r   r,   r3   r5   r8   r<   rC   rD   rF   r?   rS   rO   r   r   r   r   r   &   s$         

"	
r   c                   @   sZ   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dd Zdd ZdS )LocalClientz
    :ivar server: A Server object or FakeServer object.
    :ivar host_key_file: The path to the user's .ssh key files.
    :ivar uname: The username for the SSH connection. Default = 'root'.
    Nr   c                 C   s   || _ || _|| _d S N)r   r	   r
   )r   r   r	   r
   r   r   r   r     s    zLocalClient.__init__c                 C   s   t || dS z<
        Copy a file from one directory to another.
        Nshutilcopyfiler   r0   r1   r   r   r   r3     s    zLocalClient.get_filec                 C   s   t || dS r[   r\   r_   r   r   r   r5      s    zLocalClient.put_filec                 C   s
   t |S )z
        List all of the files and subdirectories at the specified path.
        
        :rtype: list
        :return: Return a list containing the names of the entries
                in the directory given by path.
        )r   r<   r   r   r   r   r   r<   &  s    zLocalClient.listdirc                 C   s   t j|S )z
        Check the specified path to determine if it is a directory.
        
        :rtype: boolean
        :return: Returns True if the path is an existing directory.
        )r   r   rC   r`   r   r   r   rC   0  s    zLocalClient.isdirc                 C   s   t j|S )z
        Check for the specified path, or check a file at the specified path.
        
        :rtype: boolean
        :return: If the path or the file exist, the function returns True.
        )r   r   rD   r`   r   r   r   rD   9  s    zLocalClient.existsc                 C   s   t dd S )Nz$shell not supported with LocalClient)NotImplementedErrorr-   r   r   r   rF   B  s    zLocalClient.shellc                 C   s   t jd| j  t }tj| jdtjtjtjd}| dkrpt	
d | }||d  ||d  q4t j|  t jd|   |j| fS )z
        Open a subprocess and run a command on the local host.
        
        :rtype: tuple
        :return: This function returns a tuple that contains an integer status
                and a string with the combined stdout and stderr output.
        z
running:%sT)rF   stdinstdoutstderrNr   r   z
output: %s)rI   rJ   inforP   r   
subprocessPopenPIPEpollr%   r&   communicatewritegetvalue
returncode)r   Zlog_fpprocessrQ   r   r   r   r?   E  s     
zLocalClient.runc                 C   s   d S rZ   r   r-   r   r   r   rO   Z  s    zLocalClient.close)Nr   )rU   rV   rW   rX   r   r3   r5   r<   rC   rD   rF   r?   rO   r   r   r   r   rY     s   

		rY   c                   @   s   e Zd ZdZdd ZdS )
FakeServerae  
    This object has a subset of the variables that are normally in a
    :class:`boto.manage.server.Server` object. You can use this FakeServer
    object to create a :class:`boto.manage.SSHClient` object if you
    don't have a real Server object.
    
    :ivar instance: A boto Instance object.
    :ivar ssh_key_file: The path to the SSH key file.
    c                 C   s"   || _ || _|j| _| j j| _d S rZ   )instancer   Zdns_namer    idrL   )r   rp   r   r   r   r   r   g  s    zFakeServer.__init__N)rU   rV   rW   rX   r   r   r   r   r   ro   ]  s   	ro   c                 C   s.   t jddd}|| jkr"t| S t| S dS )a  
    Connect to the specified server.

    :return: If the server is local, the function returns a 
            :class:`boto.manage.cmdshell.LocalClient` object.
            If the server is remote, the function returns a
            :class:`boto.manage.cmdshell.SSHClient` object.
    ZInstancezinstance-idN)rI   configr.   rL   rY   r   )r   rL   r   r   r   startm  s    	
rs   r   r   c                 C   s   t | |}t||||S )a  
    Create and return an SSHClient object given an
    instance object.

    :type instance: :class`boto.ec2.instance.Instance` object
    :param instance: The instance object.

    :type ssh_key_file: string
    :param ssh_key_file: A path to the private key file that is 
                        used to log into the instance.

    :type host_key_file: string
    :param host_key_file: A path to the known_hosts file used
                          by the SSH client.
                          Defaults to ~/.ssh/known_hosts
    :type user_name: string
    :param user_name: The username to use when logging into
                      the instance.  Defaults to root.

    :type ssh_pwd: string
    :param ssh_pwd: The passphrase, if any, associated with
                    private key.
    )ro   r   )rp   r   r	   Z	user_namer   sr   r   r   sshclient_from_instance|  s    
ru   )r   r   N)rX   Zboto.mashups.interactiver   rI   r   r%   r]   r   r!   rf   Zboto.compatr   objectr   rY   ro   rs   ru   r   r   r   r   <module>   s$    jN    