Thursday, February 5, 2015

[Python] Using SSH with Python

  Do you want to use ssh in python? I needed to do! I use server hosting, but there is no authority for using crontab. Beacause of that I need ssh in python! In my server I can use crontab so I can write my script using ssh with python. After that I registered that script in my crontab. Now I can fulfill my purpose through that script.

  We need paramiko module for using ssh in python. Let's install paramiko

$ pip install paramiko

  Then we will get paramiko.

  For now, write python code!

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("yourserver.com",username='your_id',password='your_passwords')
stdin, stdout, stderr = ssh.exec_command("command what you want to execute");

  Can you understand this? Import paramiko module and create paramiko SSHClient object with name ssh. And set AutoAddPolicy. When you access some server with ssh first time. You can see the message "do you trust this host and use connection?" like that. AutoAddPolicy is for that, it will trust host automatically. Next, you have to access to a server computer with connection function. After that you can execute shell command with exec_command function.

  If you need to print out result. Use "stdout.readlines()"

  Did you execute this? Let's do this!

No comments:

Post a Comment