Paramiko 模块使用

一、安装,下载

  1、下载安装 pycrypto-2.6.1.tar.gz  (apt-get install python-dev)

    解压,进入,python setup.py build【编译】,python setup.py install 【安装】  ----》import Crypto

  2、下载安装 paramiko-1.10.1.tar.gz  

    解压,进入,python setup.py build【编译】,python setup.py install 【安装】---》  import paramiko

 

二、paramiko 功能

1、连接远程服务器,并执行操作

用户名和密码连接

#!/usr/bin/env python
#coding:utf-8

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.108',22, ‘root', '123')
stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close();

2、上传和下载文件

import os,sys
import paramiko

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='WOshiniba8')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test.py','/tmp/test.py') 
t.close()


import os,sys
import paramiko

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='WOshiniba8')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test.py','/tmp/test2.py')
t.close()

 

3、通过SSH连接服务器

  ssh-keygen -t rsa

  ssh-copy-id -i ~/ssh/id_rsa.pub root@192.168.159.129

import paramiko

private_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(private_key_path)

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('182.92.219.96 ', 22, 'root', pkey=key,timeout=10)

stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close();

 

4、SSH上传和下载文件

 

import paramiko

pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path)

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='root',pkey=key)

sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test3.py','/tmp/test3.py') 

t.close()

import paramiko

pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path)

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='root',pkey=key)

sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test3.py','/tmp/test4.py') 

t.close()

 

posted @ 2016-03-10 15:07  fengjian1585  阅读(433)  评论(1编辑  收藏  举报