paramiko的SFTP对象实现Linux的scp功能
2018-06-17 23:32:56来源:未知 阅读 ()
1 #!/usr/bin/env python 2 # -*- coding: UTF-8 -*- 3 4 import paramiko 5 import os 6 import re 7 8 9 class SSHConnection(object): 10 def __init__(self, host, port, username, password): 11 self.host = host 12 self.port = port 13 self.username = username 14 self.password = password 15 self.__k = None 16 17 def run(self): 18 self.connect() 19 self.sftp_put_dir("/opt/app/appops/sbin/collectd/var", "/opt/app/") 20 # self.cmd('ls /opt/app') 21 self.close() 22 23 def connect(self): 24 transport = paramiko.Transport((self.host, self.port)) 25 transport.connect(username=self.username, password=self.password) 26 self.__transport = transport 27 28 def close(self): 29 self.__transport.close() 30 31 def upload(self, loacal_path, target_path): 32 sftp = paramiko.SFTPClient.from_transport(self.__transport) 33 sftp.put(loacal_path, target_path) 34 35 def cmd(self, command): 36 print "commadn in cmd:", command 37 ssh = paramiko.SSHClient() 38 39 ssh._transport = self.__transport 40 stdin, stdout, stderr = ssh.exec_command(command) 41 42 result = stdout.read() 43 print "result:\n", result 44 return result 45 46 def getList(self, path): 47 files_list = [] 48 files = sorted(filter(lambda x: re.match(r'^\w', x), os.listdir(path))) 49 for tmp_file in files: 50 path_file = os.path.join(path, tmp_file) 51 if os.path.isdir(path_file) and not os.path.islink(path_file): 52 files_list.append(path_file) 53 files_list += self.getList(path_file) 54 else: 55 files_list.append(path_file) 56 return files_list 57 58 def sftp_put_dir(self, local_dir, remote_dir): 59 sftp = paramiko.SFTPClient.from_transport(self.__transport) 60 if remote_dir[-1] == '/': 61 remote_dir = remote_dir[0:-1] 62 all_files = self.getList(local_dir) 63 for x in all_files: 64 f_path = x.replace(local_dir, "").lstrip('/') 65 if os.path.isdir(x): 66 r_path = os.path.join(remote_dir, f_path) 67 try: 68 sftp.mkdir(r_path) 69 except Exception,e: 70 pass 71 else: 72 remote_filename = os.path.join(remote_dir, f_path) 73 print u'Put文件%s传输中...' % f_path 74 sftp.put(x, remote_filename) 75 76 77 def main(host, port, username, password): 78 print "in main:" 79 obj = SSHConnection(host, port, username, password) 80 obj.run() 81 82 83 if __name__ == '__main__': 84 host = '' 85 port = '' 86 username = '' 87 password = '' 88 main(host, port, username, password)
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:python
- Python之对象持久化笔记 2019-08-13
- python之函数、面向对象 2019-08-13
- Python的面向对象2 2019-07-24
- Python之路【第九篇】:Python面向对象 2019-07-24
- python 之 并发编程(开启子进程的两种方式,进程对象的属性 2019-07-24
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash