私はプログラマーではありませんが、次のスクリプトを変更してみます。
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