paramiko远程连接linux服务器进行上传下载文件

花了不少时间来研究paramiko中sftpclient的文件传输,一顿操作猛如虎,最后就一直卡在了路径报错问题,疯狂查阅资料借鉴大佬们的心得,还是搞不好,睡了个午觉醒来,仔细一看原来是指定路径的文件不存在,然后我下去买了个雪糕冷静了下。留下代码,供大家借鉴,可以直接拿来用就行了。

import paramiko

class Linux(object):

def __init__(self,ip,username,password,timout = 30):
self.hostname = ip
self.username = username
self.password = password
self.port = 22
self.t = ''
self.chan = ''
#连接重试次数
self.try_times = 3
#调用改方法连接linux主机
def conn(self):
pass
#断开连接
def close(self):
pass
#发送要执行的命令
def send(self):
pass
#上传文件
def sftp_put(self,localfile,remotefile):
# 设置SSH连接的远程主机地址和端口
t = paramiko.Transport((self.hostname, 22))
# 设置登陆用户名和密码等参数
t.connect(username=self.username, password=self.password)
#将实例化的Transport作为参数传入SFTPClient中
sftp = paramiko.SFTPClient.from_transport(t)
# 将本地的test.txt put到远端,并保持为test.txt
sftp.put(localfile,remotefile)
#关闭连接
t.close()
# 下载文件
def sftp_get(self,remotefile,newlocalfile):

t = paramiko.Transport((self.hostname, 22))

t.connect(username=self.username, password=self.password)

sftp = paramiko.SFTPClient.from_transport(t)
# 将远端的test.txt put到远端,并保持为newtest.txt
sftp.get(remotefile,newlocalfile )
# 关闭连接
t.close()



if __name__ == '__main__':
localpath = r'I:\Meitu\数据库密码.txt'
remotepath = r'/usr/local/test/数据库密码.txt'
newlocalpath = r'I:\Meitu\newtest.gz'
host = Linux('192.168.55.158', 'root', '1')
host.sftp_put(localpath,remotepath)
host.sftp_get(remotepath,newlocalpath)

猜你喜欢

转载自www.cnblogs.com/liuage/p/11016641.html