批量执行命令

服务器列表保存在字典中

import paramiko
import sys

def sshExecCMDS(ip,username,password,port):
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh_client.connect(hostname=ip,port=port,username=username,password=password)
    except Exception as e:
        print("连接服务器异常!错误信息{}".format(e))
        sys.exit()

    stdin, stdout, stderr = ssh_client.exec_command("df -h")
    print("服务器{}磁盘使用率信息".format(ip))
    print(stdout.read().decode("utf-8"))
    ssh_client.close()

if __name__ == '__main__':
    #多台主机执行,暂时跑字典
    servers = {
        "172.16.2.225":{
            "username": "root",
            "password": "123456",
            "port": 22
        },
        "172.16.2.231": {
            "username": "root",
            "password": "123456",
            "port": 22
        },
        "172.16.2.233": {
            "username": "root",
            "password": "123456",
            "port": 22
        },

    }

    for ip,info in servers.items():
        print(ip,info.get("username"))
        sshExecCMDS(ip=ip,username=info.get("username"),password=info.get("password"),port=info.get("port"))

批量上传文件

import paramiko
import os
"""
    localfile:本地文件夹名称
    remotedir:服务器目录名称
"""

def sshPutFile(ip,port,username,password,localfile,remotedir):
    # 获取源文件的文件名
    file_name = os.path.basename(localfile)

    # 处理服务器目录名称 /etc/
    if not remotedir.endswith("/"):
        remotedir = remotedir + "/"

    dest_file_name = remotedir + file_name

    # 创建ssh连接
    ssh_conn = paramiko.Transport((ip,port))
    ssh_conn.connect(username=username,password=password)

    ftp_client = paramiko.SFTPClient.from_transport(ssh_conn)
    ftp_client.put(localfile,dest_file_name)

    ssh_conn.close()

if __name__ == '__main__':
    servers = {
        "172.16.2.225": {
            "username": "root",
            "password": "123456",
            "port": 22
        },
        "172.16.2.231": {
            "username": "root",
            "password": "123456",
            "port": 22
        },
        "172.16.2.233": {
            "username": "root",
            "password": "123456",
            "port": 22
        },

    }

    # 源文件名称(以绝对路径):xx.txt
    source_file = input("源文件名称(以绝对路径):")
    # 上传到的服务器目录名称: /root
    remote_dir = input("上传到的服务器目录名称: ")

    for ip,info in servers.items():
        sshPutFile(
            ip=ip,
            port=info.get("port"),
            username=info.get("username"),
            password=info.get("password"),
            localfile=source_file,
            remotedir=remote_dir
        )

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处

本文链接:http://kkxl95.cn/article/1597824328/