【python】python 模块学习之--paramiko

使用python的paramiko模块实现ssh与scp功能

1. 介绍


这篇文章简单地介绍了Python的paramiko模块的用法,paramiko实现了SSH协议,能够方便地与远程计算机交互。简单的说,就是你在terminal下执行的如下语句,现在可以通过python的paramiko实现了。

 # 执行shell语句 ssh -i ~/.ssh/id_rsa -p 1098 rds@12.164.145.21 -e 'ls -al' # 拷贝数据到远程计算机 scp -i ~/.ssh/id_rsa -P 1098 -r data rds@12.164.145.21:~/data

这里不讨论shell与python实现的优缺点,如果你没有需求,也不会看到这篇博客了。我个人使用paramiko是为了使用python的多线程,并发地对多台远程计算机执行相同的操作。

这篇博客虽然篇幅不大,但是,可能是目前网络上最好的中文入门教程了。那就开始吧!

2. 安装

安装非常简单,直接使用pip安装即可:

sudo pip instal paramiko

3. 建立SSH连接

使用密码连接:

import paramiko
ssh = paramiko.SSHClient() #这行代码的作用是允许连接不在know_hosts文件中的主机。 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect("IP", port, "username", "password")

使用私钥连接:

ssh = paramiko.SSHClient() ssh.connect('10.120.48.109', port, '用户名', key_filename='私钥')

连接以后可以执行shell命令:

In [8]: ssh.exec_command('ls') Out[8]: (<paramiko.ChannelFile from <paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport at 0x377c690L (cipher aes128-ctr, 128 bits) (active; 2 open channel(s))>>>, <paramiko.ChannelFile from <paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport at 0x377c690L (cipher aes128-ctr, 128 bits) (active; 2 open channel(s))>>>, <paramiko.ChannelFile from <paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport at 0x377c690L (cipher aes128-ctr, 128 bits) (active; 2 open channel(s))>>>)

执行shell命令以后,并不会立即打印命令的执行结果,而是返回几个Channel, 只能像下面这样获取输出:

In [9]: stdin, stdout, stderr = ssh.exec_command('ls') In [10]: print stdout.readlines() ['AgentBackkup_2015-06-11\n', 'AgentBackup\n', 'log\n', 'mysql.sh\n', 'rdsAgent\n']

注意: 命令执行出错并不会抛出异常,所以,对于命令出错需要根据自己的需求进行相应的处理:

In [54]: stdin, stdout, stderr = ssh.exec_command('cat file_not_found') In [55]: print stdout.readlines() [] In [56]: print stderr.readlines() [u'cat: file_not_found: No such file or directory\n'] In [57]: stdin, stdout, stderr = ssh.exec_command('ls') In [58]: print stderr.readlines() [] 
save_snippets.png

API文档: https://paramiko-docs.readthedocs.org/en/1.15/api/client.html


ssh实例代码如下
  1. #ssh_cmd.py
  2. #coding:utf-8
  3. import pexpect
  4. import sys
  5. import paramiko
  6. ip='218.78.186.162'
  7. user='root'
  8. passwd='xxxx'
  9. cmd='df -h'


  10. #######以密钥的形式######
  11. ssh = paramiko.SSHClient()
  12. ssh.load_system_host_keys()            ####获取ssh key密匙,默认在~/.ssh/knows_hosts
  13. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  14. ssh.connect(ip,22,'chenliang',key_filename='/root/.ssh/id_rsa')
  15. stdin, stdout, stderr=ssh.exec_command('df -h')
  16. cmd=stdout.read()
  17. print cmd
  18. ssh.close()                              ###关闭ssh

  19. ######以密码的形式######           
  20. paramiko.util.log_to_file=('syslogin.log')               #####日志存储
  21. ssh = paramiko.SSHClient()
  22. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  23. ssh.load_system_host_keys()
  24. ssh.connect(hostname='218.78.186.162',username='root',password='xxxx')
  25. stdin, stdout, stderr=ssh.exec_command('free -m')
  26. print stdout.read()
  27. ssh.close()
 
####可以自己定义keyfile的路径
#######ssh key type######
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekey = os.path.expanduser('/root/.ssh/id_rsa')      ####自己
key = paramiko.RSAKey.from_private_key_file(privatekey)   ####定义
ssh.connect(ip,22,'chenliang',pkey=key)                   ####调用
stdin, stdout, stderr=ssh.exec_command('df -h')
cmd=stdout.read()
print cmd

SFTPClient实例
  1. [root@hostnfsd :/soft/python]$ vi para2.py
  2. #ssh_cmd.py
  3. #coding:utf-8
  4. import sys
  5. import paramiko
  6. #######ssh key type######


  7. ######ssh passwd type######
  8. t=paramiko.Transport(("218.78.186.162",22))
  9. t.connect(username='root',password='xxxx')
  10. sftp = paramiko.SFTPClient.from_transport(t)
  11. sftp.put('/myproject/cms/focus/admin.py','/tmp/admin.py')   ##上传
  12. sftp.get('/root/ttt.txt','/myproject/cms/focus/ttt.txt')        ##下载
  13. sftp.mkdir('/root/testdir')                    ####mkdir
  14. sftp.rmdir('/root/testdir2')                   ###删除目录
  15. sftp.rename('/tmp/admin.py','/tmp/admin2.py')   ###重命名
  16. sftp.stat('/tmp/admin2.py')                     ###查看文件信息
  17. print sftp.listdir('/home')                     ####目录列表


导入模块报错

python>> import paramiko

  (Crypto error: 'module' object has no attribute 'HAVE_DECL_MPZ_POWM_SEC'

  找到 /usr/lib/python2.7/site-packages/Crypto/Util/number.py

  把if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC:
                asdadad

  方法注释了

  #if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC:
                #asdadad

  )



来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29096438/viewspace-2123726/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29096438/viewspace-2123726/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值