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()