系统运维工程师的法宝:python paramiko

简介:
paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。
使用paramiko可以很好的解决以下问题:
需要使用windows客户端,
远程连接到Linux服务器,查看上面的日志状态,批量配置远程服务器,文件上传,文件下载等




"paramiko" is a combination of the esperanto words for "paranoid" and
"friend".  it's a module for python 2.5+ that implements the SSH2 protocol
for secure (encrypted and authenticated) connections to remote machines.
unlike SSL (aka TLS), SSH2 protocol does not require hierarchical
certificates signed by a powerful central authority. you may know SSH2 as
the protocol that replaced telnet and rsh for secure access to remote
shells, but the protocol also includes the ability to open arbitrary
channels to remote services across the encrypted tunnel (this is how sftp
works, for example).


it is written entirely in python (no C or platform-dependent code) and is
released under the GNU LGPL (lesser GPL). 


the package and its API is fairly well documented in the "doc/" folder
that should have come with this archive.




Requirements
------------


 - python 2.5 or better 
 - pycrypto 2.1 or better 


If you have setuptools, you can build and install paramiko and all its
dependencies with this command (as root)::


   easy_install ./




Portability
-----------


i code and test this library on Linux and MacOS X. for that reason, i'm
pretty sure that it works for all posix platforms, including MacOS. it
should also work on Windows, though i don't test it as frequently there.
if you run into Windows problems, send me a patch: portability is important
to me.


some python distributions don't include the utf-8 string encodings, for
reasons of space (misdirected as that is). if your distribution is
missing encodings, you'll see an error like this::


   LookupError: no codec search functions registered: can't find encoding


this means you need to copy string encodings over from a working system.
(it probably only happens on embedded systems, not normal python
installs.) Valeriy Pogrebitskiy says the best place to look is
``.../lib/python*/encodings/__init__.py``.




Bugs & Support
--------------


Please file bug reports at https://github.com/paramiko/paramiko/. There is currently no mailing list but we plan to create a new one ASAP.




Demo
----


several demo scripts come with paramiko to demonstrate how to use it.
probably the simplest demo of all is this::


   import paramiko, base64
   key = paramiko.RSAKey(data=base64.decodestring('AAA...'))
   client = paramiko.SSHClient()
   client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
   client.connect('ssh.example.com', username='strongbad', password='thecheat')
   stdin, stdout, stderr = client.exec_command('ls')
   for line in stdout:
       print '... ' + line.strip('\n')
   client.close()


...which prints out the results of executing ``ls`` on a remote server.
(the host key 'AAA...' should of course be replaced by the actual base64
encoding of the host key.  if you skip host key verification, the
connection is not secure!)


the following example scripts (in demos/) get progressively more detailed:


:demo_simple.py:
   calls invoke_shell() and emulates a terminal/tty through which you can
   execute commands interactively on a remote server.  think of it as a
   poor man's ssh command-line client.


:demo.py:
   same as demo_simple.py, but allows you to authenticiate using a
   private key, attempts to use an SSH-agent if present, and uses the long
   form of some of the API calls.


:forward.py:
   command-line script to set up port-forwarding across an ssh transport.
   (requires python 2.3.)


:demo_sftp.py:
   opens an sftp session and does a few simple file operations.


:demo_server.py:
   an ssh server that listens on port 2200 and accepts a login for
   'robey' (password 'foo'), and pretends to be a BBS.  meant to be a
   very simple demo of writing an ssh server.


:demo_keygen.py:
   an key generator similar to openssh ssh-keygen(1) program with
   paramiko keys generation and progress functions.


Use
---


the demo scripts are probably the best example of how to use this package.
there is also a lot of documentation, generated with epydoc, in the doc/
folder.  point your browser there.  seriously, do it.  mad props to
epydoc, which actually motivated me to write more documentation than i
ever would have before.


there are also unit tests here::


   $ python ./test.py


which will verify that most of the core components are working correctly.


-、执行远程命令:
#!/usr/bin/python
#coding:utf-8
import paramiko
port =22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("*.*.*.*",port,"username", "password")
stdin, stdout, stderr = ssh.exec_command("你的命令")
print stdout.readlines()
ssh.close()


二、上传文件到远程
#!/usr/bin/python
#coding:utf-8
import paramiko


port =22
t = paramiko.Transport(("IP",port))
t.connect(username = "username", password = "password")
sftp = paramiko.SFTPClient.from_transport(t)
remotepath='/tmp/test.txt'
localpath='/tmp/test.txt'
sftp.put(localpath,remotepath)
t.close()


三、从远程下载文件
#!/usr/bin/python
#coding:utf-8
import paramiko


port =22
t = paramiko.Transport(("IP",port))
t.connect(username = "username", password = "password")
sftp = paramiko.SFTPClient.from_transport(t)
remotepath='/tmp/test.txt'
localpath='/tmp/test.txt'
sftp.get(remotepath, localpath)
t.close()


四、执行多个命令
#!/usr/bin/python
#coding:utf-8


import sys
sys.stderr = open('/dev/null')       # Silence silly warnings from paramiko
import paramiko as pm
sys.stderr = sys.__stderr__
import os


class AllowAllKeys(pm.MissingHostKeyPolicy):
   def missing_host_key(self, client, hostname, key):
       return


HOST = '127.0.0.1'
USER = ''
PASSWORD = ''


client = pm.SSHClient()
client.load_system_host_keys()
client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
client.set_missing_host_key_policy(AllowAllKeys())
client.connect(HOST, username=USER, password=PASSWORD)


channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')


stdin.write('''
cd tmp
ls
exit
''')
print stdout.read()


stdout.close()
stdin.close()
client.close()


五、获取多个文件
#!/usr/bin/python
#coding:utf-8


import paramiko
import os


ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('localhost',username='****')  


apath = '/var/log'
apattern = '"*.log"'
rawcommand = 'find {path} -name {pattern}'
command = rawcommand.format(path=apath, pattern=apattern)
stdin, stdout, stderr = ssh.exec_command(command)
filelist = stdout.read().splitlines()


ftp = ssh.open_sftp()
for afile in filelist:
   (head, filename) = os.path.split(afile)
   print(filename)
   ftp.get(afile, './'+filename)
ftp.close()
ssh.close()









本文转自 chengxuyonghu 51CTO博客,原文链接:http://blog.51cto.com/6226001001/1604437,如需转载请自行联系原作者
目录
相关文章
|
14天前
|
机器学习/深度学习 人工智能 算法
基于Python深度学习的眼疾识别系统实现~人工智能+卷积网络算法
眼疾识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了4种常见的眼疾图像数据集(白内障、糖尿病性视网膜病变、青光眼和正常眼睛) 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Django框架搭建了一个Web网页平台可视化操作界面,实现用户上传一张眼疾图片识别其名称。
72 4
基于Python深度学习的眼疾识别系统实现~人工智能+卷积网络算法
|
1月前
|
机器学习/深度学习 人工智能 算法
猫狗宠物识别系统Python+TensorFlow+人工智能+深度学习+卷积网络算法
宠物识别系统使用Python和TensorFlow搭建卷积神经网络,基于37种常见猫狗数据集训练高精度模型,并保存为h5格式。通过Django框架搭建Web平台,用户上传宠物图片即可识别其名称,提供便捷的宠物识别服务。
287 55
|
17天前
|
安全 前端开发 数据库
Python 语言结合 Flask 框架来实现一个基础的代购商品管理、用户下单等功能的简易系统
这是一个使用 Python 和 Flask 框架实现的简易代购系统示例,涵盖商品管理、用户注册登录、订单创建及查看等功能。通过 SQLAlchemy 进行数据库操作,支持添加商品、展示详情、库存管理等。用户可注册登录并下单,系统会检查库存并记录订单。此代码仅为参考,实际应用需进一步完善,如增强安全性、集成支付接口、优化界面等。
|
15天前
|
弹性计算 运维 安全
为了提升运维工程师及开发者
为了提升运维工程师及开发者
|
25天前
|
存储 缓存 监控
局域网屏幕监控系统中的Python数据结构与算法实现
局域网屏幕监控系统用于实时捕获和监控局域网内多台设备的屏幕内容。本文介绍了一种基于Python双端队列(Deque)实现的滑动窗口数据缓存机制,以处理连续的屏幕帧数据流。通过固定长度的窗口,高效增删数据,确保低延迟显示和存储。该算法适用于数据压缩、异常检测等场景,保证系统在高负载下稳定运行。 本文转载自:https://www.vipshare.com
119 66
|
19天前
|
机器学习/深度学习 运维 监控
利用深度学习进行系统健康监控:智能运维的新纪元
利用深度学习进行系统健康监控:智能运维的新纪元
81 30
|
1月前
|
机器学习/深度学习 人工智能 算法
【宠物识别系统】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+图像识别
宠物识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了37种常见的猫狗宠物种类数据集【'阿比西尼亚猫(Abyssinian)', '孟加拉猫(Bengal)', '暹罗猫(Birman)', '孟买猫(Bombay)', '英国短毛猫(British Shorthair)', '埃及猫(Egyptian Mau)', '缅因猫(Maine Coon)', '波斯猫(Persian)', '布偶猫(Ragdoll)', '俄罗斯蓝猫(Russian Blue)', '暹罗猫(Siamese)', '斯芬克斯猫(Sphynx)', '美国斗牛犬
190 29
【宠物识别系统】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+图像识别
|
11天前
|
机器学习/深度学习 算法 前端开发
基于Python深度学习果蔬识别系统实现
本项目基于Python和TensorFlow,使用ResNet卷积神经网络模型,对12种常见果蔬(如土豆、苹果等)的图像数据集进行训练,构建了一个高精度的果蔬识别系统。系统通过Django框架搭建Web端可视化界面,用户可上传图片并自动识别果蔬种类。该项目旨在提高农业生产效率,广泛应用于食品安全、智能农业等领域。CNN凭借其强大的特征提取能力,在图像分类任务中表现出色,为实现高效的自动化果蔬识别提供了技术支持。
基于Python深度学习果蔬识别系统实现
|
15天前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
26 3
|
27天前
|
存储 算法 Python
文件管理系统中基于 Python 语言的二叉树查找算法探秘
在数字化时代,文件管理系统至关重要。本文探讨了二叉树查找算法在文件管理中的应用,并通过Python代码展示了其实现过程。二叉树是一种非线性数据结构,每个节点最多有两个子节点。通过文件名的字典序构建和查找二叉树,能高效地管理和检索文件。相较于顺序查找,二叉树查找每次比较可排除一半子树,极大提升了查找效率,尤其适用于海量文件管理。Python代码示例包括定义节点类、插入和查找函数,展示了如何快速定位目标文件。二叉树查找算法为文件管理系统的优化提供了有效途径。
50 5