2013-09-01 5 views
1

Я не программист, но я пытаюсь изменить следующий скрипт.Python ssh script loop problems

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

Я хотел бы сделать сценарий немного более эффективным. В настоящий момент цикл 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 
+3

беспокоился о углублении? – matcheek

+0

Какие модификации вы пытались? –

+0

Пожалуйста, очистите отступы. –

ответ

0

Посмотрев на правильном отступа нашел источник сигнала проверить изменения ниже. Это было вдохновлено от this 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() 
+0

Жаль, что это не сработало. Нет выходного файла и никакого ssh-соединения из сценария. – user2737247

+0

@ user2737247 Где есть исключения? –

+0

Не совсем уверен, что вы имеете в виду. Скрипт работает очень хорошо, но никакого ssh-соединения не производится, и выходной файл не записывается. – user2737247