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 相关文章推荐
利用PyInstaller将python程序.py转为.exe的方法详解
May 03 Python
浅谈Python使用Bottle来提供一个简单的web服务
Dec 27 Python
Python模拟登录的多种方法(四种)
Jun 01 Python
在python中使用xlrd获取合并单元格的方法
Dec 26 Python
Python实现截取PDF文件中的几页代码实例
Mar 11 Python
pymysql的简单封装代码实例
Jan 08 Python
Python中 Global和Nonlocal的用法详解
Jan 20 Python
pytorch 使用加载训练好的模型做inference
Feb 20 Python
Python获取对象属性的几种方式小结
Mar 12 Python
jupyter notebook 调用环境中的Keras或者pytorch教程
Apr 14 Python
Python3 requests模块如何模仿浏览器及代理
Jun 15 Python
Python趣味入门教程之循环语句while
Aug 26 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
详解PHP对数组的定义以及数组的创建方法
2015/11/27 PHP
深入浅析yii2-gii自定义模板的方法
2016/04/26 PHP
php使用高斯算法实现图片的模糊处理功能示例
2016/11/11 PHP
PHP实现的抓取小说网站内容功能示例
2019/06/27 PHP
使用PHP+Redis实现延迟任务,实现自动取消订单功能
2019/11/21 PHP
Yii框架组件的事件机制原理与用法分析
2020/04/07 PHP
同一个表单 根据要求递交到不同页面的实现方法小结
2009/08/05 Javascript
通过DOM脚本去设置样式信息
2010/09/19 Javascript
23个Javascript弹出窗口特效整理
2011/02/25 Javascript
JavaScript 的继承
2011/10/01 Javascript
js实现checkbox全选和反选示例
2014/05/01 Javascript
jquery实现类似EasyUI的页面布局可改变左右的宽度
2020/09/12 Javascript
AngularJS语法详解
2015/01/23 Javascript
实现无刷新联动例子汇总
2015/05/20 Javascript
js+CSS实现模拟华丽的select控件下拉菜单效果
2015/09/01 Javascript
JS实现的自定义右键菜单实例二则
2015/09/01 Javascript
关于事件mouseover ,mouseout ,mouseenter,mouseleave的区别
2015/10/12 Javascript
精通JavaScript的this关键字
2020/05/28 Javascript
js实现鼠标单击Tab表单切换效果
2018/05/16 Javascript
详解Vue iview IE浏览器不兼容报错(Iview Bable polyfill)
2019/01/07 Javascript
如何使用pm2快速将项目部署到远程服务器
2019/03/12 Javascript
Python基于回溯法子集树模板解决野人与传教士问题示例
2017/09/11 Python
Sanic框架流式传输操作示例
2018/07/18 Python
PyGame贪吃蛇的实现代码示例
2018/11/21 Python
Python collections中的双向队列deque简单介绍详解
2019/11/04 Python
django2.2 和 PyMySQL版本兼容问题
2020/02/17 Python
Python使用windows设置定时执行脚本
2020/11/12 Python
Python爬虫之Selenium设置元素等待的方法
2020/12/04 Python
css3加js做一个简单的3D行星运转效果实例代码
2017/01/18 HTML / CSS
HTML5通过navigator.mediaDevices.getUserMedia调用手机摄像头问题
2020/04/27 HTML / CSS
Tenstickers法国:墙贴和装饰贴纸
2019/08/26 全球购物
介绍一下EJB的体系结构
2012/08/01 面试题
生产部厂长职位说明书
2014/03/03 职场文书
优秀团干部个人事迹
2014/05/29 职场文书
优秀班主任主要事迹材料
2014/12/16 职场文书
《灰雀》教学反思
2016/02/19 职场文书