系统运维工程师的法宝: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,如需转载请自行联系原作者
目录
相关文章
|
16天前
|
运维 Kubernetes 监控
构建高效自动化运维系统:基于容器技术的策略与实践
【4月更文挑战第19天】随着云计算和微服务架构的兴起,传统的运维模式正逐渐向自动化、智能化转型。本文将探讨如何利用容器技术构建一个高效、可靠的自动化运维系统,涵盖系统设计原则、关键技术选型以及实践经验分享。通过引入容器技术,我们可以实现应用的快速部署、弹性伸缩和故障自愈,从而提高运维效率,降低系统维护成本。
|
28天前
|
人工智能 机器人 测试技术
【Python】Python房屋销售系统(源码)【独一无二】(课程设计)
【Python】Python房屋销售系统(源码)【独一无二】(课程设计)
|
6天前
|
运维 监控 安全
构建高效自动化运维系统:策略与实践
【4月更文挑战第29天】 在信息技术日新月异的今天,高效的运维管理已成为企业保持竞争力的关键因素。本文将探讨如何构建一个能够适应快速变化需求的自动化运维系统。通过深入分析自动化工具的选择、配置管理的最佳实践以及持续集成和部署的策略,我们旨在为读者提供一个清晰的框架来优化他们的运维流程。文章的核心在于提出一种结合了最新技术和思维模式的综合解决方案,以实现运维工作的最优化。
|
5天前
|
运维 Kubernetes 持续交付
构建高效自动化运维系统:基于容器技术的持续集成与持续部署实践
【4月更文挑战第30天】 在快速发展的云计算时代,传统的运维模式已无法满足敏捷开发和快速迭代的需求。本文将介绍如何利用容器技术搭建一套高效自动化运维系统,实现软件的持续集成(CI)与持续部署(CD)。文章首先探讨了现代运维面临的挑战,接着详细阐述了容器技术的核心组件和工作原理,最后通过实际案例展示了如何整合这些组件来构建一个可靠、可扩展的自动化运维平台。
|
6天前
|
运维 监控 安全
构建高效自动化运维系统:策略与实践
【4月更文挑战第30天】 在现代IT基础设施管理中,自动化运维不再是可选项而是必需品。随着复杂性的增加和变更的频繁性,自动化可以提高效率、减少错误并释放人员专注于更有价值的任务。本文将探讨构建一个高效的自动化运维系统的关键环节,包括工具选择、流程设计以及监控和优化策略。通过案例分析和最佳实践分享,读者可以获得实施自动化运维的实用指导和启发。
|
7天前
|
机器学习/深度学习 人工智能 运维
构建高效自动化运维系统的策略与实践
【4月更文挑战第29天】 在数字化转型的浪潮中,企业IT基础设施变得日益复杂多变。传统的手动运维方式已无法满足快速响应和高效率的需求。本文将探讨如何通过一系列策略和技术手段构建一个高效的自动化运维系统。首先,分析当前自动化运维的必要性及其带来的益处;接着,详细阐述自动化运维的核心组件、工具选择以及实施步骤;最后,通过案例分析展示自动化运维在实际环境中的应用效果,并讨论面临的挑战及未来发展趋势。
|
7天前
|
消息中间件 运维 监控
基于SaaS云部署、云计算的区域医院云HIS系统源码(运维管理+运营管理+综合监管)
医院云his系统采用主流成熟技术开发,B/S架构,软件结构简洁、代码规范易阅读,SaaS应用,全浏览器访问,前后端分离,多服务协同,服务可拆分,功能易扩展。多医院统一登录患者主索引建立、主数据管理,统一对外接口管理。
24 1
|
7天前
|
存储 运维 监控
构建高效可靠的自动化运维系统
【4月更文挑战第28天】 随着信息技术的快速发展,企业对于信息系统的管理和维护要求越来越高。传统的手工运维方式已经难以满足现代企业的需求,因此自动化运维成为了一种趋势。本文将介绍构建高效可靠自动化运维系统的方法和技术,包括自动化工具的选择、配置管理、监控告警等方面的内容。通过本文的阅读,读者可以了解到如何利用自动化技术提高运维效率,降低人为错误的发生,从而实现企业的高效稳定运行。
|
10天前
|
数据可视化 Python
Python的分子模拟动态促进DF Theory理论对二进制硬盘系统的适用性
Python的分子模拟动态促进DF Theory理论对二进制硬盘系统的适用性
10 0
|
11天前
|
运维 Prometheus 监控
构建高效自动化运维系统:策略与实践
【4月更文挑战第24天】 在当今快速发展的信息技术时代,自动化运维已经成为提高企业IT效率、确保系统稳定性和敏捷响应市场变化的关键。本文将探讨构建一个高效自动化运维系统的关键环节,包括基础设施即代码(IaC)的实现、持续集成与持续部署(CI/CD)流程的优化以及监控和日志分析的重要性。通过这些技术的融合,我们旨在提供一个可行的蓝图,以帮助企业实现运维工作的自动化,从而提升整体业务效能。