Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script remote execution using python

Tags:

python

shell

unix

Is there a way that I can use Python on Windows to execute shell scripts which are located on a remote Unix machine?

P.S: Sorry about the late edit. I do know of Paramiko, but I wanted to know if there is way of doing it without it. For starters, could it be done with subprocess()?

like image 637
fixxxer Avatar asked Sep 23 '10 17:09

fixxxer


People also ask

Can I use Python to execute shell commands?

Python allows you to execute shell commands, which you can use to start other programs or better manage shell scripts that you use for automation. Depending on our use case, we can use os. system() , subprocess. run() or subprocess.

How do I run a Python script remotely?

Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script.

Do SSH using Python?

Practical Data Science using PythonSSH or Secure Socket Shell, is a network protocol that provides a secure way to access a remote computer. Secure Shell provides strong authentication and secure encrypted data communications between two computers connecting over an insecure network such as the Internet.


2 Answers

You will need to ssh into the remote machine and if you have appropriate credentials, you can invoke the shell scripts.

For using ssh, you can easily use paramiko module that provides ssh automation

  • http://www.lag.net/paramiko/

A typical example:

import paramiko
import sys
import os
import os.path
passwd = ""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('servername', username, password=passwd)
stdin, stdout, stderr = ssh.exec_command('df -h')
x = stdout.readlines()
print x
for line in x:
    print line
ssh.close()

Replace "df -h" command with the your shell script.

like image 110
pyfunc Avatar answered Oct 20 '22 19:10

pyfunc


There is not any 'batteries included' module for remote shell execution in python. I'd suggest looking into Fabric , which provides a really nice interface for working through SSH on remote machines, probably a bit nicer than paramiko. You can even install Fabric on windows...

like image 28
ratmatz Avatar answered Oct 20 '22 19:10

ratmatz