How to connect to localhost using Python's paramiko?
Question: I am totally new to implementing client-server communication and am trying to
get started with a very basic example using Python's paramiko module. All I
want to do is to send a simple string to my machine's localhost from one
terminal window and retrieve it from there in another terminal window.

This is what I have so far:

    
    
    import paramiko
    
    ssh = paramiko.SSHClient()
    
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    ssh.connect(hostname='localhost', username='myun', password='mypwd')
    
    stdin, stdout, stderr = ssh.exec_command('echo "Hello"')
    
    print stdout
    
    ssh.close()
    

What is get is this:

    
    
    Traceback (most recent call last):
      File "./ssh.py", line 13, in <module>
        ssh.connect(hostname='localhost', username='myun', password='mypwd')
      File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 251, in connect
        retry_on_signal(lambda: sock.connect(addr))
      File "/usr/local/lib/python2.7/site-packages/paramiko/util.py", line 270, in retry_on_signal
        return function()
      File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 251, in <lambda>
        retry_on_signal(lambda: sock.connect(addr))
      File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
        return getattr(self._sock,name)(*args)
    socket.error: [Errno 61] Connection refused
    

Can anybody please advise where I am going wrong here? Why can't I connect to
localhost using my correct username and password?


Answer: This should connect properly if SSH is accepting connections on localhost.
OpenSSH does by default. Check /etc/ssh/sshd_config and your firewall. Another
possibility is that "localhost" isn't configured properly in /etc/hosts. Try
with 127.0.0.1 or ::1.

Note that to get the actual stdout, use:

    
    
    print stdout.read()
    

