前面我们已经学习了paramiko的上传功能,这里就要给大家介绍下他的下载功能,呵呵,不废话了,直接上代码,感兴趣的可以研究下:
- [root@centos6 python]# cat paramiko-download.py
- #!/usr/bin/env python
- import paramiko
- import os
- import datetime
- hostname='74.63.229.*'
- username='root'
- password='abc123'
- port=22
- local_dir='/tmp/'
- remote_dir='/tmp/test/'
- if __name__=="__main__":
- # try:
- t=paramiko.Transport((hostname,port))
- t.connect(username=username,password=password)
- sftp=paramiko.SFTPClient.from_transport(t)
- # files=sftp.listdir(dir_path)
- files=sftp.listdir(remote_dir)
- for f in files:
- print ''
- print '#########################################'
- print 'Beginning to download file from %s %s ' % (hostname,datetime.datetime.now())
- print 'Downloading file:',os.path.join(remote_dir,f)
- sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f))
- # sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))
- print 'Download file success %s ' % datetime.datetime.now()
- print ''
- print '##########################################'
- #except Exception:
- # print "error!"
- t.close()
- [root@centos6 python]#
呵呵,代码和前面上传功能稍有区别,这里就不写注释了,我的变量名都是和直观的就能让你明白意思了,哈哈,下面看下演示功能吧,看下效果:
- [root@centos6 python]# clear
- [root@centos6 python]# python paramiko-download.py
- #########################################
- Beginning to download file from 74.63.229.* 2011-11-05 15:49:01.334686
- Downloading file: /tmp/test/wgetrc
- Download file success 2011-11-05 15:49:05.955184
- ##########################################
- #########################################
- Beginning to download file from 74.63.229.* 2011-11-05 15:49:05.955342
- Downloading file: /tmp/test/xinetd.conf
- Download file success 2011-11-05 15:49:10.929568
- ##########################################
- #########################################
- Beginning to download file from 74.63.229.* 2011-11-05 15:49:10.929740
- Downloading file: /tmp/test/warnquota.conf
- Download file success 2011-11-05 15:49:14.213570
- ##########################################
呵呵,效果还是不错的,至此,paramiko的上传下载都已经介绍完 了,呵呵,下面讲虾米内容呢,千万别走开,精彩内容继续为你放松,下一次,我将为你介绍和前面讲过的,读取配置文件,上传批量文件到多部服务器,敬请关注。。。