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连接远程服务器执行命令的更多相关文章
- Python实现SSH连接远程服务器
首先需要安装paramiko模块 #-*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import paramiko ssh = p ...
- python-ssh-远程服务器+远程docker执行命令
在python语言中实现远程服务器执行命令+远程dcoker执行命令 def ssh_exec_command(ip, username, password, cmd=None): "&qu ...
- [转]python3之paramiko模块(基于ssh连接进行远程登录服务器执行命令和上传下载文件的功能)
转自:https://www.cnblogs.com/zhangxinqi/p/8372774.html 阅读目录 1.paramiko模块介绍 2.paramiko的使用方法 回到顶部 1.para ...
- python利用paramiko执行服务器命令
话不多说直接上代码 封装连接 @staticmethod def connect(ip, server_user, server_port, server_path): ""&qu ...
- 【python】用python脚本Paramiko实现远程执行命令、下载、推送/上传文件功能
Paramiko: paramiko模块,基于SSH用于连接远程服务器并执行相关操作. SSHClient: 用于连接远程服务器并执行基本命令 SFTPClient: 用于连接远程服务器并执行上传下载 ...
- Python—实现ssh客户端(连接远程服务器)
paramiko是一个基于SSH用于连接远程服务器并执行相关操作(SSHClient和SFTPClinet,即一个是远程连接,一个是上传下载服务),使用该模块可以对远程服务器进行命令或文件操作,值得一 ...
- websocket+Django+python+paramiko实现web页面执行命令并实时输出
一.概述 WebSocket WebSocket的工作流程:浏览器通过JavaScript向服务端发出建立WebSocket连接的请求,在WebSocket连接建立成功后,客户端和服务端就可以通过 T ...
- paramiko模块(基于SSH用于连接远程服务器)
paramiko模块,基于SSH用于连接远程服务器并执行相关操作 class SSHConnection(object): def __init__(self, host_dict): self.ho ...
- windows连接远程服务器报错'SSH' 不是内部或外部命令,也不是可运行的程序 或批处理文件 解决方案
网上在windows下连接远程服务器的步骤如下: 1.打开cmd命令行窗口 2.输入cd ~/.ssh,进入c盘下的.ssh文件 3.输入“ssh root@远程服务器的ip地址”连接远程服务器, b ...
随机推荐
- Java里Serializable的那些事
本文为原创文章,欢迎转载,但请注明出处http://www.cnblogs.com/yexiubiao/p/5014015.html,未在文章页面明显位置给出原文连接的,将保留追究法律责任的权利. 通 ...
- Python的枚举类型
Python的 Python的没有我们有两种用法: 创建Enum的实例 创建Enum的subclass 创建Enum的实例 from enum import Enum, unique Month = ...
- Super Ugly Number
eg 2,3,5 把第一个元素(2,1)放到最小堆,2表示乘积,1表示乘数 乘数 队列 最小堆 即将进 ...
- 【转】启动 Eclipse 弹出“Failed to load the JNI shared library jvm.dll”错误的解决方法! .
转载地址:http://blog.csdn.net/zyz511919766/article/details/7442633 原因1:给定目录下jvm.dll不存在. 对策:(1)重新安装jre或者j ...
- pci 记录
用linux 下的sysfs可以方便的查看pci设备的配置和资源. 所有的pci设备在/sys/bus/pci/device 下面看到 pci配置空间对应的是设备对应的目录下的config文件,是二进 ...
- Linq无聊练习系列7----Insert,delete,update,attach操作练习
/*********************Insert,delete,update,attach操作练习**********************************/ ...
- 【转】Redis学习笔记(四)如何用Redis实现分布式锁(1)—— 单机版
原文地址:http://bridgeforyou.cn/2018/09/01/Redis-Dsitributed-Lock-1/ 为什么要使用分布式锁 这个问题,可以分为两个问题来回答: 为什么要使用 ...
- JNI C反射调用java方法
前面记录了调用C的学习笔记,现在来记录一下C反射调用Java的笔记.JNI开发学习之调用C方法 Android开发中调用一个类中没有公开的方法,可以进行反射调用,而JNI开发中C调用java的方法也是 ...
- windows查询占用端口
https://jingyan.baidu.com/article/3c48dd34491d47e10be358b8.html 1)端口号 - 查进程 netstat -aon|findstr &qu ...
- BZOJ 3489 A simple rmq problem 可持久化KDtree/二维线段树
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=3489 题意概述: 给出一个序列,每次询问一个序列区间中仅出现了一次的数字最大是多少,如果 ...