paramiko获取远端设备的内存使用率和CPU使用率

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

pkey = '当前目录下自己远端ssh设备的key'
key = paramiko.RSAKey.from_private_key_file(pkey)
ssh.connect('设备IP', username='设备用户名', pkey=key)
stdin, stdout, stderr = ssh.exec_command("free -h | sed -n '2p'|awk '{print $2}'")
totalmem = float(stdout.read().decode().split('G')[0])
print(totalmem)
stdin, stdout, stderr = ssh.exec_command("free -h | sed -n '3p'|awk '{print $3}'")
freemem = float(stdout.read().decode().split('G')[0])


use = round(float(freemem) / float(totalmem), 2)
print('当前内存使用率为:' + str(use*100)+'%')

#--------------------------------------------------------------------------------------------------

stdin, stdout, stderr = ssh.exec_command("top -b -n1 | sed -n '3p'|awk '{print $2}'")
cpu_usage = stdout.read().decode()
#print(cpu_usage)
print('当前CPU使用率为:' + cpu_usage.strip() + '%')

ssh.close()
### 脚本设计与实现 为了满足需求,可以利用 Python 的 `paramiko` 模块来建立 SSH 连接并执行命令。以下是完整的解决方案: #### 1. 使用 Paramiko 实现 SSH 远程连接 Paramiko 是一个用于实现 SSH 协议的 Python 库,能够轻松完成远程服务器的操作[^2]。 ```python import paramiko def ssh_connect_execute(hostname, username, password, command): try: # 创建SSH客户端实例 client = paramiko.SSHClient() # 自动添加主机密钥策略(忽略未知主机) client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 建立SSH连接 client.connect(hostname=hostname, username=username, password=password) # 执行命令 stdin, stdout, stderr = client.exec_command(command) # 获取标准输出错误输出 output = stdout.read().decode('utf-8') error = stderr.read().decode('utf-8') # 关闭连接 client.close() return output, error except Exception as e: return None, str(e) # 配置参数 hostname = "your_server_ip" username = "your_username" password = "your_password" # 执行 test 并查看进程列表 command_test = "test && ps aux | grep 'test'" # 先运行测试脚本再查找其进程 output_test, error_test = ssh_connect_execute(hostname, username, password, command_test) if error_test: print(f"Error occurred while executing the command: {error_test}") else: print("Command Output:") print(output_test) ``` 上述代码实现了通过 SSH 登录 Linux 服务器并执行命令的功能。其中,`ps aux | grep 'test'` 可以用来实时监控名为 `test` 的进程状态。 --- #### 2. 查看实时更新的进程信息 对于需要动态刷新的数据(如 `top`),可以通过设置一次性抓取的方式获取数据[^3]。例如: ```bash top -b -n 1 | head -n 4 | grep 'sy\|us' ``` 此命令会捕获一次性的 CPU 利用率统计信息,并过滤出系统 (`sy`) 用户 (`us`) 时间的比例。 如果希望更全面地展示所有进程的状态,则可以直接调用 `watch` 或者循环读取 `ps` 输出。但由于这些操作可能涉及大量数据流传输,在实际应用中需注意性能优化。 --- #### 3. 将脚本打包为可执行文件 要将该脚本转换为独立的 `.exe` 文件以便于分发使用,可以根据以下方法操作[^1]: ```bash pyinstaller --onefile your_script_name.py ``` 这一步骤将会把整个项目压缩至单个 EXE 文件形式发布给 Windows 用户运行而无需安装额外依赖环境。 --- ### 注意事项 - **安全性**: 不建议硬编码密码;考虑采用公私钥认证机制提升安全等级。 - **网络延迟影响**: 如果目标机器距离较远或者带宽有限,请适当调整超时时间以及缓冲区大小。 - **权限管理**: 确保所使用的账户具有足够的权限去启动所需服务及查询资源状况。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值