这几天被ChatGPT玩坏了,为什么说是被玩呢,这东西真的太强大了,我现在用的还是版本3就专业溜了,现在已经有版本4了,详细一些人工智能真的还快就会取代一大批只会CV程序员,所以你有什么理由不学习呢。 我觉得以后这随便都可以直接从ChatGPT上提要求然后搬运过来就是了,都可不用写了
编写一个自动化网络设巡检python程序
为了编写一个自动化网络设备巡检的Python程序,你需要遵循以下步骤:
pythonCopy codeimport paramiko
from netmiko import ConnectHandler
import subprocess
import requests
pythonCopy codedef ssh_connect(host, port, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
return ssh
pythonCopy codedef device_check(ip, username, password):
device = {
'device_type': 'cisco_ios',
'ip': ip,
'username': username,
'password': password,
}
net_connect = ConnectHandler(**device)
cpu = net_connect.send_command('show processes cpu sorted | exclude 0.00%CPU')
memory = net_connect.send_command('show processes memory sorted | exclude 0.00%')
interfaces = net_connect.send_command('show ip interface brief | exclude unassigned')
net_connect.disconnect()
return cpu, memory, interfaces
pythonCopy codeimport smtplib
from email.mime.text import MIMEText
def send_email(from_addr, to_addr, subject, body, smtp_server, smtp_port, username, password):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = to_addr
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.login(username, password)
server.sendmail(from_addr, to_addr, msg.as_string())
pythonCopy codedef main():
devices = [
{
'ip': '192.168.1.1',
'username': 'admin',
'password': 'password',
},
{
'ip': '192.168.1.2',
'username': 'admin',
'password': 'password',
},
{
'ip': '192.168.1.3',
'username': 'admin',
'password': 'password',
},
]
for device in devices:
cpu, memory, interfaces = device_check(device['ip'], device['username'], device['password'])
if cpu > 80 or memory > 80:
send_email('from@example.com', 'to@example.com', 'Device Alert', f'Device {device['ip']} is experiencing high CPU or memory usage.', 'smtp.example.com', 587, 'username', 'password')
这是一个简单的框架,
网络设备巡检用python编写一个自动化程序
以下是一个简单的网络设备巡检自动化程序的 Python 代码示例,可以用于检查网络设备的基本配置和状态信息:
复制import paramiko
# 定义设备列表
devices = [
{
"hostname": "192.168.1.1",
"username": "admin",
"password": "password",
"port": 22
},
{
"hostname": "192.168.1.2",
"username": "admin",
"password": "password",
"port": 22
}
]
# 定义命令列表
commands = [
"show version",
"show interfaces",
"show ip route"
]
# 遍历设备列表
for device in devices:
# 创建 SSH 客户端
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接设备
client.connect(
hostname=device["hostname"],
username=device["username"],
password=device["password"],
port=device["port"]
)
# 遍历命令列表
for command in commands:
# 执行命令
stdin, stdout, stderr = client.exec_command(command)
# 输出命令结果
print(f"Device: {device['hostname']}, Command: {command}")
print(stdout.read().decode())
# 关闭 SSH 连接
client.close()
上述代码使用 Paramiko 库连接到设备并执行命令。在实际使用中,可以根据需要添加更多的命令和设备信息。此外,还可以使用其他 Python 库来解析命令输出并提取有用的信息,例如使用正则表达式或 Beautiful Soup 库来解析 HTML 输出。