专栏首页python3python paramiko 问题总结

python paramiko 问题总结

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)

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()

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Python paramiko模块的安装

    paramiko是Python语言编写的遵循SSH2协议,支持加密和认证方式,连接远程服务器执行命令或者上传下载文件。

    用户2398817
  • python paramiko

    近段时间用Python写一个小东西,每次修改代码后要手工上传到服务器,觉得很麻烦,虽然有WinSCP,找了一下资料,发现paramiko可以实现自动上传文件的功...

    用户2398817
  • python 远程执行代码 para

        1.1 error: command ‘gcc’ failed with exit status 1

    用户2398817
  • Python paramiko模块的安装

    paramiko是Python语言编写的遵循SSH2协议,支持加密和认证方式,连接远程服务器执行命令或者上传下载文件。

    用户2398817
  • python paramiko

    近段时间用Python写一个小东西,每次修改代码后要手工上传到服务器,觉得很麻烦,虽然有WinSCP,找了一下资料,发现paramiko可以实现自动上传文件的功...

    用户2398817
  • 什么样的网站更值得百度去收录?

    黄伟SEO
  • python模块之paramiko学习<

    简介: paramiko是python(2.2或更高)的模块,遵循SSH2协议实现了安全(加密和认证)连接远程机器。 安装所需软件包: http://ft...

    用户2398817
  • 首席数据官的崛起

    作为美国互助保险有限公司(Nationwide Mutual Insurance)首席数据官(CDO)的Wes Hunt对自己所从事的职业目标很明确,他说:“...

    腾讯研究院
  • Hybrid App开发者一定不要错过的框架和工具

    最近开始给网站的移动版本做技术选型,发现了很多好玩的东西,写出来给大家分享下。 ionicFramework 我是hybrid app的忠实粉丝和大力倡导者,从...

    前朝楚水
  • 链接器做了什么?

    摘自《程序员自我修养》 ---- 机器指令的历史 为了更好的理解计算机程序的编译和链接的过程,我们简单地回顾计算机程序开发的历史一定会非常有益。 最原始的设备...

    233333

扫码关注云+社区

领取腾讯云代金券