2

So I am running code that looks like this on Ubuntu 11.4 and Python 2.7:

p_scan_command = "sudo nmap -sC -sV -PN -O 192.168.0.1/24"
time.sleep(1.5)
os.system(p_scan_command)
f = open('nmapscan1.log', 'r')
print f.read()
f.close()

What is happening is that I end up with no results, and the scan is not being run, probably because it is being run with 'sudo'. I want to know

  1. If I have been correct in my diagnosis of the problem and
  2. How to fix it?

2 Answers 2

7
  1. Are you sure that the log file is even created? I cannot see where this name is mentionned - but maybe it is created by default.

  2. Are you asked for the password by sudo? This could tell you if sudo is really run.

  3. os.system is kind of deprecated or at least frowned upon; better use subprocess.call(), subprocess.check_call() or subprocess.Popen() (gives you an object which you can use to further control the process).


EDIT: Just tested. Here the scan runs, but the output gets displayed instead of written to a file. Probably you are missing the > nmapscan1.log part in the os.system() call.

With subprocess, you would write

sp = subprocess.Popen(['sudo', 'nmap', '-sC', '-sV', '-PN', '-O', '192.168.0.1/24'],
    stdout=file("nmapscan1.log", "w"))
sp.wait()
f = open('nmapscan1.log', 'r')
print f.read()
f.close()

or if you don't need the file, simply

sp = subprocess.Popen(['sudo', 'nmap', '-sC', '-sV', '-PN', '-O', '192.168.0.1/24'],
    stdout=subprocess.PIPE)
print sp.stdout.read()
sp.wait()
Sign up to request clarification or add additional context in comments.

1 Comment

Right. The OP should not really be using os.system for this kind of thing.
0
  1. You can use commands module in python.
  2. You can use subprocess module.

The main issue is when use sudo command inside python program doesn't ask for password, so better run sudo python filename.py

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.