Working with paramiko

本文详细介绍了Python Paramiko模块的使用方法,包括SSH连接、执行命令、SFTP文件传输等内容,并提供了多个实例帮助理解。

这篇文章是来自http://segfault.in/2010/03/paramiko-ssh-and-sftp-with-python/,但我在最初学习时发现这篇文章还无法完全解决初学的我,我想初学paramiko看这篇文章也会出不少问题的,在这里,我将自己出的问题列出来,并且提供相关的解决方法,大家可以一边参考上面提供的URL,一边看我对这篇文章的学习过程。不过,单独看我写的也可以满足大家的学习的,不信,看下去,就知道了。

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,用的是RSAkey,我们在用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()

 

我想大家看完应该对paramiko模块有一定的认识了,更全的大家可以参考paramiko的官方手册:

http://www.lag.net/paramiko/docs/

后绪,我将贴些我最近看的demo例子的解法,并且与paramiko有关的知识,如ssh-agent

 

大家加油!

本文出自 “坏男孩” 博客,请务必保留此出处http://5ydycm.blog.51cto.com/115934/340854

内容概要:本文详细介绍了“秒杀商城”微服务架构的设计与实战全过程,涵盖系统从需求分析、服务拆分、技术选型到核心功能开发、分布式事务处理、容器化部署及监控链路追踪的完整流程。重点解决了高并发场景下的超卖问题,采用Redis预减库存、消息队列削峰、数据库乐观锁等手段保障数据一致性,并通过Nacos实现服务注册发现与配置管理,利用Seata处理跨服务分布式事务,结合RabbitMQ实现异步下单,提升系统吞吐能力。同时,项目支持Docker Compose快速部署和Kubernetes生产级编排,集成Sleuth+Zipkin链路追踪与Prometheus+Grafana监控体系,构建可观测性强的微服务系统。; 适合人群:具备Java基础和Spring Boot开发经验,熟悉微服务基本概念的中高级研发人员,尤其是希望深入理解高并发系统设计、分布式事务、服务治理等核心技术的开发者;适合工作2-5年、有志于转型微服务或提升架构能力的工程师; 使用场景及目标:①学习如何基于Spring Cloud Alibaba构建完整的微服务项目;②掌握秒杀场景下高并发、超卖控制、异步化、削峰填谷等关键技术方案;③实践分布式事务(Seata)、服务熔断降级、链路追踪、统一配置中心等企业级中间件的应用;④完成从本地开发到容器化部署的全流程落地; 阅读建议:建议按照文档提供的七个阶段循序渐进地动手实践,重点关注秒杀流程设计、服务间通信机制、分布式事务实现和系统性能优化部分,结合代码调试与监控工具深入理解各组件协作原理,真正掌握高并发微服务系统的构建能力。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值