dcheng
dcheng

Reputation: 1847

How to pass Unix Commands across network using python

So basically I have this remote computer with a bunch of files. I want to run unix commands (such as ls or cat) and receive them locally.

Currently I have connected via python's sockets (I know the IP address of remote computer). But doing:

data = None
message = "ls\n"
sock.send(message)
while not data:
    data = sock.recv(1024) <- stalls here forever
    ...

is not getting me anything.

Upvotes: 1

Views: 126

Answers (3)

Ehtesh Choudhury
Ehtesh Choudhury

Reputation: 7790

This is what I did for your situation.

In terminal 1, I set up a remote shell over a socket using ncat, a nc variant:

$ ncat -l -v 50007 -e /bin/bash

In terminal 2, I connect to the socket with this Python code:

$ cat python-pass-unix-commands-socket.py

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 50007))

sock.send('ls\n')
data = sock.recv(1024)
print data
sock.close()

$ python pass-unix-commands-socket.py

This is the output I get in terminal 1 after running the command:

Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Listening on :::50007
Ncat: Listening on 0.0.0.0:50007
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:39507.
$

And in terminal 2:

$ python pass-unix-commands-socket.py
alternating-characters.in
alternating-characters.rkt
angry-children.in
angry-children.rkt
angry-professor.in
angry-professor.rkt
$

Upvotes: 0

TerminalWitchcraft
TerminalWitchcraft

Reputation: 1852

You can use Python's subprocess module to accomplish your task. It is a built-in module and does not have much dependencies.

For your problem, I would suggest the Popen method, which runs command on remote computer and returns the result to your machine.

out = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    t = out.stdout.read() + out.stderr.read()
    socket.send(t)

where cmd is your command which you want to execute.

This will return the result of the command to your screen. Hope that helps !!!

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249183

There is an excellent Python library for this. It's called Paramiko: http://www.paramiko.org/

Paramiko is, among other things, an SSH client which lets you invoke programs on remote machines running sshd (which includes lots of standard servers).

Upvotes: 1

Related Questions