python3使用paramiko模块,构建一个Server类,实现ssh、sftp的功能(最终版,大概......)

python3使用paramiko模块,构建一个Server类,实现ssh、sftp的功能(更新版) 使用paramiko模块,构建一个Server类,用来连接远程服务器,支持ssh连接、下发单个无交互指令、sftp单文件的上传下载。 测试连接linux和solaris远程主机均能正常使用 代码: # -*- coding: utf-8 -*- """ Created on Wed May 14 10:53:38 2019 @author: Phoenix(https://blog.csdn.n... 阅读详情
python3使用paramiko模块构建Server类,实现ssh发送无交互指令、sftp上传下载,与之前的一版相比,channel发送指令可以支持交互指令,优化了部分代码。
类代码
# -*- coding: utf-8 -*-
"""
@author: Phoenix
"""
import paramiko
from time import sleep


class Server(object):

    def __init__(self, ip='', port=22, username='', password='', timeout=30):
        """
        通过IP, 端口,用户名,密码,超时时间,初始化一个远程主机
        :param str ip:
        :param int port: default value is 22
        :param str username:
        :param str password:
        :param int timeout: default value is 30.
        """
        # 连接信息
        self._ip = ip
        self._port = port
        self._username = username
        self._password = password
        self._timeout = timeout
        # transport, channel, ssh, sftp, prompt
        self._transport = None
        self._channel = None
        self._ssh = None
        self._sftp = None
        self._prompt = None
        # 连接失败的重试次数(总计3次尝试)
        self._try_times = 2

    # 调用connect方法连接远程主机
    def connect(self):
        """
        :return: result
        """
        _result = ''
        while True:
            # 尝试连接
            try:
                self._transport = paramiko.Transport((self._ip, self._port))
                self._transport.connect(username=self._username, password=self._password)
                # 如果没有抛出异常说明连接成功,直接返回
                _result += '%s 创建成功' % self._ip
                break
            # 这里对可能的异常如网络不通、链接超时、socket.error, socket.timeout直接输出
            except Exception as _e:
                if self._try_times != 0:
                    _result += '第%i次连接 %s 异常,原因:%s\n' % (3 - self._try_times, self._ip, _e)
                    _result += '进行重试\n'
                    self._try_times -= 1
                else
Python3:使用Paramiko模块实现SSH和SFTP客户端 使用Paramiko,我们可以轻松地建立SSH连接并执行远程命令,以及进行文件传输等操作。在本篇文章中,我们将展示如何使用Paramiko进行SSH和SFTP连接。我们将通过一个简单的示例程序来演示如何使用Paramiko连接到远程服务器,执行一些命令以及上传和下载文件。Paramiko是用于在Python中进行SSH连接和SFTP传输的模块,它提供了一个简单而强大的接口,可以让你在Python中轻松地执行远程命令、上传和下载文件。然后,我们执行了一个远程命令(列出远程服务器上的文件),并打印出了结果。 阅读详情

相关推荐

使用Python3中的paramiko模块进行SSH和SFTP客户端操作

通过paramiko模块,我们可以轻松地建立SSH连接并执行远程命令,以及进行SFTP文件传输操作。使用paramiko模块,我们可以方便地在Python程序中进行远程服务器操作和文件传输,为自动化和远程管理任务提供了便利。paramiko是一个用于在Python中进行SSH(Secure Shell)和SFTP(SSH File Transfer Protocol)操作的模块。在上面的代码中,我们首先创建了一个SSHClient对象,并设置了自动添加服务器主机密钥的策略。方法执行远程命令,将结果保存在。

PixelLancer的博客 500

Python与shell的3种交互方式介绍

概述 考虑这样一个问题,有hello.py脚本,输出”hello, world!”;有TestInput.py脚本,等待用户输入,然后打印用户输入的数据。那么,怎么样把hello.py输出内容发送给TestInput.py,最后TestInput.py打印接收到的”hello, world!”。下面我来逐步讲解一下shell的交互方式。 hello.py代码如下: 复制代码 代码如下: #!/usr/bin/python print “hello, world!” TestInput.py代码如下: 复制代码 代码如下: #!/usr/bin/python str = raw_input()

基于C#的跨平台上位机开发:一次编写,多平台运行

摘要: 本文探讨了如何利用C#进行跨平台上位机开发,以适配Windows、Linux、macOS等多平台需求。通过分析传统单平台开发的局限性(如API差异、硬件接口兼容性),提出基于.NET 5/6/7的解决方案,重点推荐Avalonia(类WPF的跨平台UI框架)和GtkSharp(基于GTK+)实现图形界面。同时,针对硬件通信需求,介绍了System.IO.Ports串口通信和LibUsbDotNet的跨平台支持,并强调多平台调试(VS Code、Docker)的重要性,最终实现一次编码、多端部署的高效

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1421

WiFi信道状态信息 基于Intel 5300的CSI Tool 安装及使用(一)

经过半个月的坎坷安装过程,连Windows系统都没装过的本人终于颤颤巍巍把CSI TOOL装好了,下面记录一下适于我所使用设备的安装过程。设备:一台THINKPAD X201,一台师兄借的华硕主板的台式机首先,如果你和我一样对linux其实一窍不通的话,建议先反复看教程里的安装代码,照猫画虎很难一步实现的,中途一定会有这或那的问题需要解决,所以该了解的基础linux指令还是要了解,起码安装过程中的那些指令可以去查一查。.........

Silver_777的博客 2万+

Windows Server 2012 R2虚拟机安装全攻略:从镜像选择到网络配置一步到位

本文提供Windows Server 2012 R2虚拟机安装全攻略,涵盖从镜像选择到网络配置的完整流程。详细讲解在Oracle VM VirtualBox中的安装步骤、TCP/IP网络设置、系统优化及常见问题解决方案,帮助用户快速搭建可立即投入使用的服务器环境。特别适合IT初学者和系统管理员学习传统服务器应用的部署与配置。

weixin_28363123的博客 541

为什么大语言模型推理要分成 Prefill 和 Decode?深入理解这两个阶段的真正意义

Prefill 阶段是语言模型推理中的第一个步骤,它负责处理你输入的所有上下文内容(prompt),为后续生成打下基础。“请解释一下 Transformer 的原理。这句话会被 tokenizer 编码为一串 token,比如["请", "解释", "一下", "Trans", "##former", "的", "原理", "。"]。然后这些 token 会进入 Transformer 模型进行前向传播。重点来了 👇。

Harry的博客 1万+

华为OD机试 - 荒岛求生 - 栈Stack(Python/JS/C/C++ 新系统 100分)

每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新,全天CSDN在线答疑。

学Java,找哪吒 2843

【Bug已解决】Codex 切换 model_provider 后历史会话消失的解决方案

方案适用场景推荐指数切回原 provider 验证排查的第一步,确认数据是否真的丢失⭐⭐⭐⭐⭐查看本地会话文件进一步确认数据完整性⭐⭐⭐⭐⭐查阅跨 provider 恢复命令官方是否提供了对应功能⭐⭐⭐使用社区辅助工具需要频繁切换 provider 的场景⭐⭐⭐定期备份配置目录任何场景下的通用保险措施⭐⭐⭐⭐切换后历史会话"消失"的本质是客户端的会话列表展示逻辑受当前活跃 provider 状态过滤,而不是原始数据文件被真正删除。

一键难忘的博客 6008

Error: Flash Download failed - Target DLL has been cancelled

由于换了新电脑,keil重装了下,然而之前的MCU的支持包没有安装,以及一些其他的问题,导致可以编译但是不能将程序烧录到单片机中。现整理一下解决思路: 1、将支持包下载并添加: 找到你需要用的MCU的具体型号: 例如: 点击网址,下载安装包,或者在csdn等其他网址下载安装包,将下载好的pack包放到keil5的安装目录下的.Download中: 点击file中的import,将路径选择到.........

hanhan的博客 5万+

Darknet-Yolov3 移植过程

本教程面向使用寒武纪平台进行深度学习推理任务的开发者。针对当前主流检测网络darknet-yolov3,进行寒武纪平台的移植。开发者对照移植过程,能够利用寒武纪智能处理器设备完成多种场景的目标检测任务。本实验代码基于 Neuware 1.6.1 与 Python 2.7 环境。

shengyin714959的博客 441

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

上一篇: python3跨文件夹import的解决办法
下一篇: 震惊!(python)从其它文件import一个自定义的函数,运行结果却是这样!男默女泪,邻娃馋哭!!
phoenix339
博客等级 码龄14年 25粉丝 29原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址