基于Python实现ssh兼sftp客户端

 

by:授客 QQ:1033553122

实现功能

实现ssh客户端兼ftp客户端:实现远程连接,执行linux命令,上传下载文件

测试环境

Win7 64位

Python 3.3.4

paramiko 1.15.2

下载地址:

https://pypi.python.org/pypi/paramiko/1.15.2

https://pan.baidu.com/s/1i4SJ1CL

cryptography-1.0-cp34-none-win_amd64.whl

(如果paramiko可以正常安装完,则不需要安装该类库)

下载地址:

https://pypi.python.org/pypi/cryptography/1.0

https://pan.baidu.com/s/1jIRBJvg

安装好后,找到nt.py(本例中路径为:

Lib\site-packages\pycrypto-2.6.1-py3.4-win-amd64.egg\Crypto\Random\OSRNG\nt.py),修改

import winrandom

from Crypto.Random.OSRNG import winrandom

如下

#import winrandom

from Crypto.Random.OSRNG import winrandom

以解决ImportError: No module named 'winrandom'错误

VS2010

因操作系统而异,可能需要安装VS2010,以解决包依赖问题

代码实践


mysshclient.py


 


#!/usr/bin/env/ python

#
-*- coding:utf-8 -*-


__author__
=
'shouke'


import

os
from

paramiko.client
import

AutoAddPolicy
from

paramiko.client
import

SSHClient
from

otherTools
import

OtherTools

class

MySSHClient:
    def

__init__(self):
        self.ssh_client
= SSHClient()

#
连接登录

    def

connect(self,
hostname, port, username, password):
        try:
            print('正在远程连接主机:%s'

% hostname)
            self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
            self.ssh_client.connect(hostname=hostname,

port=port,

username=username,

password=password)
            return

[True,

''
]
        except

Exception
as

e:
            print('连接出错了%s'

% e)
            return

[False,

'%s'

% e]

#
远程执行命令

    def

exec_command(self,
command):
        try:
            print('正在执行命令:'+
command)
            stdin,
stdout, stderr =
self.ssh_client.exec_command(command)
            print('命令输出:')
            print(stdout.read())

# 读取命令输出

            return

[True,

tuple]
        except

Exception
as

e:
            print('执行命:%s令出错'

% command)
            return

[False,'%s'

% e]

#
下载文件(非目录文件)

    def

download_file(self,
remotepath, localpath):
        try:
            localpath
= os.path.abspath(localpath)
            localpath
= localpath.replace('\t',

'/t'
).replace('\n',

'/n'
).replace('\r',

'/r'
).replace('\b',

'/b'
)

# 转换特殊字符

            localpath
= localpath.replace('\f',

'/f'
)
            print('转换后的本地目标路径为:%s'

% localpath)
            head,
tail = os.path.split(localpath)
            if
not

tail:
                print('下载文件:%s
到本地:%s失败,本地文件名不能为空'

% (remotepath, localpath))
                return

[False,

'下载文件:%s
到本地:%s失败,本地文件名不能为空'

% (remotepath, localpath)]
            if
not

os.path.exists(head):
                print('本地路径:%s不存在,正在创建目录'

% head)
                OtherTools().mkdirs_once_many(head)

sftp_client
=
self.ssh_client.open_sftp()
            print('正在下载远程文件:%s
到本地:%s'

% (remotepath, localpath))
            sftp_client.get(remotepath,
localpath)
            sftp_client.close()
            return

[True,

''
]
        except

Exception
as

e:
            print('下载文件:%s
到本地:%s
出错:%s'

% (remotepath, localpath, e))
            return

[False,

'下载文件:%s
到本地:%s
出错:%s'

% (remotepath, localpath, e)]

#
上传文件(非目录文件)

    def

upload_file(self,
localpath, remotepath):
        try:
            localpath
= localpath.rstrip('\\').rstrip('/')
            localpath
= localpath.replace('\t',

'/t'
).replace('\n',

'/n'
).replace('\r',

'/r'
).replace('\b',

'/b'
)

# 转换特殊字符

            localpath
= localpath.replace('\f',

'/f'
)
            localpath
= os.path.abspath(localpath)
            print('转换后的本地文件路径为:%s'

% localpath)

remotepath
= remotepath.rstrip('\\').rstrip('/')
            head,
tail = os.path.split(localpath)
            if
not

tail:
                print('上传文件:%s
到远程:%s失败,本地文件名不能为空'

% (localpath, remotepath))
                return

[False,

'上传文件:%s
到远程:%s失败,本地文件名不能为空'

% (localpath, remotepath)]
            if
not

os.path.exists(head):
                print(

'上传文件:%s
到远程:%s失败,父路径不存在'

% (localpath, remotepath, head))
                return

[False,

'上传文件:%s
到远程:%s失败,父路径不存在'

% (localpath, remotepath, head)]

if
not

(remotepath.startswith('/')

or

remotepath.startswith('.')):
                print('上传文件:%s
到远程:%s失败,远程路径填写不规范%s'

% (localpath, remotepath,remotepath))
                return

[False,

'上传文件:%s
到远程:%s失败,远程路径填写不规范%s'

% (localpath, remotepath,remotepath)]
            sftp_client
=
self.ssh_client.open_sftp()
            head,
tail = os.path.split(remotepath)

head
= sftp_client.normalize(head)
# 规范化路径

            remotepath
= head +
'/'

+ tail
            print('规范化后的远程目标路径:',
remotepath)

print('正在上传文件:%s
到远程:%s'

% (localpath, remotepath))
            sftp_client.put(localpath,
remotepath)
            sftp_client.close()
            return

[True,

''
]
        except

Exception
as

e:
            print('上传文件:%s
到远程:%s
出错:%s'

% (localpath, remotepath, e))
            return

[False,

'上传文件:%s
到远程:%s
出错:%s'

% (localpath, remotepath, e)]

def

close(self):
        self.ssh_client.close()

Python 基于Python实现的ssh兼sftp客户端(下)

Python 基于Python实现的ssh兼sftp客户端(上)的更多相关文章

  1. Python 基于Python实现的ssh兼sftp客户端(下)

    基于Python实现的ssh兼sftp客户端   by:授客 QQ:1033553122 otherTools.py #!/usr/bin/env/ python # -*- coding:utf-8 ...

  2. Python 基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现

    基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现   by:授客 QQ:1033553122 测试环境 功能需求 实现思路 代码实践(关键技术点实现) 代码模块组织 ...

  3. Python 基于python操纵zookeeper介绍

    基于python操纵zookeeper介绍 by:授客  QQ:1033553122 测试环境 Win7 64位 Python 3.3.4 kazoo-2.6.1-py2.py3-none-any.w ...

  4. Python 基于Python结合pykafka实现kafka生产及消费速率&主题分区偏移实时监控

    基于Python结合pykafka实现kafka生产及消费速率&主题分区偏移实时监控   By: 授客 QQ:1033553122   1.测试环境 python 3.4 zookeeper- ...

  5. Python 基于Python从mysql表读取千万数据实践

    基于Python 从mysql表读取千万数据实践   by:授客 QQ:1033553122 场景:   有以下两个表,两者都有一个表字段,名为waybill_no,我们需要从tl_waybill_b ...

  6. Python基于Python实现批量上传文件或目录到不同的Linux服务器

    基于Python实现批量上传文件或目录到不同的Linux服务器   by:授客 QQ:1033553122 实现功能 1 测试环境 1 使用方法 1 1. 编辑配置文件conf/rootpath_fo ...

  7. Python 基于python编写一些算法程序等

    基于python编写一些算法程序等 by:授客 QQ:1033553122 QQ群:7156436 没特意去研究,只是这对群友在QQ群里(7156436)提出的一些小程序实现.编程题,算法.问题等,本 ...

  8. Python 基于python+mysql浅谈redis缓存设计与数据库关联数据处理

    基于python+mysql浅谈redis缓存设计与数据库关联数据处理 by:授客  QQ:1033553122 测试环境 redis-3.0.7 CentOS 6.5-x86_64 python 3 ...

  9. Python 基于python操纵redis入门介绍

    基于python操纵redis入门介绍 by:授客  QQ:1033553122 测试环境 redis-3.0.7 CentOS 6.5-x86_64 python 3.3.2 基于Python操作R ...

随机推荐

  1. python(leetcode)-344反转字符串

    编写一个函数,其作用是将输入的字符串反转过来.输入字符串以字符数组 char[] 的形式给出. 不要给另外的数组分配额外的空间,你必须原地修改输入数组.使用 O(1) 的额外空间解决这一问题. 你可以 ...

  2. Git+Hexo搭建个人博客详细过程

    通过Git+Hexo搭建的个人博客地址:https://liangh.top/ 1.安装Node.js.配置好Node.js环境.安装Git和配置好Git环境,打开cmd命令行,成功界面如下 2.安装 ...

  3. 在IIS Express中配置和启动web site

    Step 1 进入 C:\Users\[User]\Documents\IISExpress\config . 编辑applicationhost.config文件 加入站点信息如下: Step2:进 ...

  4. Java垃圾回收(GC)机制详解

    一.为什么需要垃圾回收 如果不进行垃圾回收,内存迟早都会被消耗空,因为我们在不断的分配内存空间而不进行回收.除非内存无限大,我们可以任性的分配而不回收,但是事实并非如此.所以,垃圾回收是必须的. 二. ...

  5. mysql 开发进阶篇系列 5 SQL 优化(表优化)

    一. 使用sql提示 sql 提示(sql hint)是优化数据库的一个重要手段, 是在sql语句中加入一些人为的提示来达到优化操作的目的. 1.1 use index 在查询语句中表名的后面,添加u ...

  6. JavaScript高级编程(1)——JavaScript初识

    一.javascript的简介 1.1 javascript的历史回顾. Javascript诞生于1995年.当时,它主要的目的是用来处理一些由服务器端处理的输入验证操作.在javascript没有 ...

  7. Jenkins入门之执行定时任务

    通过前面我们讲解了如何通过Jenkins执行windows command,powershell脚本,此时我们便可以开始完成一些简单任务了,然而可能看到我们都是通过手动按下Build Now按钮来执行 ...

  8. 使用minukube部署kubernetes admission webhook实现etcd pod安全删除

    本需求来自于一道面试题

  9. Go Web:数据存储(3)——gob对象序列化

    序列化持久存储gob 1.内存存储 2.CSV文件存储 3.gob序列化存储 本篇文章仍然接前面的文章:内存存储,主要介绍将博客文章数据序列化持久到文件中. encoding/gob包用于编码器和解码 ...

  10. QApplication:No such file or directory 错误解决

    首先打开 Makefile 文件,查看其中 INCPATH 变量的值是否包含程序中所涉及到的头文件路径. MAKEFILE = Makefile ####### Compiler, tools and ...