Chinaunix首页 | 论坛 | 博客
  • 博客访问: 518493
  • 博文数量: 126
  • 博客积分: 851
  • 博客等级: 准尉
  • 技术积分: 1287
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-06 11:21
个人简介

个人最新博客地址http://www.skylway.com/

文章分类

全部博文(126)

文章存档

2016年(2)

2014年(60)

2013年(35)

2012年(29)

分类: 系统运维

2014-08-15 23:18:54

之前用过fabric模块通过ssh来传输文件,知道fabric是封装了paramiko模块来实现该功能的,而官方对paramiko的介绍就是:Python SSH module

一般使用paramiko的功能就是通过ssh远程执行命令,远程传输文件等等。

模拟远程执行命令:

import paramiko
 
#设置日志记录
paramiko.util.log_to_file('/tmp/test')
 
#建立连接
ssh=paramiko.SSHClient()
 
#缺失host_knows时的处理方法
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 
#连接远程客户机器
ssh.connect('10.1.6.190',port=22,username='root',password='password',compress=True)
 
#获取远程命令执行结果
stdin, stdout, stderr = ssh.exec_command('hostname;uptime')
print stdout.read()
 
#输出执行结果
ssh.close()

模拟远程文件传输:

import paramiko
 
#建立一个加密的管道
scp=paramiko.Transport(('10.1.6.190',22))
 
#建立连接
scp.connect(username='root',password='password')
 
#建立一个sftp客户端对象,通过ssh transport操作远程文件
sftp=paramiko.SFTPClient.from_transport(scp)
 
#Copy a remote file (remotepath) from the SFTP server to the local host
sftp.get('/root/debian7','/tmp/debian7')
 
#Copy a local file (localpath) to the SFTP server as remotepath
sftp.put('/root/crash-6.1.6.tar.gz','/tmp/crash-6.1.6.tar.gz')
 
scp.close()

以上都是通过 paramiko模块来远程操作服务器,如果想通过paramiko模块直接用ssh协议登陆到远程服务器怎么办呢?如下:

import paramiko
import interactive
 
#记录日志
paramiko.util.log_to_file('/tmp/test')
 
#建立ssh连接
ssh=paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.1.6.190',port=22,username='root',password='xxxxxx',compress=True)
 
#建立交互式shell连接
channel=ssh.invoke_shell()
 
#建立交互式管道
interactive.interactive_shell(channel)
 
#关闭连接
channel.close()
ssh.close()


阅读(2064) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~