- 论坛徽章:
- 22
|
本帖最后由 聆雨淋夜 于 2017-08-08 12:20 编辑
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- from multiprocessing import Process,Pool
- import paramiko
- import time
- IPList=['1.2.3.4','5.6.7.8']
- cmd='ls'
- result_dct={}
- def remote_exec(hostname,command):
- try:
- private_key = paramiko.RSAKey.from_private_key_file('/home/test/.ssh/id_rsa')
- transport = paramiko.Transport((hostname,22))
- transport.connect(username='test', pkey=private_key)
- ssh = paramiko.SSHClient()
- ssh._transport = transport
- stdin, stdout, stderr = ssh.exec_command(command)
- result_dct[hostname]=stdout.readlines() if stdout else stderr.readlines()
- transport.close()
- except Exception as e:
- print 'ssh failed'
- if __name__ == '__main__':
- pool = Pool(5)
- for ip in IPList:
- pool.apply_async(func=remote_exec, args=(ip,cmd),)
- pool.close()
- pool.join()
- print result_dct
复制代码
如上是一个多进程执行命令的脚本,定义了全局字典result_dct,在函数中给字典赋值,“result_dct[hostname]=stdout.readlines() if stdout else stderr.readlines()”在脚本结束输出result_dct,发现还是{}
在函数中加上 “global result_dct”也不行
大神帮忙看看,感谢。
|
|