1

我不是程序员,但我尝试修改以下脚本。

http://www.networking-forum.com/wiki/Python_SSH_Script

我想让脚本更有效率。目前 for 循环使脚本为每个命令进行新的登录。

我希望脚本为每个设备执行一次登录,并为每个设备运行所有命令并输出一个输出。

这是for循环:

# This function loops through devices. No real need for a function here, just doing it.
  def connect_to(x):
      for device in x:
          # This strips \n from end of each device (line) in the devices list
          device = device.rstrip()
          # This opens an SSH session and loops for every command in the file
          for command in commands:
              # This strips \n from end of each command (line) in the commands list
              command = command.rstrip()
              ssh = paramiko.SSHClient()
              ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
              ssh.connect(device, username=username, password=password)
              stdin, stdout, stderr = ssh.exec_command(command)
              output = open(device + ".out", "a")
              output.write("\n\nCommand Issued: "+command+"\n")
              output.writelines(stdout)
              output.write("\n")
              print "Your file has been updated, it is ", device+".out"
              ssh.close()

  connect_to(devices)
  f1.close()
  f2.close()
  # END 
4

1 回答 1

0

查看源代码中的正确缩进后,请查看以下修改。这是受此SO answer启发的。

注意我没有目标可以通过 ssh 进入并测试这些修改。

def connect_to(x):
    for device in x:
        # Connect to the target 
        device = device.rstrip()
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(device, username=username, password=password)

        # Open up a stream for the conncction
        channel = ssh.invoke_shell()
        ssh_stdin = channel.makefile('wb')
        ssh_stdout = channel.makefile('rb')
        output = open(device + ".out", "a")

        # Send all of the commands to the open session
        for command in commands:
            # This strips \n from end of each command (line) in the commands list
            command = command.rstrip()

            # send the command
            ssh_stdin.write(command)

            # Update the local log file
            output.write("\n\nCommand Issued: "+command+"\n")
            output.writelines(ssh_stdout.read())
            output.write("\n")
            print "Your file has been updated, it is ", device+".out"

        # Close the connection after all of the commands have been issued
        output.close()
        ssh_stdin.close()
        ssh_stdout.close()
        ssh.close()
于 2013-09-01T14:37:47.033 回答