安装和使用分两步介绍:

介绍一下,本文的运行环境是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. DAY13-前端之JavaScript

    JavaScript概述 JavaScript的历史 1992年Nombas开发出C-minus-minus(C--)的嵌入式脚本语言(最初绑定在CEnvi软件中),后将其改名ScriptEase(客 ...

  2. ListView里面adapter的不同分类的item

    public class PlayAdapter extends BaseAdapter { /** * 标题的item */ public static final int ITEM_TITLE = ...

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

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

  4. TortoiseSVN客户端安装遇到的问题汇总

    在windows server 2003版本上安装32位SVN客户,提示以下错误 1:无法通过windows installer服务安装此安装程序包” 这时需要安装更新的windows install ...

  5. The Apache Tomcat installation at this directory is version 8.5.24 Tomcat 8.0 installation is expect

    在一台新电脑上搭建Java开发环境,JDK 是1.8,Tomcat下载了Tomcat 8.5.24,已经配置好了Java和Tomcat的环境变量,开发工具是Eclipse MARS,准备在Eclips ...

  6. NSSelectorFromString 使用示例

    NSSelectorFromString 动态加载实例方法. SEL sel = NSSelectorFromString(@"yourMethod:")//有参数 if([obj ...

  7. Django框架 之 view视图

    Django框架 之 view视图 浏览目录 概述 简单的视图 HttpRequest对象 CBV和FBV 给视图加装饰器 Request对象 Response对象 JsonResponse对象 Dj ...

  8. 前端学习01-06URL

    URL(Uniform Resource Locator) 统一资源定位 URL的基本组成:协议,主机名,端口号,资源名 例如: http://www.sina.com:80/index.html 相 ...

  9. wordcount小程序

    wordcount小程序 (1)github网址 https://github.com/yuyuyu960818/count_txt_file (2)PSP表 PSP2.1 PSP阶段 预估耗时 (分 ...

  10. WordCount 优化版测试小程序实现

    Stage1:代码编写+单元测试 Github地址: https://github.com/245553473/wcPro.git PSP表格: PSP PSP阶段 预估耗时(分钟) 实际耗时(分钟) ...