1

I need to get the output from netcat in python script. My current code is

  response = subprocess.Popen(["netcat","smtp.myserver.net", "25"], stdout=subprocess.PIPE).stdout.read()
  x = response.find("220 ***")

I want it to check for 200 * status and work with that, but it seems to wait for my input everytime it runs in a loop. How can I open netcat, get it's result, close it and move on?

1 Answer 1

6

Don't do that.

Python has, built-in, an smtp client library that can do this trivially. Really. There's no reason not to use it.

from smtplib import SMTP
SMTP('smtp.myserver.net')

It's that simple. Catch the exceptions you care about.

If you really want to know what you were doing wrong,

Your program was waiting for you to type quit.

Solution? Close the writing-end first:

child = subprocess.Popen(["netcat","smtp.myserver.net", "25"],
    stdout=subprocess.PIPE,
    stdin=subprocess.PIPE)
child.stdin.close()
response = child.stdout.read()
x = response.find("220 ***")

The reason you need to do this is because by default standard input is still connecting netcat to your terminal.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.