python用paramiko模块默认中只可以上传文件,在网上也没有找到合适的直接上传目录的方法,所以用os.walk方法和paramiko结合写了一个上传目录的方法,代码如下:
#!/usr/bin/env python
import paramiko,datetime,os
hostname='192.168.1.100'
username='root'
password='123456'
port=22
def upload(local_dir,remote_dir):
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp=paramiko.SFTPClient.from_transport(t)
print 'upload file start %s ' % datetime.datetime.now()
for root,dirs,files in os.walk(local_dir):
for filespath in files:
local_file = os.path.join(root,filespath)
a = local_file.replace(local_dir,'')
remote_file = os.path.join(remote_dir,a)
try:
sftp.put(local_file,remote_file)
except Exception,e:
sftp.mkdir(os.path.split(remote_file)[0])
sftp.put(local_file,remote_file)
print "upload %s to remote %s" % (local_file,remote_file)
for name in dirs:
local_path = os.path.join(root,name)
a = local_path.replace(local_dir,'')
remote_path = os.path.join(remote_dir,a)
try:
sftp.mkdir(remote_path)
print "mkdir path %s" % remote_path
except Exception,e:
print e
print 'upload file success %s ' % datetime.datetime.now()
t.close()
except Exception,e:
print e
if __name__=='__main__':
local_dir='/home/soft/'
remote_dir='/tmp/aaa/'
upload(local_dir,remote_dir)
经过多次测试,完美实现。
©著作权归作者所有:来自51CTO博客作者AIOPS_DBA的原创作品,如需转载,请注明出处,否则将追究法律责任
共同学习,写下你的评论
评论加载中...
作者其他优质文章