Nate
Nate

Reputation: 21

Subprocess causing error: TypeError: expected str, bytes or os.PathLike object, not tuple

I am working on building an enumeration tool for servers featured on Hack the box, Try Hack Me, etc. When trying to automate the port scan I run into issues with subprocess and writing output to a file.

import os
import sys
import traceback
import subprocess as sub
import re

ip_addr = ''
nickName = ''
Dir = ''


def getIP():
    global ip_addr
    ip_addr = str(input('[+] Please enter the IP address you would like to enumerate: \n'))
    if not re.match("^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$", ip_addr):
        print('[-] That is not the correct format for an IP address. \n    [-] Please try again.')
        getIP()
    
def mk_nickname():
    global nickName
    nickName = str(input('[+] Please give this IP a nickname. \n    [+] This will be used to create a directory to keep you notes organized. \n    [+] This will be found in your documents folder within your home directory.\n'))
    if nickName == '':
        mk_nickname()
    return

#add if file already exsists clause (exsit_ok may have done the trick)
def mkdir():
    global Dir
    Dir = f"{os.getenv('HOME')}/Documents/" + nickName
    os.makedirs(Dir, mode=0o700, exist_ok=True)
    

def PortScan():
    YN = str(input('[+] Would you like to run a port scan? '))
    portDir = Dir +'/portscan.txt'
    print(portDir)
    if YN == 'y' or YN == 'yes':
        print('[+] Starting portscan.\n    [+] The results can be found here: ' + portDir )
        cmd = "rustscan", "-a", ip_addr, "--", "-sV", "-sC", "-A"
        print(cmd)
        sub.Popen([cmd], stdout=sub.PIPE, stderr=sub.PIPE, text=True)
        with open(portDir, w) as f:
            file.write(result.stdout)

        
    elif YN == 'n' or YN == 'no':
        return
    else:
        print('[-] Invalid input!\n[-] Please try again.')
    

        
print('[+] Lets start enumerating!!!')
getIP()
mk_nickname()
mkdir()
PortScan()

I have tried many different things, but cannot seem to get it working.

Here is the error received:

[+] Lets start enumerating!!!
[+] Please enter the IP address you would like to enumerate: 
10.10.10.75
[+] Please give this IP a nickname. 
    [+] This will be used to create a directory to keep you notes organized. 
    [+] This will be found in your documents folder within your home directory.
nibbles
[+] Would you like to run a port scan? yes
/home/kali/Documents/nibbles/portscan.txt
[+] Starting portscan.
    [+] The results can be found here: /home/kali/Documents/nibbles/portscan.txt
('rustscan', '-a', '10.10.10.75', '--', '-sV', '-sC', '-A')
Traceback (most recent call last):
  File "/home/kali/Desktop/OSCPENUM.py", line 57, in <module>
    PortScan()
  File "/home/kali/Desktop/OSCPENUM.py", line 41, in PortScan
    sub.Popen([cmd], stdout=sub.PIPE, stderr=sub.PIPE, text=True)
  File "/usr/lib/python3.9/subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.9/subprocess.py", line 1698, in _execute_child
    and os.path.dirname(executable)
  File "/usr/lib/python3.9/posixpath.py", line 152, in dirname
    p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not tuple

I can chalk this up to not completely understanding subprocess but after looking through the docs and many different fourms/stack overflow posts I am still unable to find a solution. This is why I have turned to the lords of Stack Overflow themselves! :)

Upvotes: 1

Views: 956

Answers (1)

Nate
Nate

Reputation: 21

Replace the Popen line with sub.Popen(cmd, stdout=sub.PIPE, stderr=sub.PIPE, text=True) . (Notice that I removed the square brackets) – Flimm 1

This has solved this issue in question. Now onto debugging the rest of the program. Which has been easy since getting past this issue.

From my understanding of the issue: The subprocess documents specify using brackets [] for the value of "arg". That does not apply when you pass a variable through the subprocess.Popen() rather than the direct command.

def PortScan():
    YN = str(input('[+] Would you like to run a port scan?\n'))
    portDir = Dir +'/portscan.txt'
    print(portDir)
    if YN == 'y' or YN == 'yes':
        print('[+] Starting portscan.\n    [+] The results can be found here: ' + portDir )
        cmd = "rustscan", "-a", ip_addr, "--", "-sV", "-sC", "-A"
        print(cmd)
        f = open(portDir, "w")
        sub.Popen(cmd, stdout=f, text=True)

Big thanks to Flimm for the quick response!

Upvotes: 1

Related Questions