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 smtplib模块发送SSL/TLS安全邮件实例
Apr 08 Python
python使用xlrd实现检索excel中某列含有指定字符串记录的方法
May 09 Python
Python中super的用法实例
May 28 Python
python爬虫面试宝典(常见问题)
Mar 02 Python
Python基于whois模块简单识别网站域名及所有者的方法
Apr 23 Python
Python对切片命名的实现方法
Oct 16 Python
Python中shapefile转换geojson的示例
Jan 03 Python
基于wxPython的GUI实现输入对话框(2)
Feb 27 Python
在Python中COM口的调用方法
Jul 03 Python
Python Json数据文件操作原理解析
May 09 Python
python语言time库和datetime库基本使用详解
Dec 25 Python
python推导式的使用方法实例
Feb 28 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
关于Intype一些小问题的解决办法
2008/03/28 PHP
php 在文件指定行插入数据的代码
2010/05/08 PHP
PHP中替换换行符的几种方法小结
2012/10/15 PHP
PH P5.2至5.5、5.6的新增功能详解
2014/07/14 PHP
PHP读取配置文件类实例(可读取ini,yaml,xml等)
2015/07/28 PHP
详解js异步文件加载器
2016/01/24 PHP
[原创]图片分页查看
2006/08/28 Javascript
通过 Dom 方法提高 innerHTML 性能
2008/03/26 Javascript
js表头排序实现方法
2015/01/16 Javascript
Javascript中With语句用法实例
2015/05/14 Javascript
手机端转盘抽奖代码分享
2015/09/10 Javascript
javascript实现tab响应式切换特效
2016/01/29 Javascript
DIV随滚动条滚动而滚动的实现代码【推荐】
2016/04/12 Javascript
深入理解JavaScript中的尾调用(Tail Call)
2017/02/07 Javascript
详解vue-resource promise兼容性问题
2017/06/20 Javascript
vue elementUI table表格数据 滚动懒加载的实现方法
2019/04/04 Javascript
javascript中的数据类型检测方法详解
2019/08/07 Javascript
利用vue3+ts实现管理后台(增删改查)
2020/10/30 Javascript
[01:00:14]DOTA2-DPC中国联赛 正赛 Ehome vs Elephant BO3 第二场 2月28日
2021/03/11 DOTA
Python实现二分查找算法实例
2015/05/26 Python
python 多线程实现检测服务器在线情况
2015/11/25 Python
django1.8使用表单上传文件的实现方法
2016/11/04 Python
用Python删除本地目录下某一时间点之前创建的所有文件的实例
2017/12/14 Python
使用Python快速搭建HTTP服务和文件共享服务的实例讲解
2018/06/04 Python
对Python模块导入时全局变量__all__的作用详解
2019/01/11 Python
iPython pylab模式启动方式
2020/04/24 Python
用sleep间隔进行python反爬虫的实例讲解
2020/11/30 Python
HTML5注册表单的自动聚焦与占位文本示例代码
2013/07/19 HTML / CSS
瑜伽灵感珠宝:Satya Jewelry
2018/01/06 全球购物
精选鞋类、服装和配饰的全球领先目的地:Bodega
2021/02/27 全球购物
计算机专业职业规划
2014/02/28 职场文书
社保委托书怎么写
2014/08/02 职场文书
小学生十佳少年事迹材料
2014/08/20 职场文书
网络工程专业大学生求职信
2014/10/01 职场文书
CAD实训总结范文
2015/08/03 职场文书
关于元旦的广播稿2016
2015/12/17 职场文书