再在代码中加入:设备信息从CSV文件中读取
时间: 2024-02-27 09:51:40 浏览: 26
好的,我们可以使用 Python 内置的 `csv` 模块来读取 CSV 文件中的设备信息,并在代码中使用这些信息来访问设备并获取 CPU 使用率。修改后的代码如下:
```python
import pexpect
import ping3
import csv
# 从 CSV 文件中读取设备信息
filename = "devices.csv"
with open(filename, "r") as f:
reader = csv.reader(f)
next(reader) # 跳过标题行
for row in reader:
device_ip, username, password, enable_password = row
# 检查设备是否在线
if not ping3.ping(device_ip):
print(f"设备 {device_ip} 不在线")
continue
# 访问设备
ssh = pexpect.spawn(f"ssh {username}@{device_ip}")
ssh.expect("password:")
ssh.sendline(password)
# 进入特权模式
ssh.expect(">")
ssh.sendline("enable")
ssh.expect("Password:")
ssh.sendline(enable_password)
# 获取 CPU 使用率
ssh.expect("#")
ssh.sendline("display cpu-usage")
ssh.expect("#")
output = ssh.before.decode("utf-8").strip()
# 输出结果
print(f"设备 {device_ip} 的 CPU 使用率为:")
print(output)
```
在上面的代码中,我们首先打开指定的 CSV 文件,并使用 `csv.reader` 方法读取文件中的内容。然后,我们使用 `next` 函数跳过标题行,然后遍历 CSV 文件中的每一行,获取设备 IP 地址、用户名、密码和特权模式密码。对于每个设备,我们都使用 `ping3.ping` 方法检查设备是否在线。如果设备不在线,就会输出一条提示信息,并使用 `continue` 关键字跳过当前循环,继续处理下一个设备。如果设备在线,就会继续执行后面的代码,访问设备并获取 CPU 使用率。
相关推荐
![m](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)