Kosie
Kosie

Reputation: 441

Python Popen using PIPE issue

I am trying to replicate this command using python and Popen:

echo "Acct-Session-Id = 'E4FD590583649358F3B712'" | /usr/local/freeradius/bin/radclient -r 1 1.1.1.1:3799 disconnect secret

When running this from the command line as it is above, I get the expected:

Sent Disconnect-Request Id 17 from 0.0.0.0:59887 to 1.1.1.1:3799 length 44

I want to achieve the same from a python script, so I coded it like this:

rp1 = subprocess.Popen(["echo", "Acct-Session-Id = 'E4FD590583649358F3B712'"], stdout=subprocess.PIPE)
rp2 = subprocess.Popen(["/usr/local/freeradius/bin/radclient",
                     "-r 1",
                     "1.1.1.1:3799",
                     "disconnect",
                     "secret"],
                     stdin = rp1.stdout,
                     stdout = subprocess.PIPE,
                     stderr = subprocess.PIPE)

rp1.stdout.close()

result = rp2.communicate()

print "RESULT: " + str(result)

But, I must be doing this incorrectly as the "result" variable contains the radclient usage info, as if it is called incorrectly:

RESULT: ('', "Usage: radclient [options] server[:port] <command> [<secret>]\n  <command>....

Anybody any idea where my mistake lies?

Thanks!

Upvotes: 0

Views: 270

Answers (1)

Chen A.
Chen A.

Reputation: 11280

Besides @Rawing catch of the args typo, you can make it much simpler with a single Popen process. Try this:

rp = subprocess.Popen(["/usr/local/freeradius/bin/radclient",
                     "-r",
                     "1",
                     "1.1.1.1:3799",
                     "disconnect",
                     "secret"],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)

result = rp.communicate("Acct-Session-Id = 'E4FD590583649358F3B712'")

Using communicate to handle all the I/O prevents possible deadlocks that are possible when explicitly writing to stdin when you also need to read from stdout/stderr.

Upvotes: 1

Related Questions