笔记:Python 远程连接linux并执行命令(示例)

import paramiko
from paramiko.ssh_exception import AuthenticationException, SSHException

host = "10.24.217.31"
port = 22
username = "root"
password = "eV&**!!2024"
try:
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, port, username, password)
    stdin, stdout, stderr = ssh.exec_command('free -g')
    output = stdout.read().decode()
    # 分析输出并提取内存信息
    lines = output.split('\n')
    mem_info = {}
    for line in lines:
        if 'Mem' in line:
            total, used, free, shared, buffers, cached = line.split()[1:][:6]
            mem_info['total'] = int(total)
            mem_info['used'] = int(used)
            mem_info['free'] = int(free)
            mem_info['buffers'] = int(buffers)
            mem_info['cached'] = int(cached)
            break
    ssh.close()
    print(mem_info)
except AuthenticationException:
    print("Authentication failed.")
except SSHException as e:
    print(f"SSH error occurred: {e}")
except Exception as e:
    print(f"Error occurred: {e}")
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值