Search code examples
pythonlinuxoperating-systemsubprocessnmap

using os or subprocess module to return string or integer


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


Solution

  • 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.