我學習Python和Python的腳本在我的學習道路運行遠程SSH命令 腳本本身運行正常,但它打破當我要進行實驗類繼承功能。Python類繼承,缺少屬性
原創劇本pyssh.py:
#!/usr/bin/env python
import sys
import socket
import paramiko
#=================================
# Class: PySSH
#=================================
class PySSH:
def __init__ (self):
self.ssh = None
self.transport = None
def disconnect (self):
if self.transport is not None:
self.transport.close()
if self.ssh is not None:
self.ssh.close()
def connect(self,hostname,username,password,port=22):
self.hostname = hostname
self.username = username
self.password = password
self.ssh = paramiko.SSHClient()
#Don't use host key auto add policy for production servers
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.load_system_host_keys()
try:
self.ssh.connect(hostname,port,username,password)
self.transport=self.ssh.get_transport()
except (socket.error,paramiko.AuthenticationException) as message:
print "ERROR: SSH connection to "+self.hostname+" failed: " +str(message)
sys.exit(1)
return self.transport is not None
def runcmd(self,cmd,sudoenabled=False):
if sudoenabled:
fullcmd="echo " + self.password + " | sudo -S -p '' " + cmd
else:
fullcmd=cmd
if self.transport is None:
return "ERROR: connection was not established"
session=self.transport.open_session()
session.set_combine_stderr(True)
#print "fullcmd ==== "+fullcmd
if sudoenabled:
session.get_pty()
session.exec_command(fullcmd)
stdout = session.makefile('rb', -1)
#print stdout.read()
output=stdout.read()
session.close()
return output
#===========================================
# MAIN
#===========================================
if __name__ == '__main__':
hostname = 'server1'
username = 'admin'
password = 'Password123'
ssh = PySSH()
ssh.connect(hostname,username,password)
output=ssh.runcmd('date')
print output
output=ssh.runcmd('service sshd status',True)
print output
ssh.disconnect()
現在我想用擰乾的新腳本pyssh2.sh
#!/usr/bin/env python
from pyssh import PySSH
class PySSHT(PySSH):
def connect(self,hostname):
self.ssh = PySSH()
self.username = 'admin'
self.password = 'Password1'
self.ssh.connect(hostname,self.username,self.password)
host = 'server1'
ssh = PySSHT()
ssh.connect(host)
output=ssh.runcmd('date')
print output
output=ssh.runcmd('service sshd status',True)
print output
ssh.disconnect()
它給了這個錯誤,測試類的繼承,看來自我的價值。在ssh.connect()中分配的傳輸在runcmd()中丟失。有沒有簡單的類繼承規則我缺少?
[[email protected] ~]# ./pyssh2.py
ERROR: connection was not established
ERROR: connection was not established
Traceback (most recent call last):
File "./pyssh2.py", line 17, in <module>
ssh.disconnect()
File "/root/pyssh.py", line 19, in disconnect
self.ssh.close()
AttributeError: PySSH instance has no attribute 'close
爲了工作,你應該改變你的最後一行'ssh.disconnect()''到ssh.ssh.disconnect()'。 – snahor 2014-10-30 02:05:31