python通过paramiko复制远程文件及文件目录到本地
最近写运维自动化平台,需要用python写很多的小功能模块。
这里就分享一个用Python的paramiko来实现功能的一段代码:
复制远程服务器上的文件及文件夹到本地目录。
解释一下什么叫paramiko:
paramiko是用python写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。利用该模块,可以方便的进行ssh连接和sftp协议进行sftp文件传输以及远程命令执行。
安装paramiko也很简单,我用的是python3,装好了pip,可以直接用pip来安装。
不过由于paramiko模块内部依赖pycrypto,所以先下载安装pycrypto:
pip3installpycrypto pip3installparamiko
好了。我定义一个方法,用于远程复制文件。代码如下:
importos importparamiko defRemoteScp(host_ip,host_port,host_username,host_password,remote_file,local_file): scp=paramiko.Transport((host_ip,host_port)) scp.connect(username=host_username,password=host_password) sftp=paramiko.SFTPClient.from_transport(scp) sftp.get(remote_file,local_file) scp.close() return("success")
注意这里的语句:
sftp.get(remote_file,local_file)中自带的get方法,只能拷贝文件目录,不能拷贝文件夹。
然后调用这个方法:
if__name__=='__main__': host_ip='192.168.1.123' host_port=22 host_username='root' host_password='password' remote_path='/tmp/test.sql' local_path='/tmp/test.sql' RemoteScp(host_ip,host_port,host_username,host_password,remote_path,local_path)
这就是基本远程文件复制的功能实现。这里只能实现文件对文件的远程复制。
如果我们要远程复制整个文件夹。需要对上面的方法改进一下,加一段循环,让其能遍历远程目录里的所有文件,然后按照上面的方法依次复制到本地。
我在代码中加了一些注释。修改以后的完整代码如下:
importos importparamiko defRemoteScp(host_ip,host_port,host_username,host_password,remote_path,local_path): scp=paramiko.Transport((host_ip,host_port)) scp.connect(username=host_username,password=host_password) sftp=paramiko.SFTPClient.from_transport(scp) try: remote_files=sftp.listdir(remote_path) forfileinremote_files:#遍历读取远程目录里的所有文件 local_file=local_path+file remote_file=remote_path+file sftp.get(remote_file,local_file) exceptIOError:#如果目录不存在则抛出异常 return("remote_pathorlocal_pathisnotexist") scp.close() if__name__=='__main__': host_ip='192.168.1.123'#远程服务器IP host_port=22#远程服务器端口 host_username='root'#远程服务器用户名 host_password='password'#远程服务器密码 remote_path='/tmp/'#这个是远程目录 local_path='/tmp/'#这个是本地目录 RemoteScp(host_ip,host_port,host_username,host_password,remote_path,local_path)#调用方法
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。