Python Regex从子流程输出中查找以特殊字开头的字符串
在代码中,我正在搜索以Python Regex从子流程输出中查找以特殊字开头的字符串,python,regex,Python,Regex,在代码中,我正在搜索以FAILED开头的字符串。 tt变量保存子进程.Popen的stdoutput。 我尝试了re.serach和re.match,但它返回值为None #!/usr/bin/python import subprocess import re def cbk(): with open('GDPC.txt', 'r') as f: for line in f: tt = subprocess.Popen(['/grid/it/b
FAILED
开头的字符串。
tt
变量保存子进程.Popen的stdoutput
。
我尝试了re.serach
和re.match
,但它返回值为None
#!/usr/bin/python
import subprocess
import re
def cbk():
with open('GDPC.txt', 'r') as f:
for line in f:
tt = subprocess.Popen(['/grid/it/bin/cyberarksdk.sh' , 'chk', line], stdout=subprocess.PIPE).communicate()[0]
#pat_match=re.search(".*FAILED:\s+", tt)
pat_match=re.search(r'(^FAILED:)\s+', tt)
print pat_match
cbk()
上述脚本的输出:
变量tt
的输出:
意图:只需搜索以FAILED
字符串开头的行,并剪切第三列myserevr1并放入文件file1
,类似地,任何以1
开头的行都要剪切myserver2
并放入另一个文件file2
注意:
GDPC.txt
包含服务器名称。我现在得到的解决方案是获取包含的行失败的
#!/usr/bin/python
import subprocess
import re
##################
def cbk():
with open('GDPC.txt', 'rw') as f:
for line in f:
tt = subprocess.Popen(['/grid/it/bin/cyberarksdk.sh' , 'chk', line], stdout=subprocess.PIPE).communicate()[0]
pm = re.search('FAILED.*', tt)
if pm:
#print pm.group(0)
for line in pm.group(0).splitlines():
col = line.split()
if len(col) >=3:
print col[2]
cbk()
以下是输出:
解决方案:借鉴
使用split()和splitlines()(将字符串转换为行列表,并将行列表转换为列列表,然后根据需要进行索引):是否执行pat_match=re.search(r'(^FAILED:)\s+,tt,re.MULTILINE)
工作?@Jan,让我检查一下。@Jan,否。。它仍然在返回结果中给出相同的None
。
FAILED: Account/host myserver1 does not exist inside cyberark.
1 102_2923 DS-KS-DEFAULT-UNIX-ROOT Operating System-DS-Unix-RootAccounts-SSH-myserver2-root
#!/usr/bin/python
import subprocess
import re
##################
def cbk():
with open('GDPC.txt', 'rw') as f:
for line in f:
tt = subprocess.Popen(['/grid/it/bin/cyberarksdk.sh' , 'chk', line], stdout=subprocess.PIPE).communicate()[0]
pm = re.search('FAILED.*', tt)
if pm:
#print pm.group(0)
for line in pm.group(0).splitlines():
col = line.split()
if len(col) >=3:
print col[2]
cbk()
$./cyberCheck.py
myserver1
myserver2
myserver3