Python中paramiko模块的使用
2016-01-18 14:45
585 查看
paramiko支持SSH协议,可以与Linux或Windows(搭建了SSH服务)进行交互,包括远程执行命令或执行上传/下载文件等操作。
代码如下:
代码如下:
import os import paramiko def exec_command(ip, port, username, password, cmd): """远程执行命令 """ paramiko.util.log_to_file("paramiko.log") ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=ip, port=int( port), username=username, password=password, timeout=5) stdin, stdout, stderr = ssh.exec_command('cmd.exe /C "%s"' % cmd) ssh.close() def upload_file(ip, port, username, password, local_file_path, remote_file_path): """上传文件 """ paramiko.util.log_to_file("paramiko.log") trans = paramiko.Transport((ip, int(port))) trans.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(trans) sftp.put(local_file_path, remote_file_path) trans.close() def download_file(ip, port, username, password, local_file_path, remote_file_path): """下载文件 """ paramiko.util.log_to_file("paramiko.log") trans = paramiko.Transport((ip, int(port))) trans.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(trans) sftp.get(remote_file_path, local_file_path) trans.close() def upload_dir(ip, port, username, password, local_dir, remote_dir): """上传目录(从windows上传) """ paramiko.util.log_to_file("paramiko.log") trans = paramiko.Transport((ip, int(port))) trans.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(trans) try: sftp.mkdir(remote_dir) except Exception, e: pass for root, dirs, files in os.walk(local_dir): for file_name in files: local_file_path = os.path.join(root, file_name) remote_file_path = os.path.join( remote_dir, local_file_path[3:]) # 切片:windows路径去掉盘符 remote_file_path = remote_file_path.replace("\\", "/") try: sftp.put(local_file_path, remote_file_path) except Exception, e: sftp.mkdir(os.path.dirname(remote_file_path)) sftp.put(local_file_path, remote_file_path) for dir_name in dirs: local_dir = os.path.join(root, dir_name) remote_path = os.path.join(remote_dir, local_dir[3:]) remote_path = remote_path.replace("\\", "/") try: sftp.mkdir(os.path.dirname(remote_path)) sftp.mkdir(remote_path) except Exception, e: pass trans.close()
相关文章推荐
- 32. Longest Valid Parentheses leetcode python new season 2016
- 安装numpy只需一步简单的方法
- 利用python将alfw转换成bing标注格式
- 31. Next Permutation leetcode Python 2016 new Season
- python(1) - 安装篇
- python学习----------正则表达式
- python 和 sqlmap的安装使用
- Python 4.3 继承和多态
- python中基于descriptor的一些概念
- ubuntu 文件重命名
- 用python将SQL格式文件改成自己想要的格式
- python 深浅拷贝
- Python算法题----逆序列表
- Python Tkinter Grid布局管理器详解
- 如何让你的Python代码更加pythonic ?
- Python--day1
- python中的 \r以及基于此实现简单的倒计时小程序
- 笨方法学python(ex1-17)--%,input,解包,读取,写文件
- 《Python for kids》学习笔记(二)
- 用python做自动化测试--对Java代码做单元测试 (1)