0

I'm trying to make a tool right now that encompasses more than one network scaning tool. using the os module i'm sending code to the console to find my ip + CIDR and it is working but I cannot get it to return the numbers as something I can use (i.e. a string or int) it always just returns '0' as my ip address.

*

#!/usr/bin/env python3
import os
import subprocess
def quiet_scan():
    address = "ip addr | grep 'inet 10.*' | awk '{print $2}'"
    ipcidr = int(os.system(address))
    print(ipcidr)
    nmapCom = ('nmap -sS ' + str(ipcidr))
    print(nmapCom)
    final = (os.system(nmapCom))
    print(final
root@kali:/home/kali# ./recon.py -q 
10.0.2.15/24
0

in the end I want the output to be nmap -sS 10.50.0.2 in place of the final 0

Eli1776
  • 17
  • 4
  • I think you are looking for stdout value rather than return value which then you need to utilize subprocess, see [here](https://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line) for details – sqz Jul 19 '20 at 20:28

2 Answers2

0

I think subprocess.run with the capture_output flag would work well here:

import subprocess

result = subprocess.run(["nmap", "-sS"], capture_output=True)
print(result.stdout)

result will hold the results of running the process, including exit codes and what was written to the streams. If the data you want is what nmap printed to the stdout, you can simply inspect that attribute.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • is there any way I could pass in that "address" variable. i have no idea how that subprocess syntax works and it keeps erroring out – Eli1776 Jul 19 '20 at 21:40
  • I've never actually used the `subprocess` module with any piping before. [These answers](https://stackoverflow.com/questions/13332268/how-to-use-subprocess-command-with-pipes) though suggest that basically, you'll need to break that string into the three commands individually, and pipe between them manually. They're referring to a different method, but it likely carries. – Carcigenicate Jul 19 '20 at 21:51
0

Try this script :

#!/usr/bin/env python3
import os
import subprocess

def run_cmd(cmd):
    return subprocess.run(cmd, capture_output=True, shell=True).stdout.decode().strip()

def quiet_scan():
    address = run_cmd("ip addr | grep 'inet 10.*' | awk '{print $2}'")
    print(address)
    final = run_cmd(f"nmap -sS {address}") 
    print(final)

quiet_scan()

The function run_cmd takes a cmd as string, run it with shell, then decode the result and strip of last newline.

Philippe
  • 20,025
  • 2
  • 23
  • 32