安装和使用分两步介绍:

介绍一下,本文的运行环境是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模块。

参考文章:

  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. 1106SQLserver基础--变量、运算符的使用,if...else,while语句

    数据库---变量(对数据库中的数据没有任何影响) 作用:临时存储数据的作用,起一个衔接的作用,为了方便理解存储过程. 例:Declare @hello varchar(20) Set @hello=’ ...

  2. cygwin选择安装包选项搭建NDK开发环境/配置cygwin的root权限

    9.Search是可以输入你要下载的包的名称,能够快速筛选出你要下载的包.那四个单选按钮是选择下边树的样式,默认就行,不用动.View默认是Category,建议改成full显示全部包再查,省的一些包 ...

  3. SQL基础E-R图基础

    ER图分为实体.属性.关系三个核心部分.实体是长方形体现,而属性则是椭圆形,关系为菱形. ER图的实体(entity)即数据模型中的数据对象,例如人.学生.音乐都可以作为一个数据对象,用长方体来表示, ...

  4. 第2章 构建springboot工程 2-1 构建SpringBoot第一个demo

    以后的趋势肯定是以一个微服务为主导的, Spring-Boot的指导 Maven整个环境构建之前的整个项目其实是一个很普通的J2SE项目,它构建完之后会进行重构,重构为Maven的一个项目路径.可以看 ...

  5. JPA entityManagerFactory配置详解

    以下是本人的一些理解 如有误的地方欢迎指出 谢谢! jpa.LocalContainerEntityManagerFactoryBean 与 hibernate的sessionFactory一样都实现 ...

  6. 使用Javascript Ajax 通信操作JSON数据 [上]

    以前只是知道json的格式而已,也做过的是从数据库获得数据然后弄成json的格式然后赋给HighCharts生成曲线,先把数据库的数据使用array()函数转换成数组,然后使用json_encode( ...

  7. 04 UUID

    1 什么是UUID UUID 的目的是让分布式系统中的所有元素,都能有唯一的辨识资讯,而不需要透过中央控制端来做辨识资讯的指定. 2 应用场景 MySQL数据库不能想oracle数据库那样创建序列,就 ...

  8. WINFORM 无边框窗体 阴影与移动

    //窗体移动API[DllImport("user32.dll")]public static extern bool ReleaseCapture();[DllImport(&q ...

  9. Tensorflow学习练习-卷积神经网络应用于手写数字数据集训练

    # coding: utf-8 import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data mn ...

  10. Hibernate 处理查询 in 字句

    from : http://blog.csdn.net/wodestudy/article/details/38200421 在处理hibernate的实体查询,一般可以采用多种方式处理复杂的查询,比 ...