话不多说直接上代码

封装连接

@staticmethod
def connect(ip, server_user, server_port, server_path):
"""
连接服务器 :param :
:return:
"""
ssh = paramiko.SSHClient()
private_key = paramiko.RSAKey.from_private_key_file('{}.ssh/id_rsa'.format(server_path))
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(ip, port=server_port, username=server_user, pkey=private_key, timeout=5, allow_agent=True)
return ssh
except Exception as e:
app.logger.info('connect_error info is {}'.format(e.__repr__())) return {
'result': 1,
'ip': ip,
'msg': e.__repr__(),
}

在服务器执行命令

    def fabric_run_cmd(self, ip, server_user, server_port, server_path, cmd):
"""
批量在服务器执行命令 :return:
"""
conn = self.connect(ip, server_user, server_port, server_path)
try:
if type(conn) == dict:
return conn
else:
stdin, stdout, stderr = conn.exec_command(cmd)
app.logger.info('fabric_run_cmd_stdout info is {}'.format(stdout.readlines()))
app.logger.info('fabric_run_cmd_stderr info is {}'.format(stderr.readlines()))
channel = stdout.channel
status = channel.recv_exit_status()
conn.close()
app.logger.info('fabric_run_cmd_status info is {}'.format(status))
if status == 0:
return {
'ip': ip,
'msg': '执行成功',
'result': 0
}
else:
return {
'ip': ip,
'msg': stderr.readlines(),
'result': 1
}
except Exception as e:
app.logger.info('fabric_run_cmd_error info is {}'.format(e.__repr__()))
return {
'ip': ip,
'msg': e.__repr__(),
'result': 1
}

将文件发送到服务器

    def fabric_put_file(self, ip, src_file, dst_file, server_user, server_port, server_path):
"""
发送文件到服务器 :return:
"""
conn = self.connect(ip, server_user, server_port, server_path)
if type(conn) == dict:
return conn
else:
try:
ftp = conn.open_sftp()
ftp.put(dst_file, src_file) # 发送文件之前先判断有没有目标文件夹 如果没有现在服务器上创建文件夹
ftp.close() # 在此判断文件是否发送成功
return {
'ip': ip,
'msg': '上传成功',
'result': 0
}
except Exception as e:
app.logger.info('fabric_put_file_error info is {}'.format(e.__repr__()))
return {
'ip': ip,
'msg': e.__repr__(),
'result': 1
}

能力有限,如有不妥请留言指正

python利用paramiko执行服务器命令的更多相关文章

  1. python利用subprocess执行交互命令

    已经知道,os.system可以方便的利用python代码执行一些像ping.ipconfig之类的系统命令,但却只能得到命令执行是否成功,不能获得命令成功执行后的结果,像下面这样: >> ...

  2. python利用paramiko连接远程服务器执行命令

    python中的paramiko模块是用来实现ssh连接到远程服务器上的库,在进行连接的时候,可以用来执行命令,也可以用来上传文件. 1.得到一个连接的对象 在进行连接的时候,可以使用如下的代码: d ...

  3. python 多线程 paramiko实现批量命令输入输出

    远程批量执行命令 实现多线程执行 速度快 实现多并发登录 #-*- coding: utf-8 -*- #!/usr/bin/python import paramiko import threadi ...

  4. appium自动化测试框架——在python脚本中执行dos命令

    一般我们运行dos命令,会有两种需求,一种是需要收集执行结果,如ip.device等:一种是不需要收集结果,如杀死或开启某个服务. 对应的在python中就要封装两种方法,来分别实现这两种需求. 1. ...

  5. Python教程:执行cmd命令

    我们通常可以使用os模块的命令进行执行cmd 方法一:os.system def system(*args, **kwargs): # real signature unknown "&qu ...

  6. Python ssh 远程执行shell命令

    工具 python paramiko 远程执行命令 import paramiko ssh = paramiko.SSHClient() key = paramiko.AutoAddPolicy() ...

  7. python中command执行shell命令脚本方法

    在Python中有一个模块commands也很容易做到以上的效果.看一下三个函数:1). commands.getstatusoutput(cmd)用os.popen()执行命令cmd, 然后返回两个 ...

  8. Flex利用JavaScript执行cmd命令

    Flex: //注册js事件            protected function init():void            {                ExternalInterfa ...

  9. python 利用subprocess调用cmd命令程序,并正确输出控制台的输出中文

    平台Python3.7 1.利用控制台运行程序后在控制台会输出中文提示,但是用python调用subprocess.run函数后返回的输出是乱码,于是,解决方法是用subprocess.check_o ...

随机推荐

  1. ImportError: cannot import name webdriver解决方案

        在sublime写一个Python程序的时候,使用from selenium import webdriver,在run的时候却出现ImportError: cannot import nam ...

  2. (function($){….})(jQuery)与$(function(){})的区别

    function fun($){…};fun(jQuery);这种方法多用于存放开发的插件,执行其中的代码时,Dom对象并不一定加载完毕. $(function(){})等价于$(document). ...

  3. git使用中的问题

    一.github ssh_exchange_identification: read: Connection reset by peer 和电脑环境有关,检查防火墙关了没有,是不是杀毒软件.安全卫士的 ...

  4. (转)线程池 ExecutorService 详细介绍以及注意点区别

    线程池 ExecutorService 相信java开发都用到,这里做个简单笔记 一 Java通过Executors提供四种线程池,分别为: newCachedThreadPool创建一个可缓存线程池 ...

  5. C++: inheritance

    公有继承(public).私有继承(private).保护继承(protected)是常用的三种继承方式. 1. 公有继承(public) 公有继承的特点是基类的公有成员和保护成员作为派生类的成员时, ...

  6. Clover config.plist Boot部分

    <key>Boot</key> <dict> <key>Arguments</key> < nv_disable= kext-dev- ...

  7. 2-sat——hdu3062基础

    hdu就是会卡cin,, 另一种建模方式,把点i拆成i*2,i*2+1,有时候这样会比较简单 #include<bits/stdc++.h> using namespace std; #d ...

  8. SQLite C++操作类

    为了方便SQLite的使用,封装了一个SQLite的C++类,同时支持ANSI 和UNICODE编码.代码如下:   头文件(SQLite.h) [cpp] view plaincopy /***** ...

  9. Jtopo使用中link中文字与link平行

    修改源代码如下 //新增 a.translate(e ,f ); a.rotate(Math.atan((d.y-c.y)/(d.x-c.x))); //修改 a.fillText(this.text ...

  10. 笔试之const问题

    1 . ; int *j=(int *)&i; *j=; cout<<i<<*j<<endl; 答案i为0,*j为1. 2. char * const p= ...