python - AttributeError: 'NoneType' object has no attribute 'read'

956 Views Asked by At
import os
import random
import subprocess
pas = ''
while True:
    for x in range(4):
        pas = pas + random.choice(list('1234567890'))
    print('your password is: ', pas)
    cmd = f'torsocks -P {pas}'
    stdout=subprocess.PIPE
    p = subprocess.Popen(cmd, shell = True)
    print ('consol:', p.stdout)
    if '3333' in p.stdout.read().decode('utf-8'): 
        fp = open('/home/kali/test.txt', 'w')
        fp.write(p)
        fp.close()
    break

write:

> your password is:  7352
> consol: None
> Traceback (most recent call last):
> File "/home/kali/test.py", line 13, in <module>
                                                                                                                          if '3333' in p.stdout.read().decode('utf-8'): 
                             AttributeError: 'NoneType' object has no attribute 'read'
                                                                                                                                                                                                                                                                          
Please provide an application to torify.

Python parsing console and write to file.

1

There are 1 best solutions below

1
ShadowRanger On

You need to pass stdout=subprocess.PIPE to the Popen constructor; as is, you defined a random local variable which was then ignored. Replace:

stdout=subprocess.PIPE
p = subprocess.Popen(cmd, shell = True)

with:

p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)

I'll note that as written, you're using Popen when subprocess.run would simplify matters a bit (you're eagerly consuming the output anyway, so you may as well do so safely; as written, if the underlying program tries to read from stdin, you'll deadlock). So you could simplify a bit to:

import os
import random
import subprocess
pas = ''
while True:
    for x in range(4):
        pas += random.choice('1234567890')  # No need for list wrapping, str is a sequence already
    print('your password is: ', pas)
    # Never use shell=True if you can avoid it, it's slower and more dangerous,
    # and in this case, simple list wrapping of the raw command is easy
    # We just explicitly tell it to capture the stdout, and decode as UTF-8 for us
    p = subprocess.run(['torsocks', '-P', pas], stdout=subprocess.PIPE, text=True, encoding='utf-8')
    print('consol:', p.stdout)
    if '3333' in p.stdout:  # No need to read or decode, run did it for you
        with open('/home/kali/test.txt', 'w') as fp:  # Use with statement for guaranteed close even on exception
            fp.write(p.stdout)
    break