此處的總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'。無論如何,我不知道你爲什麼擁有它。 –