文章目录

  • 环境要求
  • 远程操作的核心模块
  • 调用方法


环境要求

需要python的第三方模块:paramiko
注意:该模块的依赖包非常多,并且安装中可能出现各种报错,安装时需要有心理准备~~~

远程操作的核心模块

设如下脚本的名称为REXEC.py:

python 怎么查看远程参数 包版本有哪些_python
python 怎么查看远程参数 包版本有哪些_python_02

#/usr/bin/python
#! -*- coding:utf-8 -*-
# @CreateTime: 2019/9/6 17:19
# @Auth      : WillZhu
# @FileName  : REXEC.py
# @UpdateTime: -

import paramiko


host_default_info = {'port':端口号,'user':'你的用户名','pwd':'你猜你猜'}



def rexec_single(host_msg_dict, command):
    """
    :param host_msg_dict: 某台服务器的授权信息,类型为字典,包含的key有:ip/port/user/pwd.其中后面3个key可缺失,缺失的部分用host_default_info中对应的键值代替
    :param command: 需要在远程服务器上执行的指令
    :return: 返回远程执行结果:  {'status':'执行状态(P成功,E为错误,F为返回内容中有失败信息,)', 'ef_msg':'错误或失败信息', 'result':结果内容}
    """
    #解析远程服务器授权信息

    if type(host_msg_dict) != dict:
        return {'status':'E', 'ef_msg':"""远程服务器登录信息格式错误!\n输入的远程连接权限信息必须为字典格式,如:\n{'ip':'', 'port':'','user':'','pwd':''}\n其中ip键值对必须存在,其余键值对如果不存在,本程序则使用默认值。""", 'result':''}
    if 'ip' not in host_msg_dict.keys():
        return {'status': 'E', 'ef_msg': '远程服务器IP必须输入', 'result':''}

    ip = host_msg_dict['ip']
    port = host_default_info['port'] if 'port' not in host_msg_dict.keys() else host_msg_dict['port']
    user = host_default_info['user'] if 'user' not in host_msg_dict.keys() else host_msg_dict['user']
    pwd  = host_default_info['pwd'] if 'pwd' not in host_msg_dict.keys() else host_msg_dict['pwd']

    #开始远程处理
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  #防止出现not found in known_hosts
        ssh_client.connect(ip,port,user,pwd)
        std_in, std_out, std_err = ssh_client.exec_command(command)
        get_stdout = str(std_out.read(),encoding='utf-8')
        get_stderr = str(std_err.read(),encoding='utf-8')
        return_msg = [ get_stdout, get_stderr]
        ssh_client.close()
        status = 'F' if return_msg[1] else 'P'
        return {'status':status, 'ef_msg': return_msg[1], 'result':return_msg[0]}
    except Exception as e:
        return {'status': 'E', 'ef_msg':  '[远程操作发生异常]%s'%e, 'result':''}

$\color{blue} {PS:目前只支持单个服务器的远程操作,后续需要使用多线程和队列模块增加一个并行等落多个服务器的方法。} $

调用方法

调用示例test.py:

from REXEC import rexec_single
#host_msg的格式为:{"ip":"", "port":"","user":"","pwd":""},其中ip是必须的,其余key值如果和默认值相同,可不用填
host_msg = {"ip":"10.255.4.17"}
remote_script = "df -h"
res = rexec_single(host_msg, remote_script)
if res['status'] != 'P':
    print(res['ef_msg'])
else:
    print(res['result'])

执行结果:

>>test.py
Filesystem            Size  Used Avail Use% Mounted on
/dev/vda1              20G  4.0G   15G  21% /
/dev/vdb              153G   22G  123G  16% /data


Process finished with exit code 0