安装和使用分两步介绍:

介绍一下,本文的运行环境是win7 64位 和python 2.7  。

安装:

  WIN7_64位 安装python-ssh访问模块(paramiko)的安装教程,本人亲测下面教程没问题的,所以可以放心按步骤进行操作

参考地址:

http://jingyan.baidu.com/article/fdbd4277c629c9b89e3f4828.html

使用:

1. paramiko连接

  使用paramiko模块有两种连接方式,一种是通过paramiko.SSHClient()函数,另外一种是通过paramiko.Transport()函数。

  方法一:  

  1. import paramiko
  2. ssh = paramiko.SSHClient()
  3. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  4. ssh.connect("某IP地址",22,"用户名", "口令")

  方法二:

  1. import paramiko
  2. t = paramiko.Transport(("主机","端口"))
  3. t.connect(username = "用户名", password = "口令")

如果连接远程主机需要提供密钥,上面第二行代码可改成:

  1. t.connect(username = "用户名", password = "口令", hostkey="密钥")

2. 上传本地文件到服务器:

  1. #!/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3.  
  4. import paramiko
  5.  
  6. if __name__ == '__main__':
  7. host_ip = '10.*.*.*'
  8. port = ''
  9. username1 = '***'
  10. password1 = '***'
  11. t = paramiko.Transport(host_ip, port)
  12. t.connect(username=username1, password=password1)
  13. sftp = paramiko.SFTPClient.from_transport(t)
  14. remotepath = r'/home/temp/b.txt'
  15. localpath = r'D:\aaa\a.txt'
  16. sftp.put(localpath, remotepath)
  17. t.close()

3. 下载服务器文件到本地:

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import paramiko
  4. import os
  5.  
  6. def remote_scp(host_ip, port, remote_path, local_path, username, password):
  7. port= port or 22
  8. t = paramiko.Transport((host_ip, port))
  9. t.connect(username=username, password=password)
  10. sftp = paramiko.SFTPClient.from_transport(t)
  11. src = remote_path
  12. des = local_path
  13. sftp.get(src, des)
  14. t.close()
  15.  
  16. if __name__ == '__main__':
  17. host_ip = '10.*.*.*'
  18. remote_path = '/home/temp/a.txt'
  19. local_path = r'D:\aaa\a.txt'
  20. part_path= os.path.dirname(local_path)
  21. if not os.path.exists(part_path):
  22. os.makedirs(part_path)
  23. username = '***'
  24. password = '****'
  25. remote_scp(host_ip, 22, remote_path, local_path, username, password)

4. ssh连接服务器:

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import paramiko
  4.  
  5. def ssh2(ip, username, passwd, cmd):
  6. try:
  7. ssh = paramiko.SSHClient()
  8. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  9. ssh.connect(ip, 22, username, passwd, timeout=50)
  10. stdin, stdout, stderr = ssh.exec_command(cmd)
  11. # stdin.write("Y") #简单交互,输入 ‘Y’
  12. print stdout.read()
  13. # for x in stdout.readlines():
  14. # print x.strip("\n")
  15. print '%s\tOK\n' % (ip)
  16. ssh.close()
  17. except:
  18. print '%s\tError\n' % (ip)
  19.  
  20. if __name__ == '__main__':
  21. host_ip = '10.*.*.*'
  22. port = ''
  23. username1 = '***'
  24. password1 = '***'
  25. ssh2(host_ip, username1, password1, 'less /home/temp/a.txt')

5. 目录下多个文件的上传下载:

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import paramiko, datetime, os
  4.  
  5. host_ip = '10.*.*.*'
  6. username1 = '***'
  7. password1 = '****'
  8. port = 22
  9. local_dir = 'd:/aaa'
  10. remote_dir = '/home/temp/Templates'
  11. try:
  12. t = paramiko.Transport(host_ip, port)
  13. t.connect(username=username1, password=password1)
  14. sftp = paramiko.SFTPClient.from_transport(t)
  15. files = os.listdir(local_dir) # 上传多个文件
  16. # files = sftp.listdir(remote_dir) # 下载多个文件
  17. for f in files:
  18. print ''
  19. print '#########################################'
  20. print 'Beginning to download file from %s %s ' % (host_ip, datetime.datetime.now())
  21. print 'Downloading file:', (remote_dir + '/' + f)
  22. # sftp.get(remote_dir + '/' + f, os.path.join(local_dir, f)) # 下载多个文件
  23. sftp.put(os.path.join(local_dir, f), remote_dir + '/' + f) # 上传多个文件
  24. print 'Download file success %s ' % datetime.datetime.now()
  25. print ''
  26. print '##########################################'
  27. t.close()
  28. except Exception:
  29. print "connect error!"

6. 递归上传目录里面的文件或是文件夹到多个服务器

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import paramiko
  4. import datetime
  5. import os
  6.  
  7. def upload(local_dir, remote_dir, hostname, port, username, password):
  8. try:
  9. t = paramiko.Transport((hostname, port))
  10. t.connect(username=username, password=password)
  11. sftp = paramiko.SFTPClient.from_transport(t)
  12. print('upload file start %s ' % datetime.datetime.now())
  13. for root, dirs, files in os.walk(local_dir):
  14. print('[%s][%s][%s]' % (root, dirs, files))
  15. for filespath in files:
  16. local_file = os.path.join(root, filespath)
  17. print(11, '[%s][%s][%s][%s]' % (root, filespath, local_file, local_dir))
  18. a = local_file.replace(local_dir, '').replace('\\', '/').lstrip('/')
  19. print('', a, '[%s]' % remote_dir)
  20. remote_file = os.path.join(remote_dir, a).replace('\\', '/')
  21. print(22, remote_file)
  22. try:
  23. sftp.put(local_file, remote_file)
  24. except Exception as e:
  25. sftp.mkdir(os.path.split(remote_file)[0])
  26. sftp.put(local_file, remote_file)
  27. print("66 upload %s to remote %s" % (local_file, remote_file))
  28. for name in dirs:
  29. local_path = os.path.join(root, name)
  30. print(0, local_path, local_dir)
  31. a = local_path.replace(local_dir, '').replace('\\', '/').lstrip('/')
  32. print(1, a)
  33. print(1, remote_dir)
  34. # remote_path = os.path.join(remote_dir, a).replace('\\', '/')
  35. remote_path = remote_dir + a
  36. print(33, remote_path)
  37. try:
  38. sftp.mkdir(remote_path)
  39. print(44, "mkdir path %s" % remote_path)
  40. except Exception as e:
  41. print(55, e)
  42. print('77,upload file success %s ' % datetime.datetime.now())
  43. t.close()
  44. except Exception as e:
  45. print(88, e)
  46.  
  47. if __name__ == '__main__':
  48. # 选择上传到那个服务器
  49. serverlist = ['服务器00', '服务器01', '服务器02']
  50. for i in range(len(serverlist)):
  51. print ("序号:%s 对应的服务器为:%s" % (i, serverlist[i]))
  52. num = raw_input("请输入对应服务器的序号:")
  53. num = int(num)
  54. hostname = ['10.*.*.*', '10.*.*.*', '10.*.*.*']
  55. username = ['root', 'root', 'root']
  56. password = ['***', '***', '***']
  57. port = [22, 22, 22]
  58.  
  59. local_dir = r'D:\aaa'
  60. remote_dir = '/home/temp/dd/'
  61. upload(local_dir, remote_dir, hostname=hostname[num], port=port[num], username=username[num],
  62. password=password[num])

7. 利用paramiko实现ssh的交互式连接

以下是通过paramiko模块直接用ssh协议登陆到远程服务器的操作代码,这里先定义一个interactive模块(即 interactive.py),

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import socket
  4. import sys
  5.  
  6. # windows does not have termios...
  7. try:
  8. import termios
  9. import tty
  10.  
  11. has_termios = True
  12. except ImportError:
  13. has_termios = False
  14.  
  15. def interactive_shell(chan):
  16. if has_termios:
  17. posix_shell(chan)
  18. else:
  19. windows_shell(chan)
  20.  
  21. def posix_shell(chan):
  22. import select
  23. oldtty = termios.tcgetattr(sys.stdin)
  24. try:
  25. tty.setraw(sys.stdin.fileno())
  26. tty.setcbreak(sys.stdin.fileno())
  27. chan.settimeout(0.0)
  28. while True:
  29. r, w, e = select.select([chan, sys.stdin], [], [])
  30. if chan in r:
  31. try:
  32. x = chan.recv(1024)
  33. if len(x) == 0:
  34. print '\r\n*** EOF\r\n',
  35. break
  36. sys.stdout.write(x)
  37. sys.stdout.flush()
  38. except socket.timeout:
  39. pass
  40. if sys.stdin in r:
  41. x = sys.stdin.read(1)
  42. if len(x) == 0:
  43. break
  44. chan.send(x)
  45. finally:
  46. termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
  47.  
  48. # thanks to Mike Looijmans for this code
  49. def windows_shell(chan):
  50. import threading
  51. sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")
  52.  
  53. def writeall(sock):
  54. while True:
  55. data = sock.recv(256)
  56. if not data:
  57. sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
  58. sys.stdout.flush()
  59. break
  60. sys.stdout.write(data)
  61. sys.stdout.flush()
  62.  
  63. writer = threading.Thread(target=writeall, args=(chan,))
  64. writer.start()
  65. try:
  66. while True:
  67. d = sys.stdin.read(1)
  68. if not d:
  69. break
  70. chan.send(d)
  71. except EOFError:
  72. # user hit ^Z or F6
  73. pass

写一个ssh_inter.py的交互主程序调用interactive模块,代码如下:

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import paramiko
  4. import interactive
  5.  
  6. if __name__ == '__main__':
  7. host_ip = '10.*.*.*'
  8. username1 = '***'
  9. password1 = '***'
  10. port = 22
  11. # 记录日志写到本地文件中
  12. paramiko.util.log_to_file(r'D:/aaa/wu.txt')
  13. # 建立ssh连接
  14. ssh = paramiko.SSHClient()
  15. ssh.load_system_host_keys()
  16. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  17. ssh.connect(host_ip, port=22, username=username1, password=password1, compress=True)
  18. # 建立交互式shell连接
  19. channel = ssh.invoke_shell()
  20. # 建立交互式管道
  21. interactive.interactive_shell(channel)
  22. # 关闭连接
  23. channel.close()
  24. ssh.close()

总结:

  paramiko模块是一个比较强大的ssh连接模块,以上的示例只是列出了该模块的一些简单的使用方法,还可以使用threading模块加块程序并发的速度;也可以使用configparser模块处理配置文件,而我们将所有IP、用户信息操作都放入配置文件;使用setproctitle模块为执行的程序加一个容易区分的title等。
同样,虽然连fabric这样大名鼎鼎的软件使用的ssh都是用paramiko模块进行的封装,不过你依然可以选择不使用它,你也可以选择pexpect模块实现封装一个简易的ssh连接工具、或者使用同样比较火的salt-ssh模块。

参考文章:

  1. http://www.111cn.net/phper/python/67973.htm    
  2. http://blog.csdn.net/wawa8899/article/details/52965077#

paramiko模块的安装和使用(含上传本地文件或文件夹到服务器,以及下载服务器文件到本地)的更多相关文章

  1. python paramiko模拟ssh登录,实现sftp上传或者下载文件

    Python Paramiko模块的安装与使用详解 paramiko是短链接,不是持续链接,只能执行你设定的shell命令,可以加分号执行两次命令. http://www.111cn.net/phpe ...

  2. Windows下GIT安装与使用(上传远程端)

    Windows下GIT安装与使用(上传远程服务器) 1.  登陆http://msysgit.github.io/并下载Git 2.  打开下载的exe文件,一路默认(路径可以去修改).有可能电脑需要 ...

  3. Git安装配置及第一次上传项目到GitHub

    平时的学习工作少不了保存自己的Code到代码库,这里必须要使用到Git与GitHub. 1.   关于Git的安装 下载Git:下载地址:https://git-scm.com/downloads  ...

  4. 微信小程序云函数中有以下未安装的依赖,如果未安装即全量上传

    云函数中有以下未安装的依赖,如果未安装即全量上传 在新建的云函数,右击终端打开->cmd,安装依赖 npm install --production 依赖安装成功之后,文件里面会出现 packa ...

  5. python selectors模块实现 IO多路复用机制的上传下载

    import selectorsimport socketimport os,time BASE_DIR = os.path.dirname(os.path.abspath(__file__))''' ...

  6. spring mvc 图片上传,图片压缩、跨域解决、 按天生成文件夹 ,删除,限制为图片代码等相关配置

    spring mvc 图片上传,跨域解决 按天生成文件夹 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ ...

  7. python的paramiko模块的安装与使用

    一:简介 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 由于使用的是python这样的能够跨平台运行的语言,所以所有python支 ...

  8. paramiko模块的安装

    1.找到自己python安装的目录(默认路径:C:\Users\zhangliyuan\AppData\Local\Programs\Python\Python35) 注:cmd中所有命令 2.进入S ...

  9. python在windows下安装paramiko模块和安装pycrypto模块(3步搞定)(转)

    Python中使用SSH需要用到OpenSSH,而OpenSSH依赖于paramiko模块,而paramiko模块又依赖于pycrypto模块,因此要在Python中使用SSH,我们需要先安装pycr ...

随机推荐

  1. 微信开发准备(二)--springmvc+mybatis项目结构的搭建

    转自:http://www.cuiyongzhi.com/post/34.html 前面一篇有说道如何在MyEclipse中搭建maven项目,这里将继续介绍如何在搭建好的基础maven项目中引入我们 ...

  2. Struts旅程(六)Struts页面转发控制ActionForward和ActionMapping

    转自:https://blog.csdn.net/lovesummerforever/article/details/19125933

  3. mybatis(非常详细的哦~~~~)

    备注:ibatis 迁入google code 更名为Mybatis 官方文档:http://mybatis.org/mybatis-3/ 比较好的教程推荐:http://www.blogjava.n ...

  4. springboot整合mybatis+generator

    源码地址:springboot-integration 如果你觉得解决了你使用的需求,欢迎fork|star.

  5. [转]AJAX工作原理及其优缺点

    1.什么是AJAX?AJAX全称为“Asynchronous JavaScript and XML”(异步JavaScript和XML),是一种创建交互式网页应用的网页开发技术.它使用:使用XHTML ...

  6. ROS Learning-001 安装 ROS indigo

    如何在 Ubuntu14.04 上安装 ROS indigo 我使用的虚拟机软件:VMware Workstation 11 使用的Ubuntu系统:Ubuntu 14.04.4 LTS ROS 版本 ...

  7. 算法Sedgewick第四版-第1章基础-005一封装输入(可以文件,jar包里的文件或网址)

    1. package algorithms.util; /*********************************************************************** ...

  8. 100211D Police Cities

    传送门 分析 看到这个题我们的第一反应自然是Tarjan缩点,在这之后我们可以发现实际只要在缩点之后所有出度或入度为0的点布置警察局就可以达到要求,我们用dpij表示考虑前i个出度或入度为0的点共布置 ...

  9. CH 4302 Interval GCD

    辗转相减法的扩展 $gcd(x, y, z) = gcd(x, y - x, z - y)$ 当有n个数时也成立 所以构造$a_{i}$的差分数组$b_{i} = a_{i} - a_{i - 1}$ ...

  10. Java中抽象类也能实例化.RP

    在Java中抽象类真的不能实例化么? 在学习的过程中,发现了一个问题,抽象类在没有实现所有的抽象方法前是不可以通过new来构建该对象的,但是抽象方法却是可以有自己的构造方法的.这样就把我搞糊涂了,既然 ...