python的paramiko库是一个功能齐全且强大的库文件,通过使用该库文件我们轻易定制出属于我们的SSH、SFTP工具,这次将会介绍使用paramiko实现sftp功能
在使用sftp功能,首先要建立好安全机制,这个安全机制就要依赖于paramiko的Transport的类。
技术实现路线:
paramiko-->Transport-->SFTPClient
废话不说,直接上代码:
import paramiko
class qqftp(object):
"""docstring for ClassName"""
def __init__(self, hostname,port,username,password):
self.hostname=str(hostname)
self.port=int(port)
self.username=str(username)
self.password=str(password)
def connect(self):
try:
socket=paramiko.Transport((self.hostname,self.port))
socket.connect(username=self.username,password=self.password)
self.sftp=paramiko.SFTPClient.from_transport(socket)
print("#########connect successful#########")
self.sftp.listdir("/")
return 1
except Exception as e:
print("#########connect failure!#########")
print(e)
return 0
def get(self,remotepath,localpath):
try:
#remotepath=get_file[0].strip()
#localpath=get_file[1].strip()
#print remotepath,localpath
self.sftp.get(remotepath,localpath)
print 'download successful'
except:
print(Exception)
def showfile(self,path=r'./'):
try:
#self.sftp.chdir(path)
index=path.find('*')
if index!=-1 :
fset=self.sftp.listdir('./')
for f in fset:
if f.find(path[0:index])!=-1:
print self.sftp.lstat(f),f
return 1
filename=self.sftp.listdir(path)
#print self.sftp.getcwd()
if len(filename)>0:
for f in filename:
print self.sftp.lstat(f),f
print
except:
try:
print self.sftp.lstat(path),path
except Exception as e:
print(e)
def chgdir(self,path=r'./'):
try:
self.sftp.chdir(path)
print self.sftp.getcwd()
except:
print(Exception)
def showpwd(self,path=r'./'):
try:
print self.sftp.getcwd()
except:
print(Exception)
def put(self,localpath,remotepath):
try:
self.sftp.put(localpath,remotepath)
print 'Upload successful!'
except:
print(Exception)