pyhon 多节点安装部署

# !/usr/bin/env python3

# -*- coding: utf-8 -*-

'

import shlex

import subprocess

__author__ = 'gyz'

import tarfile
import socket
import paramiko
import time


def un_gz(sourceFile, targetDir):
    """ungz zip file"""
    tar = tarfile.open(sourceFile)
    names = tar.getnames()
    for name in names:
        tar.extract(name, path=targetDir)
    tar.close()
    # 关闭gzip对象


def isOpen(ip, port):
    time.sleep(3)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip, int(port)))
        s.shutdown(2)
        # 利用shutdown()函数使socket双向数据传输变为单向数据传输。shutdown()需要一个单独的参数,
        # 该参数表示了如何关闭socket。具体为:0表示禁止将来读;1表示禁止将来写;2表示禁止将来读和写。
        return True
    except:
        return False


def executeCommand(cmdstring, cwd=None, shell=False):
    """执行一个SHELL命令
        封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr
        参数:
      cwd: 运行命令时更改路径,如果被设定,子进程会直接先更改当前路径到cwd
      timeout: 超时时间,秒,支持小数,精度0.1秒
      shell: 是否通过shell运行
    Returns: return_code
    Raises: Exception: 执行超时
    """
    if shell:
        cmdstring_list = cmdstring
    else:
        cmdstring_list = shlex.split(cmdstring)

    # 没有指定标准输出和错误输出的管道,因此会打印到屏幕上;
    sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE, shell=shell, bufsize=4096)

    # subprocess.poll()方法:检查子进程是否结束了,如果结束了,设定并返回码,放在subprocess.returncode变量中
    sub.wait()
    return sub.returncode


def scpFile(ip, port, username, password, *localFileAndTargetFileSplitBy_Space_):
    if not isinstance(localFileAndTargetFileSplitBy_Space_, (list, tuple)):
        return

    ssh = paramiko.SSHClient()
    # 允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接服务器

    ssh.connect(ip, port, username, password, allow_agent=False)
    # private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
    sftp = paramiko.SFTPClient.from_transport(ssh.get_transport())
    for pair in localFileAndTargetFileSplitBy_Space_:
        paths = pair.split("_ _", 2)
    sftp.put(paths[0], paths[1])
    sftp.close()
    ssh.close()


def cmdRemote(ip, port, username, password, cmds):
    if not isinstance(cmds, (list, tuple)):
        return
    ssh = paramiko.SSHClient()
    # 允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接服务器

    ssh.connect(ip, port, username, password, allow_agent=False)
    # private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
    result = []
    for cmd in cmds:
        stdin, stdout, stderr = ssh.exec_command(cmd)
        result.append(stdout.read())

    ssh.close()
    return result
 

猜你喜欢

转载自blog.csdn.net/qq_37303226/article/details/80731829