Working with paramiko

SSHClient is the main class provided by the paramkio module. It provides the basic interface you are going to want to use to instantiate server connections. The above code creates a new SSHClient object, and then calls ”connect()” to connect us to the local SSH server.

Here’s a simple example:

1

import paramiko

2

ssh = paramiko.SSHClient()

3               ssh.connect('192.168.1.2', username='vinod', password='screct')

这样将会报如下错误:

>>> ssh.connect('127.0.0.1',username='root',password='000000')

Traceback (most recent call last):

File "<stdin>", line 1, in ?

File "/usr/lib/python2.4/site-packages/paramiko/client.py", line 311, in connect

self._policy.missing_host_key(self, server_hostkey_name, server_key)

File "/usr/lib/python2.4/site-packages/paramiko/client.py", line 85, in missing_host_key

raise SSHException('Unknown server %s' % hostname)

paramiko.SSHException: Unknown server 127.0.0.1

解决方法:

Known_host="/root/.ssh/known_hosts"<=前提,这里应该存在与127.0.0.1有关的信息。

ssh.load_system_host_keys( known_host)

Another way is to use an SSH key:

1

import paramiko

2

import os

3

privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')

4

mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)

5

ssh.connect('192.168.1.2', username = 'vinod', pkey = mykey)

注意:(这里的key,用的是RSA的key,我们在用ssh-keygen -t rsa来指定它,才可以在这里用,否则将会报无法识别的RSA KEY。而且如果你的RSA Key有密码的话,你还需要

mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password='12345678')

不过,我们可以用publickey来登录的。

解法如下:

serverHost = "127.0.0.1"

serverPort = 22

userName = "root"

keyFile = "~/.ssh/badboy"

known_host = "~/.ssh/known_hosts"

channel = paramiko.SSHClient();

channel.load_system_host_keys( known_host )

channel.connect( serverHost, serverPort,username = userName, key_filename = keyFile )

Running Simple Commands

Lets run some simple commands on a remote machine.

1

import paramiko

2

ssh = paramiko.SSHClient()

3

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) <=这样的话,就会报paramiko.SSHException: Unknown server

4

ssh.connect('beastie', username='vinod', password='secret')

5

stdin, stdout, stderr = ssh.exec_command('df -h')

6

print stdout.readlines()

7

ssh.close()

“paramiko.AutoAddPolicy()” which will auto-accept unknown keys.

Using sudo in running commands:

01

import paramiko

02

03

cmd    = "sudo /etc/rc.d/apache2 restart"

04

05

ssh    = paramiko.SSHClient()

06

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

07

ssh.connect('beastie', username='vinod', password='secret')

08

stdin, stdout, stderr = ssh.exec_command(cmd)

09

stdin.write('secret\n')

10

stdin.flush()

11

print stdout.readlines()

12

ssh.close()

在这个例子中,无法运行,也无法解释,希望志同道合的朋友能给个解释!

Secure File Transfer Using SFTPClient

SFTPClient is used to open an sftp session across an open ssh Transport and do remote file operations.

An SSH Transport attaches to a stream (usually a socket), negotiates an encrypted session, authenticates, and then creates stream tunnels, called Channels, across the session. Multiple channels can be multiplexed across a single session (and often are, in the case of port forwardings).

以下是用密码认证功能登录的

#!/usr/bin/env python

import paramiko

socks=('127.0.0.1',22)

testssh=paramiko.Transport(socks)

testssh.connect(username='root',password='000000')

sftptest=paramiko.SFTPClient.from_transport(testssh)

remotepath="/tmp/a.log"

localpath="/tmp/c.log"

sftptest.put(remotepath,localpath)

sftptest.close()

testssh.close()

以下是用DSA认证登录的(PubkeyAuthentication)
#!/usr/bin/env python

import paramiko

serverHost = "192.168.1.172"

serverPort = 22

userName = "root"

keyFile = "/root/.ssh/zhuzhengjun"

known_host = "/root/.ssh/known_hosts"

channel = paramiko.SSHClient();

#host_keys = channel.load_system_host_keys(known_host)

channel.set_missing_host_key_policy(paramiko.AutoAddPolicy())

channel.connect(serverHost, serverPort,username=userName, key_filename=keyFile )

testssh=paramiko.Transport((serverHost,serverPort))

mykey = paramiko.DSSKey.from_private_key_file(keyFile,password='xyxyxy')

testssh.connect(username=userName,pkey=mykey)

sftptest=paramiko.SFTPClient.from_transport(testssh)

filepath='/tmp/e.log'

localpath='/tmp/a.log'

sftptest.put(localpath,filepath)

sftptest.close()

testssh.close()

以下是用RSA Key认证登录的

#!/usr/bin/evn python

import os

import paramiko

host='127.0.0.1'

port=22

testssh=paramiko.Transport((host,port))

privatekeyfile = os.path.expanduser('~/.ssh/badboy')

mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')

username = 'root'

testssh.connect(username=username, pkey=mykey)

sftptest=paramiko.SFTPClient.from_transport(testssh)

filepath='/tmp/e.log'

localpath='/tmp/a.log'

sftptest.put(localpath,filepath)

sftptest.close()

testssh.close()

另一种方法:

在paramiko中使用用户名和密码通过sftp传输文件,不使用key文件。

import getpass

import select

import socket

import traceback

import paramiko

def putfile():

#import interactive

# setup logging

paramiko.util.log_to_file('demo.log')

username = username

hostname = hostname

port = 22

# now connect

try:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((hostname, port))

except Exception, e:

print '*** Connect failed: ' + str(e)

traceback.print_exc()

sys.exit(1)

t = paramiko.Transport(sock)

try:

t.start_client()

except paramiko.SSHException:

print '*** SSH negotiation failed.'

sys.exit(1)

keys = {}

# check server's host key -- this is important.

key = t.get_remote_server_key()

# get username

t.auth_password(username, password)

sftp = paramiko.SFTPClient.from_transport(t)

# dirlist on remote host

d=datetime.date.today()-datetime.timedelta(1)

sftp.put(localFile,serverFile)

sftp.close()

t.close()

使用DSA认证登录的(PubkeyAuthentication)

#!/usr/bin/env python

import socket

import paramiko

import os

username='root'

hostname='192.168.1.169'

port = 22

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((hostname, port))

t=paramiko.Transport(sock)

t.start_client()

key=t.get_remote_server_key()

#t.auth_password(username,'000000')

privatekeyfile = os.path.expanduser('/root/.ssh/zhuzhengjun')

mykey=paramiko.DSSKey.from_private_key_file(privatekeyfile,password='061128')

t.auth_publickey(username,mykey)

sftp=paramiko.SFTPClient.from_transport(t)

sftp.put("/tmp/a.log","/tmp/h.log")

sftp.close()

t.close()

使用RSA Key验证

#!/usr/bin/env python

import socket

import paramiko

import os

username='root'

hostname='127.0.0.1'

port = 22

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((hostname, port))

t=paramiko.Transport(sock)

t.start_client()

key=t.get_remote_server_key()

#t.auth_password(username,'000000')

privatekeyfile = os.path.expanduser('~/.ssh/badboy')

mykey=paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')

t.auth_publickey(username,mykey)

sftp=paramiko.SFTPClient.from_transport(t)

sftp.put("/tmp/a.log","/tmp/h.log")

sftp.close()

t.close()

转载于:https://blog.51cto.com/lihuipeng/1077357

python paramiko 问题总结相关推荐

  1. python paramiko安装_Python Paramiko模块的安装与使用详解

    一.前言 常见的解决方法都会需要对远程服务器必要的配置,如果远程服务器只有一两台还好说,如果有N台,还需要逐台进行配置,或者需要使用代码进行以上操作时,上面的办法就不太方便了.而使用paramiko可 ...

  2. python paramiko并发_使用Python paramiko模块利用多线程实现ssh并发执行操作

    1.paramiko概述 ssh是一个协议,OpenSSH是其中一个开源实现,paramiko是Python的一个库,实现了SSHv2协议(底层使用cryptography). 有了Paramiko以 ...

  3. python paramiko使用_python Paramiko使用示例

    Paramiko 是由 Python 语言编写的一个扩展模块,提供了基于 SSHv2 协议 (包括客户端和服务端)的多种功能实现.通常被用来远程控制类 UNIX 系统. Paramiko 可以直接使用 ...

  4. Python | paramiko的概念及其使用

    本文主要介绍 paramiko 的概念及其使用 1' 2' 3' 4. 本文环境 Centos 7.9, Python 3.7, Paramiko 2.7.2. Last Updated: 2022 ...

  5. python paramiko模块中设置执行命令超时值

    经常使用paramiko工具对几百台设备进行管理,但是由于服务器本身或是网络原因,有时返回值回不来,然后程序就看在那里一直等待,这个时候后需要设置一个超时值.paramiko模块中执行命令代码如下: ...

  6. python paramiko模块 远程上传目录文件

    目录 上传目录 上传文件 上传目录 python用paramiko模块默认中只可以上传文件,在网上也没有找到合适的直接上传目录的方法,所以用os.walk方法和paramiko结合写了一个上传目录的方 ...

  7. python paramiko包 ssh报错No existing session 解决方法

    在connect 的时候加入参数 allow_agent, look_for_keys 就可以了 ssh.connect('localhost',username=name,password=pw,a ...

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

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

  9. python paramiko模块

    paramiko模块 1. 介绍: paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的para ...

最新文章

  1. kalinux实现自适用全屏、与物理主机共享文件方法
  2. linux 交叉编译 libxml2,openssl,libssh2
  3. boot返回码规范 spring_SpringBoot 系列 web 篇之自定义返回 Http Code 的 n 种姿势
  4. Hibernate入门(二)
  5. 女生适不适学习Java编程
  6. R语言tidyverse数据处理建模案例
  7. VS下如何配置才能使用 cl 命令行方式编译 C/C++ 程序
  8. 2016年大数据Spark“蘑菇云”行动之spark streaming消费flume采集的kafka数据Directf方式...
  9. 使用Redis存取数据+数据库存取(spring+java)
  10. goland编写go语言导入自定义包出现: package xxx is not in GOROOT (/xxx/xxx) 的解决方案
  11. rda分析怎么做_PCA、PCoA、NMDS 、RDA和CCA等排序分析方法
  12. 安卓投屏大师_还不会把手机投屏到电脑?教你四种方法,柯达带你直播玩的更溜...
  13. mysql lbs_LBS类数据服务对比分析 (一)
  14. C++ 二元一次不定方程巧妙求解——运用扩展欧几里得算法
  15. 模拟浏览器下载Excel 到本地
  16. 【MATLAB】基本绘图 ( plot 函数绘制多个图形 | legend 函数标注图形 | 图形修饰 )
  17. NetTerm 使用简介
  18. Linux多线程编程之pthread (多线程编程) --- (高级)---原作优秀
  19. ChatGpt对于学术和程序员的影响
  20. 机载激光雷达数据获取及生产流程

热门文章

  1. jq的ajax和模块引擎
  2. PAT天梯赛练习题——L3-005. 垃圾箱分布(暴力SPFA)
  3. Robot Framework--06 用户关键字User Keyword
  4. 以色列研究人员实现利用计算机风扇噪音窃听
  5. 人工智能中对机器学非常简要的介绍
  6. 一个有趣的this指向问题
  7. 【Storm篇】--Storm基础概念
  8. Putty常用属性设置
  9. [翻译][1.4.2]Flask-Admin入门介绍
  10. C# 中的 sealed(密封) 关键字