我不是程序员,但我尝试修改以下脚本。
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