Hola!

You've found my spot on the internet that's all about me. I put together this little site to show off my work and keep track of my various projects.

Python and SSH

A majority of the python scripts and projects that I work on, there is a need for an ssh connection. Paramiko is my friend.

import paramiko, os

address = '127.0.0.1'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

#Testing if we can ping then SSH to the endpoint
try:
    print 'Pinging ' + address
    response = os.system("ping -c 1 " + address)
        
    if response == 0:
        print 'Connection up. Testing credentials.'
        ssh.connect(address, username=user, password=password)
        print 'Credentials are good.'
        
    else:
        print 'Connection down'
        return False
        
except (paramiko.BadHostKeyException, paramiko.AuthenticationException, 
    paramiko.SSHException, socket.error) as e:
    print e

This sets up the connection as the variable ssh. To work with it, I’ll do something like this.

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('my_command')

print ssh_stdout.read()

Leave a Reply

Your email address will not be published. Required fields are marked *