通过使用iter(),我从json文件中获取主机名。我试图通过函数调用将主机名转发给paramiko connect,exec_command方法。
但是,在将hostname替换为变量时,connect方法将其视为主机名而不是变量。
如何在paramiko connect中替换变量?
import paramiko,json
def exec_commands(host_data):
host_data = host_data
new_client=paramiko.SSHClient()
new_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
new_client.connect(host_data,username='root',password='password',port=22,timeout=60)
stdin, stdout, stderr = new_client.exec_command('uptime')
for i in stdout:
print(i)
new_client.close()
with open('server_list.json','r') as f:
server_list = json.load(f)
for item in server_list:
print((item['mydev']))
iterator_var = iter(item['mydev'])
next(iterator_var)
exec_commands(next(iterator_var))
json文件的内容如下
[
{
"mydev" : ["192.168.56.101","192.168.56.101","192.168.56.101"]
}
]
错误:
Traceback (most recent call last):
File "D:\Personal\Python_code\Logs_Finder\authentication.py", line 30, in <module>
exec_commands(next(iterator_var))
File "D:\Personal\Python_code\Logs_Finder\authentication.py", line 16, in exec_commands new_client.connect(host_data,username='root',password='password',port=22,timeout=60)
File "C:\Users\rgenupula\AppData\Local\Continuum\Miniconda3\lib\site-packages\paramiko\client.py", line 310, in connect
retry_on_signal(lambda: sock.connect(addr))
File "C:\Users\rgenupula\AppData\Local\Continuum\Miniconda3\lib\site-packages\paramiko\util.py", line 276, in retry_on_signal
return function()
File "C:\Users\rgenupula\AppData\Local\Continuum\Miniconda3\lib\site-packages\paramiko\client.py", line 310, in <lambda>
retry_on_signal(lambda: sock.connect(addr))
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
[Finished in 26.4s]
import paramiko,json
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.56.102',port=22,username='root',password='password',timeout=60)
stdin, stdout, stderr = client.exec_command('uptime')
for i in stdout:
print(i)
client.close()
答案 0 :(得分:1)
当我运行你的代码时,它甚至没有进入exec_commands
。您的next
电话对我来说有点意义。
这很好用:
for item in server_list:
for item2 in item['mydev']:
exec_commands(item2)