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二分法实现实例
Nov 21 Python
MySQL最常见的操作语句小结
May 07 Python
python查看微信好友是否删除自己
Dec 19 Python
pandas.loc 选取指定列进行操作的实例
May 18 Python
Python实现的txt文件去重功能示例
Jul 07 Python
python得到windows自启动列表的方法
Oct 14 Python
python 列表递归求和、计数、求最大元素的实例
Nov 28 Python
python+opencv打开摄像头,保存视频、拍照功能的实现方法
Jan 08 Python
python对列进行平移变换的方法(shift)
Jan 10 Python
Python控制Firefox方法总结
Jun 03 Python
python tkinter组件摆放方式详解
Sep 16 Python
django中ImageField的使用详解
Dec 21 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
动漫定律:眯眯眼都是怪物!这些角色狠话不多~
2020/03/03 日漫
解析如何去掉CodeIgniter URL中的index.php
2013/06/25 PHP
ThinkPHP5.1框架页面跳转及修改跳转页面模版示例
2019/05/06 PHP
你所要知道JS(DHTML)中的一些技巧
2007/01/09 Javascript
javascript String 对象
2008/04/25 Javascript
JS点击链接后慢慢展开隐藏着图片的方法
2015/02/17 Javascript
使用jQuery获取data-的自定义属性
2015/11/10 Javascript
jQuery学习之DOM节点的插入方法总结
2017/01/22 Javascript
vue.js国际化 vue-i18n插件的使用详解
2017/07/07 Javascript
基于Vue2.0+ElementUI实现表格翻页功能
2017/10/23 Javascript
学习JS中的DOM节点以及操作
2018/04/30 Javascript
基于Bootstrap下拉框插件bootstrap-select使用方法详解
2018/08/07 Javascript
微信小程序性能优化之checkSession的使用
2019/03/06 Javascript
小程序实现短信登录倒计时
2019/07/12 Javascript
layui监听单元格编辑前后交互的例子
2019/09/16 Javascript
vue-cli3 热更新配置操作
2020/09/18 Javascript
JavaScript实现原型封装轮播图
2020/12/27 Javascript
[44:40]2018DOTA2亚洲邀请赛3月30日 小组赛A组Liquid VS OG
2018/03/31 DOTA
python缩进区别分析
2014/02/15 Python
wxpython中Textctrl回车事件无效的解决方法
2016/07/21 Python
Python sep参数使用方法详解
2020/02/12 Python
Python Django view 两种return的实现方式
2020/03/16 Python
CSS3 mask 遮罩的具体使用方法
2017/11/03 HTML / CSS
Melissa香港官网:MDreams
2016/07/01 全球购物
马来西亚网上购物:Youbeli
2018/03/30 全球购物
怎样从/向数据文件读/写结构
2014/11/23 面试题
保送生自荐信范文
2013/10/06 职场文书
三好学生自我鉴定
2013/12/17 职场文书
暑期实践思想汇报
2014/01/06 职场文书
幼儿园教师培训制度
2014/01/16 职场文书
建筑系毕业生自我鉴定
2014/01/24 职场文书
涉外离婚协议书怎么写
2014/11/20 职场文书
2014年幼儿园保育工作总结
2014/12/02 职场文书
2014年财政局工作总结
2014/12/09 职场文书
Django框架模板用法详解
2022/06/10 Python
win10如何更改appdata文件夹的默认位置?
2022/07/15 数码科技