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