1

我需要登录多个设备,运行多个命令并存储输出。我目前正在使用 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 与子进程一起使用,但正在寻找内置的 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()

但是,现在我有空白单元格。我在命令行解释器上尝试了这个,它工作正常。可能出了什么问题?

4

1 回答 1

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()
于 2014-04-16T15:42:27.980 回答