Paramiko is a Python implementation of SSH with a whole range of supported features. To start, let’s look at the most simple example – connecting to a remote SSH server and gathering the output of ls /tmp/
import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect('localhost', username='testuser', password='t3st@#test123') except paramiko.SSHException: print "Connection Failed" quit() stdin,stdout,stderr = ssh.exec_command("ls /etc/") for line in stdout.readlines(): print line.strip() ssh.close()
After importing paramiko, we create a new variable ‘ssh’ to hold our SSHClient. ssh.set_missing_host_key_policy automatically adds our server’s host key without prompting. For security, this is not a good idea in production, and host keys should be added manually. Should a host key change unexpectedly, it could indicate that the connection has been compromised and is being diverted elsewhere.
Next, we create 3 variables, stdin, stdout and stderr allowing us to access the respective streams when calling ls /etc/
Finally, for each “\n” terminated line on stdout, we print the line, stripping the trailing “\n” (as print adds one). Finally we close the SSH connection.
Let’s look at another example, where we communicate with stdin.
Read the rest of this entry »