John Dorian
John Dorian

Reputation: 1904

In Ubuntu Python 2.7 reading output of an os.system() command

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?

Upvotes: 2

Views: 1410

Answers (2)

Kracekumar
Kracekumar

Reputation: 20419

  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

Upvotes: 0

glglgl
glglgl

Reputation: 91029

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

Upvotes: 7

Related Questions