Connect via SSH to another machine and run script

Asked

Viewed 973 times

0

I am automating tasks and I am new in Python, so I would like your help because I need to run a Shell script on another machine and this command I need to give inside a Python code.

I thought I’d wear something like:

 #!/usr/bin/python

 # -*- coding: utf8 -*- 
 import subprocess 

 subprocess.call('ssh user@host', shell=True)

But that’s why, because I don’t know how I would implement Login and Password (as well as "yes" of cryptography).

  • I think you will have to "study" a little more. If you have access to both machines the best thing to do is to work with keys rsa and configure the file ~/.ssh/config, so you don’t need to keep moving password, user name and not even host address, so make it easy for once your life use the Fabric and be happy.

  • I forgot to mention the plumbum, in case you want to go the way seemingly easier.

1 answer

0


I imagine you want to make an SSH connection via python. If so, the pxssh module does exactly what you want. For example, to run 'ls -l' and to print the output, you need to do something like this:

import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
    print "SSH falha no login."
    print str(s)
else:
    print "SSH sucesso no login"
    s.sendline ('ls -l')
    s.prompt()         
    print s.before     
    s.logout()

Some useful links:

http://dsnra.jpl.nasa.gov/software/Python/site-packages/Contrib/pxssh.html http://www.noah.org/wiki/pexpect

  • I did this what you said and used the rsa keys. It really helped a lot. The difficulty now is to run the linux commands inside the machine that was accessed. Meu código simples ficou assim:&#xA;&#xA;##############################################&#xA;#! /usr/bin/python&#xA;# -- coding: utf8 -- import subprocess subprocess.call('echo Running Shell inside Python', shell=True) subprocess.call('ssh <user>@<localhost>', shell=True) subprocess.call('echo I’m in <localhost>', shell=True) ###################################################Xa;; It accesses the machine, but inside it does not echo.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.