此处的总noob。我试图创建一个python对象并在其中的一个实例中执行方法,似乎我想执行的代码块不会运行。问题中的代码块是run_job,它在被调用时似乎什么都不做。我究竟做错了什么?未执行Python方法
import datetime
import uuid
import paramiko
class scan_job(object):
def __init__(self, protocol, target, user_name, password, command):
self.guid = uuid.uuid1()
self.start_time = datetime.datetime.now()
self.target = target
self.command = command
self.user_name = user_name
self.password = password
self.protocol = protocol
self.result = ""
def run_job(self):
if self.protocol == 'SSH':
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
print "creating connection"
ssh.connect(self.target, self.user_name, self.password)
print "connected"
stdin, stdout, stderr = ssh.exec_command(self.command)
for line in stdout:
print '... ' + line.strip('\n')
self.result += line.strip('\n')
yield ssh
finally:
print "closing connection"
ssh.close()
print "closed"
else:
print "Unknown protocol"
def show_command(self):
print self.command
test = scan_job('SSH', '192.168.14.10', 'myuser', 'mypassword', 'uname -n')
test.show_command()
test.run_job()
你已经写了发电机的方法,以'yield'声明。这是你的意思吗?生成器创建惰性迭代器。 –
删除'yield ssh'。无论如何,我不知道你为什么拥有它。 –