paramiko操作详解(封装好的类,可以直接使用)

时间:2024-12-13 22:33:38
#!/usr/bin/env python
#encoding:utf8
#author: djoker import paramiko class myParamiko:
def __init__(self,hostip,username,password,port=22):
self.hostip = hostip
self.port = port
self.username = username
self.password = password
self.obj = paramiko.SSHClient()
self.obj.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.obj.connect(self.hostip,self.port,self.username,self.password)
self.objsftp = self.obj.open_sftp() def run_cmd(self,cmd):
stdin,stdout,stderr = self.obj.exec_command(cmd)
return stdout.read() def run_cmdlist(self,cmdlist):
self.resultList = []
for cmd in cmdlist:
stdin,stdout,stderr = self.obj.exec_command(cmd)
self.resultList.append(stdout.read())
return self.resultList def get(self,remotepath,localpath):
self.objsftp.get(remotepath,localpath) def put(self,localpath,remotepath):
self.objsftp.put(localpath,remotepath) def getTarPackage(self,path):
list = self.objsftp.listdir(path)
for packageName in list:
stdin,stdout,stderr = self.obj.exec_command("cd " + path +";"
+ "tar -zvcf /tmp/" + packageName
+ ".tar.gz " + packageName)
stdout.read()
self.objsftp.get("/tmp/" + packageName + ".tar.gz","/tmp/" + packageName + ".tar.gz")
self.objsftp.remove("/tmp/" + packageName + ".tar.gz")
print "get package from " + packageName + " ok......" def close(self):
self.objsftp.close()
self.obj.close() if __name__ == '__main__':
sshobj = myParamiko('10.10.8.21','root','xxxxxxxx',22)
sshobj.close()