2015-02-04 3 views
0

Nmap 스캔의 출력을 파이썬을 사용하여 텍스트 파일로 리디렉션하려고합니다.서브 프로세스의 출력을 파일로 리디렉션

outputName = raw_input("What is the output file name?") 
fname = outputName 
with open(fname, 'w') as fout: 
    fout.write('') 

command = raw_input("Please enter an Nmap command with an IP address.") 
args = shlex.split(command) 
proc = subprocess.Popen(args,stdout=fname) 

오류 : 워드 프로세서

Traceback (most recent call last): 
    File "mod2hw4.py", line 17, in <module> 
    proc = subprocess.Popen(args,stdout=fname) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 701, in __init__ 
    errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1127, in _get_handles 
    c2pwrite = stdout.fileno() 
AttributeError: 'str' object has no attribute 'fileno' 

답변

2

파울로는 위에서 언급 한 바와 같이, 당신이 열려있는 파일을 통과해야; 파일 이름이 작동하지 않습니다. 당신이 만든 동일한 문맥 (with 블록)으로 이것을 수행해야 할 것이다. 이에 정리하려고 :

outputName = raw_input("What is the output file name?") 
fname = outputName 

command = raw_input("Please enter an Nmap command with an IP address.") 
args = shlex.split(command) 

with open(fname, 'w') as fout: 
    proc = subprocess.Popen(args,stdout=fout) 
    return_code = proc.wait() 

이 그 subprocess.Popen 대신 stdout=fname 지금 stdout=fout 호출되지는 않습니다. with 문으로 작성된 컨텍스트 관리자는 예외가 발생하더라도 nmap 프로세스가 완료 될 때 파일이 닫히도록 보장합니다.

+0

감사합니다.이 또한 도움이되었습니다. –

+0

주 :'Popen'이 자식 프로세스가 종료되기를 기다리지 않기 때문에 * nmap이 끝나기 전에 파일이 부모 프로세스에서 닫힐 수 있습니다. nmap은 파일 디스크립터의 복사본을 상속 받는다. – jfs

+0

@ J.F.Sebastian이 맞습니다. 프로세스가 먼저 완료 될 때까지 명시 적으로 기다려야합니다. with 블록에서이를 수행하기 위해'subprocess.wait'에 대한 호출을 추가했습니다. – wrigby

1

:

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.

그래서 파일 이름이 표준 출력 인수에 대한 유효한 값이 아닙니다

여기 내 코드입니다.

proc = subprocess.Popen(args,stdout=open(fname, 'w')) 

또는 더 나은 아직, 그냥 with 블록 내에서 모든 것을 유지 :

내가 대신이 원하는 생각

with open(fname, 'w') as fout: 
    fout.write('') 

    command = raw_input("Please enter an Nmap command with an IP address.") 
    args = shlex.split(command) 
    proc = subprocess.Popen(args,stdout=fout) 
+0

'check_output '을 의미합니다. 동의해라. (작은 오타가있는 이것에 대해 삭제 된 주석이있다 :'checked_output'). –

+0

정말 고마워요! 설명서의 설명을 읽었지만 열린 파일과 파일 객체의 이름이 같은 것이 아니라는 것을 이해하지 못했습니다. 따라서 오류입니다. 그래서 fout은 실제 파일 객체입니다. 그래서 명확합니다. –

+0

예, 그렇습니다. 파이썬에서 열린 파일에 대한 흥미로운 점은 "컨텍스트 관리 프로토콜"을 준수한다는 것입니다. 따라서'with' 문에서 사용할 때 그들은 블록의 끝에서 자동으로 닫히게됩니다 (그래서 프로그램은 누수 자원 - 대부분의 운영 시스템은 열린 파일의 수를 제한합니다.) –

관련 문제