python利用paramiko连接远程服务器执行命令的方法


Posted in Python onOctober 16, 2017

python中的paramiko模块是用来实现ssh连接到远程服务器上的库,在进行连接的时候,可以用来执行命令,也可以用来上传文件。

1、得到一个连接的对象

在进行连接的时候,可以使用如下的代码:

def connect(host):
  'this is use the paramiko connect the host,return conn'
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  try:
#    ssh.connect(host,username='root',allow_agent=True,look_for_keys=True)
    ssh.connect(host,username='root',password='root',allow_agent=True)
    return ssh
  except:
    return None

在connect函数中,参数是一个主机的IP地址或者是主机名称,在执行这个方法之后,如果成功的连接到服务器,那么就会返回一个sshclient对象。

第一步是建立一个SSHClient的对象,然后设置ssh客户端允许连接不在know_host文件中的机器,然后就尝试连接服务器,在连接服务器的时候,可以使用两种方式:一种方式是使用秘钥的方式,也就是参数look_for_keys,这里用设置密码寻找,也可以直接使用密码的方式,也就是直接使用参数password,从而最后返回一个连接的对象。

2、 获取设置的命令

在进行paramiko连接之后,那么必须要得到需要执行的命令,如下代码所示:

def command(args,outpath):
  'this is get the command the args to return the command'
  cmd = '%s %s' % (outpath,args)
  return cmd

在参数中,一个是args,一个outpath,args表示命令的参数,而outpath表示为可执行文件的路径,例如/usr/bin/ls -l。在其中outpath也就是/usr/bin/ls ,而参数为-l

这个方法主要是用来组合命令,将分开的参数作为命令的一部分进行组装。

3、 执行命令

在连接过后,可以进行直接执行命令,那么就有了如下的函数:

def exec_commands(conn,cmd):
  'this is use the conn to excute the cmd and return the results of excute the command'
  stdin,stdout,stderr = conn.exec_command(cmd)
  results=stdout.read()
  return results

在此函数中,传入的参数一个为连接的对象conn,一个为需要执行的命令cmd,最后得到执行的结果,也就是stdout.read(),最后返回得到的结果

4、 上传文件

在使用连接对象的时候,也可以直接进行上传相关的文件,如下函数:

def copy_moddule(conn,inpath,outpath):
  'this is copy the module to the remote server'
  ftp = conn.open_sftp()
  ftp.put(inpath,outpath)
  ftp.close()
  return outpath

此函数的主要参数为,一个是连接对象conn,一个是上传的文件名称,一个上传之后的文件名称,在此必须写入完整的文件名称包括路径。

做法主要是打开一个sftp对象,然后使用put方法进行上传文件,最后关闭sftp连接,最后返回一个上传的文件名称的完整路径

5、 执行命令得到结果

最后就是,执行命令,得到返回的结果,如下代码:

def excutor(host,outpath,args):
  conn = connect(host)
  if not conn:
    return [host,None]
  exec_commands(conn,'chmod +x %s' % outpath)
  cmd =command(args,outpath)
  result = exec_commands(conn,cmd)
  print '%r' % result
  result = json.loads(result)
  return [host,result]

首先,进行连接服务器,得到一个连接对象,如果连接不成功,那么返回主机名和None,表示没有连接成功,如果连接成功,那么修改文件的执行权限,从而可以执行文件,然后得到执行的命令,最后,进行执行命令,得到结果,将结果用json格式表示返回,从而结果能得到一个美观的json格式,最后和主机名一起返回相关的信息

6、 测试代码

测试代码如下:

if __name__ == '__main__':
  print json.dumps(excutor('192.168.1.165','ls',' -l'),indent=4,sort_keys=True)
  print copy_module(connect('192.168.1.165'),'kel.txt','/root/kel.1.txt')
  exec_commands(connect('192.168.1.165'),'chmod +x %s' % '/root/kel.1.txt')

第一步测试命令执行,第二步测试上传文件,第三部测试修改上传文件的权限。

完整代码如下:

#!/usr/bin/env python
import json
import paramiko

def connect(host):
  'this is use the paramiko connect the host,return conn'
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  try:
#    ssh.connect(host,username='root',allow_agent=True,look_for_keys=True)
    ssh.connect(host,username='root',password='root',allow_agent=True)
    return ssh
  except:
    return None

def command(args,outpath):
  'this is get the command the args to return the command'
  cmd = '%s %s' % (outpath,args)
  return cmd

def exec_commands(conn,cmd):
  'this is use the conn to excute the cmd and return the results of excute the command'
  stdin,stdout,stderr = conn.exec_command(cmd)
  results=stdout.read()
  return results

def excutor(host,outpath,args):
  conn = connect(host)
  if not conn:
    return [host,None]
  #exec_commands(conn,'chmod +x %s' % outpath)
  cmd =command(args,outpath)
  result = exec_commands(conn,cmd)
  result = json.dumps(result)
  return [host,result]
def copy_module(conn,inpath,outpath):
    'this is copy the module to the remote server'
    ftp = conn.open_sftp()
    ftp.put(inpath,outpath)
    ftp.close()
    return outpath


if __name__ == '__main__':
    print json.dumps(excutor('192.168.1.165','ls',' -l'),indent=4,sort_keys=True)
    print copy_module(connect('192.168.1.165'),'kel.txt','/root/kel.1.txt')
    exec_commands(connect('192.168.1.165'),'chmod +x %s' % '/root/kel.1.txt')

主要就是使用python中的paramiko模块通过ssh连接linux服务器,然后执行相关的命令,并且将文件上传到服务器。

以上这篇python利用paramiko连接远程服务器执行命令的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用ctypes模块调用windowsapi获取系统版本示例
Apr 17 Python
简单解析Django框架中的表单验证
Jul 17 Python
Python使用redis pool的一种单例实现方式
Apr 16 Python
Python通过Django实现用户注册和邮箱验证功能代码
Dec 11 Python
Python图形绘制操作之正弦曲线实现方法分析
Dec 25 Python
Python图片转换成矩阵,矩阵数据转换成图片的实例
Jul 02 Python
对tensorflow中cifar-10文档的Read操作详解
Feb 10 Python
Python 炫技操作之合并字典的七种方法
Apr 10 Python
Python基于traceback模块获取异常信息
Jul 23 Python
如何使用python socket模块实现简单的文件下载
Sep 04 Python
python之语音识别speech模块
Sep 09 Python
python DataFrame中stack()方法、unstack()方法和pivot()方法浅析
Apr 06 Python
基于使用paramiko执行远程linux主机命令(详解)
Oct 16 #Python
python中文件变化监控示例(watchdog)
Oct 16 #Python
python中import reload __import__的区别详解
Oct 16 #Python
使用Python操作excel文件的实例代码
Oct 15 #Python
python出现"IndentationError: unexpected indent"错误解决办法
Oct 15 #Python
python 二分查找和快速排序实例详解
Oct 13 #Python
Python实现的排列组合计算操作示例
Oct 13 #Python
You might like
SSI指令
2006/11/25 PHP
PHP的curl实现get,post和cookie(实例介绍)
2013/06/17 PHP
用jquery生成二级菜单的实例代码
2013/06/24 Javascript
js中小数转换整数的方法
2014/01/26 Javascript
原生js和jQuery写的网页选项卡特效对比
2015/04/27 Javascript
AngularJS基础学习笔记之控制器
2015/05/10 Javascript
使用jquery.qrcode.js生成二维码插件
2016/10/17 Javascript
详解用vue-cli来搭建vue项目和webpack
2017/04/20 Javascript
解决ztree搜索中多级菜单展示不全问题
2017/07/05 Javascript
JS Input里添加小图标的两种方法
2017/11/11 Javascript
JavaScript原生实现观察者模式的示例
2017/12/15 Javascript
自定义vue组件发布到npm的方法
2018/05/09 Javascript
jQuery实现获取选中复选框的值实例详解
2018/06/28 jQuery
vue.js计算属性computed用法实例分析
2018/07/06 Javascript
vue.js动画中的js钩子函数的实现
2018/07/06 Javascript
解决vue 格式化银行卡(信用卡)每4位一个符号隔断的问题
2018/09/14 Javascript
微信小程序实现通过js操作wxml的wxss属性示例
2018/12/06 Javascript
详解React中合并单元格的正确写法
2019/01/08 Javascript
解决vue语法会有延迟加载显现{{xxx}}的问题
2019/11/14 Javascript
[05:31]干嘛呢兄弟!DOTA2 TI9语音轮盘部分出处
2019/05/14 DOTA
利用Python的装饰器解决Bottle框架中用户验证问题
2015/04/24 Python
Python用户推荐系统曼哈顿算法实现完整代码
2017/12/01 Python
Python使用Flask-SQLAlchemy连接数据库操作示例
2018/08/31 Python
Python的iOS自动化打包实例代码
2018/11/22 Python
Python常见数据类型转换操作示例
2019/05/08 Python
用OpenCV将视频分解成单帧图片,图片合成视频示例
2019/12/10 Python
Python特殊属性property原理及使用方法解析
2020/10/09 Python
聊聊python在linux下与windows下导入模块的区别说明
2021/03/03 Python
西班牙床垫网上商店:Colchones.es
2018/05/06 全球购物
太太口服液广告词
2014/03/20 职场文书
幼儿园安全责任书范本
2014/07/24 职场文书
2014年高中生自我评价范文
2014/09/26 职场文书
村党支部对照检查材料思想汇报
2014/09/28 职场文书
PHP命令行与定时任务
2021/04/01 PHP
Python移位密码、仿射变换解密实例代码
2021/06/27 Python
图文详解nginx日志切割的实现
2022/01/18 Servers