1

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?

3
  • 1
    The redirection operator < is part of shell functionality. Your call doesn't use the shell so cat processes the parameter directly (and doesn't understand it)CommentedSep 8, 2018 at 0:36
  • @MichaelButscher Thanks for the reply. How do I execute this command using subprocess then?CommentedSep 8, 2018 at 0:39
  • check_output supports a shell parameter for thatCommentedSep 8, 2018 at 0:41

2 Answers 2

2

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.)

3
  • Works. Thanks :)CommentedSep 8, 2018 at 1:07
  • Can you explain why subprocess is the wrong way to approach this? Besides the fact it isn't working for Umar haha
    – jadki
    CommentedSep 8, 2018 at 3:14
  • 1
    In general it's both easier and faster to try to do things natively in a single language if you can. If you're using subprocess for basic file I/O (ls cat grep sed ...) (or in this case, network I/O) you should just use your local language primitives for it instead.CommentedSep 8, 2018 at 11:08
1

Give this a try:

import subprocess com = "sudo cat </dev/tcp/time.nist.gov/13" subprocess.Popen(com, stdout = subprocess.PIPE, shell = True) 
2
  • Doesnt work, error: cannot open /dev/tcp/time.nist.gov/13L No such file or directoryCommentedSep 8, 2018 at 0:50
  • Turn it into the full path. I don't know what that is on your pc. Ie, C:/User/.../dev/tcp/time.nist.gov/13. Or put the script into the same folder as the application you are trying to call.
    – jadki
    CommentedSep 8, 2018 at 0:52

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.