我需要登录多个设备,运行多个命令并存储输出。我目前正在使用paramiko进行远程SSH,然后使用xlswriter将结果存储在excel表中。这是我目前的代码:
import getpass
import paramiko
import xlsxwriter
username = raw_input('Enter username for device login:')
def enterPassword():
while True: # repeat forever
password = getpass.getpass('Enter corresponding password:')
password_again = getpass.getpass('Confirm password:')
if password != password_again:
print 'Password and confirmation do not match.Please try again!!'
else:
return password
password = enterPassword()
print "Running the tests..this might take some time.."
# Opens file in read mode
f1 = open('hostnames','r')
f2 = open('commandlist','r')
# Creates list based on f1
devices = f1.readlines()
commands = f2.readlines()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
data = []
for device in devices:
column = device.split()
data.append([column[0]])
print column[0]
for command in commands:
try:
conn=ssh.connect(column[1], username=username, password=password, timeout=4)
if conn is None:
stdin, stdout, stderr = ssh.exec_command(command)
data[-1].append(stdout.read())
ssh.close()
except paramiko.AuthenticationException:
output = "Authentication Failed"
data[-1].append(output)
break
except paramiko.SSHException:
output = "Issues with SSH service"
data[-1].append(output)
break
except socket.error, e:
output = "Connection Error"
data[-1].append(output)
break
data[-1] = tuple(data[-1])
f1.close()
f2.close()
book = xlsxwriter.Workbook('finalresults.xlsx')
sheet = book.add_worksheet('sheet1')
for row, data_in_row in enumerate(data):
for col, text in enumerate(data_in_row):
sheet.write(row + 1, col, text)
book.close()
这在运行bash的远程机器上完全正常,我只得到我运行的命令的输出。但是,在某些没有运行bash的机器上,我得到命令运行和输出中的额外提示如下:
如何从循环中的每个命令中删除stdout.read()的第一行和最后两行。我听说过使用grep和subprocess但是正在寻找内置的python字符串运算符
修改 所以我做了一些阅读,拖了一些网站,这就是我所拥有的:
data = []
offending = [">"]
for device in devices:
column = device.split()
data.append([column[0]])
print column[0]
for command in commands:
try:
conn=ssh.connect(column[1], username=username, password=password, timeout=4)
if conn is None:
stdin, stdout, stderr = ssh.exec_command(command)
for line in stdout.readline():
if not True in [item in line for item in offending]:
output = line
data[-1].append(output)
ssh.close()
然而,现在我有空白单元格。我在命令行解释器上尝试了这个并且它工作正常。可能出错?
答案 0 :(得分:3)
好的。经过一番研究和反复试验后,这段代码就可以了:
data = []
for device in devices:
column = device.split()
data.append([column[0]])
print column[0]
for command in commands:
try:
conn=ssh.connect(column[1], username=username, password=password, timeout=4)
if conn is None:
stdin, stdout, stderr = ssh.exec_command(command)
output = '\n'.join(item for item in stdout.read().splitlines() if '>' not in item)
data[-1].append(output)
ssh.close()