【Python小隨筆】 SSH 獲取資訊

PythonNew_Mr.Wang發表於2024-03-23
import paramiko



# 獲取資訊
def check_msg(hostname,username,password):
    # 建立 SSH 客戶端例項
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(hostname, 22, username, password)
    dists = {}
    # HOSTNAME
    stdin, stdout, stderr = ssh_client.exec_command('hostname')
    hostname = stdout.read().decode("utf-8").replace("\n","")
    dists['Hostname'] = hostname
    # CPU
    stdin, stdout, stderr = ssh_client.exec_command('lscpu')
    output = stdout.read().decode()
    cpu_info = {}
    for line in output.split('\n'):
        if ':' in line:
            key, value = line.split(':', 1)
            cpu_info[key.strip()] = value.strip()
    dists['CPU'] = cpu_info.get("Model name", "N/A")
    dists['JiaGou'] = cpu_info.get("Architecture", "N/A")
    dists['CPUS'] = cpu_info.get("CPU(s)", "N/A")
    stdin, stdout, stderr = ssh_client.exec_command('top -bn1 | grep "Cpu(s)"')
    output = stdout.read().decode()
    cpu_usage = output.split('Cpu(s):', 1)[1].strip().split(',')
    for item in cpu_usage:
        if 'id' in item:
            idle_percentage = item.split()[0]
    cpu_use = round(100 - float(idle_percentage),2)
    dists['CPUuse'] = str(cpu_use) + "%"
    # 記憶體
    stdin, stdout, stderr = ssh_client.exec_command('free -m')
    output = stdout.read().decode("utf-8").split('\n')
    for line in output:
        if line.startswith('Mem:'):
            # 分割每行並提取關鍵資訊
            parts = line.split()
            total_memory = int(parts[1])
            used_memory = int(parts[2])
            free_memory = int(parts[3])
            dists['TotalMemory'] = str(total_memory) + " MB"
            dists['UsedMemory'] = str(used_memory) + " MB"
            dists['FreeMemory'] = str(free_memory) + " MB"
    # 硬碟
    stdin, stdout, stderr = ssh_client.exec_command('df -h')
    output = stdout.read().decode("utf-8").split('\n')
    disk_space_info = []
    for line in output:
        if line.startswith('/'):
            disk_info = line.split()
            filesystem = disk_info[0]
            size = disk_info[1]
            used = disk_info[2]
            available = disk_info[3]
            use_percentage = disk_info[4]
            mount_point = disk_info[5]
            disk_space_info.append({
                'filesystem': filesystem,
                'size': size,
                'used': used,
                'available': available,
                'use_percentage': use_percentage,
                'mount_point': mount_point
            })
    # dists['FreeDisk']
    yingpan = ""
    count = 0
    for disk in disk_space_info:
        count = count + 1
        yingpan = yingpan +  f"  第{count}塊硬碟資訊:總大小:{disk['size']},已使用:{disk['used']},使用佔比:{disk['use_percentage']}"
    dists['Disk'] = yingpan
    # 關閉 SSH 連線
    ssh_client.close()
    return dists


# 傳送檔案
def send(hostname,username,password,local_path,remote_path):
    """
    :param local_path:
    :param remote_path:
    :return:
    """
    try:
        # 建立 SSH 連線
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname, 22, username, password)
        sftp = ssh_client.open_sftp()
        sftp.put(local_path, remote_path)
        # 關閉 SFTP 客戶端和 SSH 連線
        sftp.close()
        ssh_client.close()
        return 1
    except:
        return 0


if __name__ == '__main__':
    # 設定 SSH 連線引數
    hostname = '192.168.88.101'
    username = 'root'
    password = '123456'


    send(hostname, username, password,r'C:\Users\17750\Desktop\TEST.txt',"/home/TEST.txt")

相關文章