今天我继续给大家介绍paramiko这个模块的其他功能,主要介绍利用paramiko来上传文件到远程主机,呵呵,其实就是paramiko模块中put方法的介绍,下面不废话,直接上代码,大家感兴趣,可以看下:
-
[root@centos6 python]# clear
-
[root@centos6 python]# cat paramiko-upload.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=os.listdir(local_dir)
-
for f in files:
-
print ''
-
print '#########################################'
-
print 'Beginning to upload file %s ' % datetime.datetime.now()
-
print 'Uploading file:',os.path.join(local_dir,f)
-
-
# sftp.get(os.path.join(dir_path,f),os.path.join(local_path,f))
-
sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))
-
-
print 'Upload file success %s ' % datetime.datetime.now()
-
print ''
-
print '##########################################'
-
-
#except Exception:
-
# print "error!"
-
t.close()
-
-
[root@centos6 python]
下面给大家演示下效果:
-
[root@centos6 python]# python paramiko-upload.py
-
-
#########################################
-
Beginning to upload file 2011-10-15 15:02:51.453422
-
Uploading file: /tmp/ipt.out
-
Upload file success 2011-10-15 15:02:53.051348
-
-
##########################################
-
-
#########################################
-
Beginning to upload file 2011-10-15 15:02:53.051500
-
Uploading file: /tmp/ipt.err
-
Upload file success 2011-10-15 15:02:54.304115
-
-
##########################################
-
[root@centos6 python]
在本地文件夹中,机local_dir下面包含文件夹的会报错,大家如果在工作中项使用的话,需要注意这点。
原链接转载:
阅读(1866) | 评论(0) | 转发(0) |