Python3 SSH批量命令下发(支持H3C/CISCO/HUAWEI)
前言
基于CentOS7的批量命令下发,CentOS安装相关组件命令如下:
CentOS7最小化安装后
yum install python3 -y #安装python3
pip3 install paramiko # 安装SSH模块
命令&文件格式
设备读取文件:存放在/home目录下
vim /home/user.csv
host_ip,host_port,user,password,type
10.1.1.102,22,cisco,cisco,cisco
10.1.1.103,22,cisco,cisco,cisco
10.1.1.104,22,cisco,cisco,cisco
10.1.1.101,22,cisco,cisco,cisco
命令行存放文本格式:
vim /home/cisco.txt
enable
conf t
do wr
注意创建的命令行文件名必须:h3c.txt/cisco.txt/hw.txt,其中type作为识别项:cisco,hw,h3c
PS:不要留下空行
脚本内容
#! /bin/python3
import paramiko,time,csv,threading,os
filepath="/home/user.csv"
h3c_Command="/home/h3c.txt"
hw_Command="/home/hw.txt"
cisco_Command="/home/cisco.txt"
sem=threading.Semaphore(4) #线程并发
date=time.strftime("%Y年%m月%d日")
txt=[ h3c_Command,hw_Command,cisco_Command ]
os.system(" touch /home/hw.txt & touch /home/h3c.txt & touch /home/cisco.txt")
filename="/home/"+date
f = open(filepath)
reader = csv.reader(f)
try:
os.mkdir(filename)
except:
print(filename,"文件夹已被创建!")
def user():
f = open(filepath)
next(f)
print("登录以下设备:")
for i in f:
i=i[:-1]
ip,type = i.split(',')[0],i.split(',')[4]
print("Device_IP:%s Device_Type:%s" %(ip,type,))
else:
f.close()
time.sleep(3)