paramiko模块的安装和使用(含上传本地文件或文件夹到服务器,以及下载服务器文件到本地)
安装和使用分两步介绍:
介绍一下,本文的运行环境是win7 64位 和python 2.7 。
安装:
WIN7_64位 安装python-ssh访问模块(paramiko)的安装教程,本人亲测下面教程没问题的,所以可以放心按步骤进行操作
参考地址:
http://jingyan.baidu.com/article/fdbd4277c629c9b89e3f4828.html
使用:
1. paramiko连接
使用paramiko模块有两种连接方式,一种是通过paramiko.SSHClient()函数,另外一种是通过paramiko.Transport()函数。
方法一:
- import paramiko
- ssh = paramiko.SSHClient()
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- ssh.connect("某IP地址",22,"用户名", "口令")
方法二:
- import paramiko
- t = paramiko.Transport(("主机","端口"))
- t.connect(username = "用户名", password = "口令")
如果连接远程主机需要提供密钥,上面第二行代码可改成:
- t.connect(username = "用户名", password = "口令", hostkey="密钥")
2. 上传本地文件到服务器:
- #!/usr/bin/python
- # -*- coding:utf-8 -*-
- import paramiko
- if __name__ == '__main__':
- host_ip = '10.*.*.*'
- port = ''
- username1 = '***'
- password1 = '***'
- t = paramiko.Transport(host_ip, port)
- t.connect(username=username1, password=password1)
- sftp = paramiko.SFTPClient.from_transport(t)
- remotepath = r'/home/temp/b.txt'
- localpath = r'D:\aaa\a.txt'
- sftp.put(localpath, remotepath)
- t.close()
3. 下载服务器文件到本地:
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- import paramiko
- import os
- def remote_scp(host_ip, port, remote_path, local_path, username, password):
- port= port or 22
- t = paramiko.Transport((host_ip, port))
- t.connect(username=username, password=password)
- sftp = paramiko.SFTPClient.from_transport(t)
- src = remote_path
- des = local_path
- sftp.get(src, des)
- t.close()
- if __name__ == '__main__':
- host_ip = '10.*.*.*'
- remote_path = '/home/temp/a.txt'
- local_path = r'D:\aaa\a.txt'
- part_path= os.path.dirname(local_path)
- if not os.path.exists(part_path):
- os.makedirs(part_path)
- username = '***'
- password = '****'
- remote_scp(host_ip, 22, remote_path, local_path, username, password)
4. ssh连接服务器:
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import paramiko
- def ssh2(ip, username, passwd, cmd):
- try:
- ssh = paramiko.SSHClient()
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- ssh.connect(ip, 22, username, passwd, timeout=50)
- stdin, stdout, stderr = ssh.exec_command(cmd)
- # stdin.write("Y") #简单交互,输入 ‘Y’
- print stdout.read()
- # for x in stdout.readlines():
- # print x.strip("\n")
- print '%s\tOK\n' % (ip)
- ssh.close()
- except:
- print '%s\tError\n' % (ip)
- if __name__ == '__main__':
- host_ip = '10.*.*.*'
- port = ''
- username1 = '***'
- password1 = '***'
- ssh2(host_ip, username1, password1, 'less /home/temp/a.txt')
5. 目录下多个文件的上传下载:
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import paramiko, datetime, os
- host_ip = '10.*.*.*'
- username1 = '***'
- password1 = '****'
- port = 22
- local_dir = 'd:/aaa'
- remote_dir = '/home/temp/Templates'
- try:
- t = paramiko.Transport(host_ip, port)
- t.connect(username=username1, password=password1)
- sftp = paramiko.SFTPClient.from_transport(t)
- files = os.listdir(local_dir) # 上传多个文件
- # files = sftp.listdir(remote_dir) # 下载多个文件
- for f in files:
- print ''
- print '#########################################'
- print 'Beginning to download file from %s %s ' % (host_ip, datetime.datetime.now())
- print 'Downloading file:', (remote_dir + '/' + f)
- # sftp.get(remote_dir + '/' + f, os.path.join(local_dir, f)) # 下载多个文件
- sftp.put(os.path.join(local_dir, f), remote_dir + '/' + f) # 上传多个文件
- print 'Download file success %s ' % datetime.datetime.now()
- print ''
- print '##########################################'
- t.close()
- except Exception:
- print "connect error!"
6. 递归上传目录里面的文件或是文件夹到多个服务器
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import paramiko
- import datetime
- import os
- def upload(local_dir, remote_dir, hostname, port, username, password):
- 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):
- print('[%s][%s][%s]' % (root, dirs, files))
- for filespath in files:
- local_file = os.path.join(root, filespath)
- print(11, '[%s][%s][%s][%s]' % (root, filespath, local_file, local_dir))
- a = local_file.replace(local_dir, '').replace('\\', '/').lstrip('/')
- print('', a, '[%s]' % remote_dir)
- remote_file = os.path.join(remote_dir, a).replace('\\', '/')
- print(22, remote_file)
- try:
- sftp.put(local_file, remote_file)
- except Exception as e:
- sftp.mkdir(os.path.split(remote_file)[0])
- sftp.put(local_file, remote_file)
- print("66 upload %s to remote %s" % (local_file, remote_file))
- for name in dirs:
- local_path = os.path.join(root, name)
- print(0, local_path, local_dir)
- a = local_path.replace(local_dir, '').replace('\\', '/').lstrip('/')
- print(1, a)
- print(1, remote_dir)
- # remote_path = os.path.join(remote_dir, a).replace('\\', '/')
- remote_path = remote_dir + a
- print(33, remote_path)
- try:
- sftp.mkdir(remote_path)
- print(44, "mkdir path %s" % remote_path)
- except Exception as e:
- print(55, e)
- print('77,upload file success %s ' % datetime.datetime.now())
- t.close()
- except Exception as e:
- print(88, e)
- if __name__ == '__main__':
- # 选择上传到那个服务器
- serverlist = ['服务器00', '服务器01', '服务器02']
- for i in range(len(serverlist)):
- print ("序号:%s 对应的服务器为:%s" % (i, serverlist[i]))
- num = raw_input("请输入对应服务器的序号:")
- num = int(num)
- hostname = ['10.*.*.*', '10.*.*.*', '10.*.*.*']
- username = ['root', 'root', 'root']
- password = ['***', '***', '***']
- port = [22, 22, 22]
- local_dir = r'D:\aaa'
- remote_dir = '/home/temp/dd/'
- upload(local_dir, remote_dir, hostname=hostname[num], port=port[num], username=username[num],
- password=password[num])
7. 利用paramiko实现ssh的交互式连接
以下是通过paramiko模块直接用ssh协议登陆到远程服务器的操作代码,这里先定义一个interactive模块(即 interactive.py),
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import socket
- import sys
- # windows does not have termios...
- try:
- import termios
- import tty
- has_termios = True
- except ImportError:
- has_termios = False
- def interactive_shell(chan):
- if has_termios:
- posix_shell(chan)
- else:
- windows_shell(chan)
- def posix_shell(chan):
- import select
- oldtty = termios.tcgetattr(sys.stdin)
- try:
- tty.setraw(sys.stdin.fileno())
- tty.setcbreak(sys.stdin.fileno())
- chan.settimeout(0.0)
- while True:
- r, w, e = select.select([chan, sys.stdin], [], [])
- if chan in r:
- try:
- x = chan.recv(1024)
- if len(x) == 0:
- print '\r\n*** EOF\r\n',
- break
- sys.stdout.write(x)
- sys.stdout.flush()
- except socket.timeout:
- pass
- if sys.stdin in r:
- x = sys.stdin.read(1)
- if len(x) == 0:
- break
- chan.send(x)
- finally:
- termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
- # thanks to Mike Looijmans for this code
- def windows_shell(chan):
- import threading
- sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")
- def writeall(sock):
- while True:
- data = sock.recv(256)
- if not data:
- sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
- sys.stdout.flush()
- break
- sys.stdout.write(data)
- sys.stdout.flush()
- writer = threading.Thread(target=writeall, args=(chan,))
- writer.start()
- try:
- while True:
- d = sys.stdin.read(1)
- if not d:
- break
- chan.send(d)
- except EOFError:
- # user hit ^Z or F6
- pass
写一个ssh_inter.py的交互主程序调用interactive模块,代码如下:
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import paramiko
- import interactive
- if __name__ == '__main__':
- host_ip = '10.*.*.*'
- username1 = '***'
- password1 = '***'
- port = 22
- # 记录日志写到本地文件中
- paramiko.util.log_to_file(r'D:/aaa/wu.txt')
- # 建立ssh连接
- ssh = paramiko.SSHClient()
- ssh.load_system_host_keys()
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- ssh.connect(host_ip, port=22, username=username1, password=password1, compress=True)
- # 建立交互式shell连接
- channel = ssh.invoke_shell()
- # 建立交互式管道
- interactive.interactive_shell(channel)
- # 关闭连接
- channel.close()
- ssh.close()
总结:
paramiko模块是一个比较强大的ssh连接模块,以上的示例只是列出了该模块的一些简单的使用方法,还可以使用threading模块加块程序并发的速度;也可以使用configparser模块处理配置文件,而我们将所有IP、用户信息操作都放入配置文件;使用setproctitle模块为执行的程序加一个容易区分的title等。
同样,虽然连fabric这样大名鼎鼎的软件使用的ssh都是用paramiko模块进行的封装,不过你依然可以选择不使用它,你也可以选择pexpect模块实现封装一个简易的ssh连接工具、或者使用同样比较火的salt-ssh模块。
参考文章:
paramiko模块的安装和使用(含上传本地文件或文件夹到服务器,以及下载服务器文件到本地)的更多相关文章
- python paramiko模拟ssh登录,实现sftp上传或者下载文件
Python Paramiko模块的安装与使用详解 paramiko是短链接,不是持续链接,只能执行你设定的shell命令,可以加分号执行两次命令. http://www.111cn.net/phpe ...
- Windows下GIT安装与使用(上传远程端)
Windows下GIT安装与使用(上传远程服务器) 1. 登陆http://msysgit.github.io/并下载Git 2. 打开下载的exe文件,一路默认(路径可以去修改).有可能电脑需要 ...
- Git安装配置及第一次上传项目到GitHub
平时的学习工作少不了保存自己的Code到代码库,这里必须要使用到Git与GitHub. 1. 关于Git的安装 下载Git:下载地址:https://git-scm.com/downloads ...
- 微信小程序云函数中有以下未安装的依赖,如果未安装即全量上传
云函数中有以下未安装的依赖,如果未安装即全量上传 在新建的云函数,右击终端打开->cmd,安装依赖 npm install --production 依赖安装成功之后,文件里面会出现 packa ...
- python selectors模块实现 IO多路复用机制的上传下载
import selectorsimport socketimport os,time BASE_DIR = os.path.dirname(os.path.abspath(__file__))''' ...
- spring mvc 图片上传,图片压缩、跨域解决、 按天生成文件夹 ,删除,限制为图片代码等相关配置
spring mvc 图片上传,跨域解决 按天生成文件夹 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ ...
- python的paramiko模块的安装与使用
一:简介 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 由于使用的是python这样的能够跨平台运行的语言,所以所有python支 ...
- paramiko模块的安装
1.找到自己python安装的目录(默认路径:C:\Users\zhangliyuan\AppData\Local\Programs\Python\Python35) 注:cmd中所有命令 2.进入S ...
- python在windows下安装paramiko模块和安装pycrypto模块(3步搞定)(转)
Python中使用SSH需要用到OpenSSH,而OpenSSH依赖于paramiko模块,而paramiko模块又依赖于pycrypto模块,因此要在Python中使用SSH,我们需要先安装pycr ...
随机推荐
- 微信开发准备(二)--springmvc+mybatis项目结构的搭建
转自:http://www.cuiyongzhi.com/post/34.html 前面一篇有说道如何在MyEclipse中搭建maven项目,这里将继续介绍如何在搭建好的基础maven项目中引入我们 ...
- Struts旅程(六)Struts页面转发控制ActionForward和ActionMapping
转自:https://blog.csdn.net/lovesummerforever/article/details/19125933
- mybatis(非常详细的哦~~~~)
备注:ibatis 迁入google code 更名为Mybatis 官方文档:http://mybatis.org/mybatis-3/ 比较好的教程推荐:http://www.blogjava.n ...
- springboot整合mybatis+generator
源码地址:springboot-integration 如果你觉得解决了你使用的需求,欢迎fork|star.
- [转]AJAX工作原理及其优缺点
1.什么是AJAX?AJAX全称为“Asynchronous JavaScript and XML”(异步JavaScript和XML),是一种创建交互式网页应用的网页开发技术.它使用:使用XHTML ...
- ROS Learning-001 安装 ROS indigo
如何在 Ubuntu14.04 上安装 ROS indigo 我使用的虚拟机软件:VMware Workstation 11 使用的Ubuntu系统:Ubuntu 14.04.4 LTS ROS 版本 ...
- 算法Sedgewick第四版-第1章基础-005一封装输入(可以文件,jar包里的文件或网址)
1. package algorithms.util; /*********************************************************************** ...
- 100211D Police Cities
传送门 分析 看到这个题我们的第一反应自然是Tarjan缩点,在这之后我们可以发现实际只要在缩点之后所有出度或入度为0的点布置警察局就可以达到要求,我们用dpij表示考虑前i个出度或入度为0的点共布置 ...
- CH 4302 Interval GCD
辗转相减法的扩展 $gcd(x, y, z) = gcd(x, y - x, z - y)$ 当有n个数时也成立 所以构造$a_{i}$的差分数组$b_{i} = a_{i} - a_{i - 1}$ ...
- Java中抽象类也能实例化.RP
在Java中抽象类真的不能实例化么? 在学习的过程中,发现了一个问题,抽象类在没有实现所有的抽象方法前是不可以通过new来构建该对象的,但是抽象方法却是可以有自己的构造方法的.这样就把我搞糊涂了,既然 ...