python利用paramiko连接远程服务器执行命令的方法
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连接远程服务器执行命令的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
- Android实现图片异步加载操作
- (PDF.NET框架实例讲解)将存储过程映射为实体类
- 【开源】QuickPager ASP.NET2.0分页控件——使用示例、基本应用和查询功能
- 移花接木:当泛型方法遇上抽象类----我的“内存数据库”诞生记
- Android扫描多媒体文件剖析
- Android的进程与线程使用总结
- Android在WebView中加载HTML并实现交互
- 使用ASP.NET MVC2+PDF.NET 构建一个简单的新闻管理程序 示例过程
- 【开源】QuickPager ASP.NET2.0分页控件V2.0.0.3 【增加了使用说明】
- Android中Java和JavaScript交互
- Android UI控件系列:TabWidget(切换卡)
- 在Linux系统运行WinForm程序
- 将ZIP文件添加到程序集资源文件然后在运行时解压文件
- Android中App安装位置详解
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法