[英]What's a more pythonic way to build this simple factory class?
前言:我对 Python 非常陌生。 我通常写PHP。 我也知道这可能被认为是一个主观问题,并且可能会被标记为主观问题,但我确实认为可以从中得出一个“足够正确”的答案,它肯定会对我有所帮助。 另外我不知道还能去哪里问。
现在,这只是播放代码,但我的想法是拥有某种静态工厂,可以根据选项构建 Paramiko SSHClient 类。 我不确定最终将如何设计它,但我有一种强烈的感觉,即使现在我也没有充分利用 python 设计功能,而是强迫它像 PHP 一样工作。 基本上,我做错了吗?
import paramiko
import time
import sys
class Client:
@staticmethod
def build(host, **options):
default_connect_opts = {'look_for_keys': True}
client = paramiko.SSHClient()
# automatically add untrusted hosts
if options.get('special').get('auto_add_policy'):
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
our_connect_opts = options.get('connect');
# merge defaults with provided with preference for provided opts
connect_opts = dict(default_connect_opts.items() + our_connect_opts.items())
#print connect_opts
#sys.exit()
client.connect(host, **connect_opts)
return client
options = {
'connect': {
'username': 'root',
'password': 'p4assw0rd',
'look_for_keys': False,
},
'special': {
'auto_add_policy': True,
}
}
client = Client.build('10.0.0.13', **options)
print client
编辑:只是为了清楚我最终要完成的工作——我可能想为通用的 unix/linux 主机构建 paramiko sshclients,但也希望能够为像 Cisco 交换机这样的奇怪的人构建专门的 sshclient 类不运行真正的shell。 为此,我必须传递额外的选项来禁用分页,有时还需要在命令之间sleep
,等等,这取决于远程“shell”的性质。
你应该知道NoneType Error
。
options.get('special').get('auto_add_policy')
将在special
不在options
时抛出异常,因为您不能执行None.get()
。
# Deal with `options` without key 'special'
if options.get('special', {}).get('auto_add_policy'):
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
default_connect_opts.update(options.get('connect', {}))
client.connect(host, **default_connect_opts)
您可以SSHClient
您的目的派生SSHClient
,并在默认情况下为look_for_key = True
去掉default_connect_opts
。
class Client(paramiko.SSHClient):
def __init__(self, host, **options):
super(Client, self).__init__()
# set policy
if options.get('special', {}).get('auto_add_policy'):
self._policy = paramiko.AutoAddPolicy()
# look_for_key = True by default
self.connect(host, **options.get('connect', {}))
client = Client(host, **options)
new_client = Client(new_host, **new_options)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.