# Device details
device = "test"
user = "abc"
password = "123"
# Invoking remote session
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(device, username=user, password=password)
# std commands to capture shell output
channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
# remote commands to run
stdin, stdout, stderr = client.exec_command('vmm ping | grep no-response')
noresponse = stdout.read()
print noresponse
#print some_string.split('', 1)[0]
noresponse = noresponse.split(' ', 1)[0]
print noresponse
# Close connections
stdout.close()
stdin.close()
client.close()
输出:
> C:\Python27\python.exe "C:/Python/Scripts/Login to Unix3.py"
R1_MPC00 10.49.123.146 no-response
R3_MPC00 10.49.122.24 no-response
R6_re 10.49.122.226 no-response
R7_re 10.49.122.217 no-response
R8_re 10.49.122.215 no-response
R11_MPC00 10.49.122.20 no-response
R14_re 10.49.122.152 no-response
R14_MPC00 10.49.122.151 no-response
R17_MPC00 10.49.122.129 no-response
R19_re 10.49.121.213 no-response
R20_re 10.49.121.206 no-response
SW2_MPC00 10.49.120.54 no-response
R1_MPC00
问题:
我需要输出的所有行中的第一个单词,而不仅仅是R1_MPC00
。我怎样才能做到这一点?
答案 0 :(得分:1)
pattern = r'[^.*\s]*'
with open('test.txt') as f:
for line in f:
match = re.search(pattern, line)
if match:
print(match.group())
是一个评论,您可以沿着换行符分割,然后使用列表理解进行拆分,这可能会更容易,但为什么在使用正则表达式时呢?< / p>
with open('test.txt') as file:
words = [x for x in [l.split(' ')[0] for l in file.read().split('\n')] if x]
答案 1 :(得分:0)
只需在noresponse
noresponse = """\
R1_MPC00 10.49.123.146 no-response
R3_MPC00 10.49.122.24 no-response
R6_re 10.49.122.226 no-response
R7_re 10.49.122.217 no-response
R8_re 10.49.122.215 no-response
R11_MPC00 10.49.122.20 no-response
R14_re 10.49.122.152 no-response
R14_MPC00 10.49.122.151 no-response
R17_MPC00 10.49.122.129 no-response
R19_re 10.49.121.213 no-response
R20_re 10.49.121.206 no-response
SW2_MPC00 10.49.120.54 no-response
"""
for line in noresponse.splitlines():
print(line.split(' ', 1)[0])