1

私はプログラマーではありませんが、次のスクリプトを変更してみます。

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

スクリプトをもう少し効率的にしたいと思います。現時点では、for ループにより、スクリプトはコマンドごとに新しいログインを実行します。

スクリプトでデバイスごとに 1 つのログインを実行し、デバイスごとに 1 つの出力ですべてのコマンドを実行したいと思います。

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 に答える