Umar Dastgir
Umar Dastgir

Reputation: 724

Execute shell command using Python subprocess

I want to execute the following command via a python script:

sudo cat </dev/tcp/time.nist.gov/13

I can execute this command via the command line completely fine. However, when I execute it using subprocess, I get an error:

Command ['sudo','cat','</dev/tcp/time.nist.gov/13'] returned non-zero exit status 1

My code is as follows

import subprocess
subprocess.check_output(['sudo','cat','</dev/tcp/time.nist.gov/13'])

As I mentioned above, executing the command via the command line gives the desired output without any error. I am using the Raspbian Jessie OS. Can someone point me in the right direction?

Upvotes: 1

Views: 2199

Answers (2)

David Maze
David Maze

Reputation: 158908

You don't want to use subprocess for this at all.

What does this command really do? It uses a bash extension to open a network socket, feeds it through cat(1) to reroute it to standard output, and decides to run cat as root. You don't really need the bash extension, or /bin/cat, or root privileges to do any of this in Python; you're looking for the socket library.

Here's an all-Python equivalent:

#!/usr/bin/env python3
import socket
s = socket.create_connection(('time.nist.gov', 13))
try:
    print(s.recv(4096))
finally:
    s.close()

(Note that all of my experimentation suggests that this connection works but the daytime server responds by closing immediately. For instance, the simpler shell invocation nc time.nist.gov 13 also returns empty string.)

Upvotes: 2

jadki
jadki

Reputation: 492

Give this a try:

import subprocess

com = "sudo cat </dev/tcp/time.nist.gov/13"

subprocess.Popen(com, stdout = subprocess.PIPE, shell = True)

Upvotes: 1

Related Questions