import time
import socket
import threading
def device_info():
ip_list = []
name_list = []
user_list = []
passwd_list = []
f = open('devices_list.txt',encoding='UTF-8')
for line in f.readlines():
line_s = line.split()
device_ip = line_s[0]
device_name = line_s[1]
username = line_s[2]
passwd = line_s[3]
ip_list.append(device_ip)
name_list.append(device_name)
user_list.append(username)
passwd_list.append(passwd)
f.close()
return ip_list,name_list,user_list,passwd_list
def ssh_f(ip,name,user,passwd):
data = time.strftime('%Y-%m-%d')
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip, username=user, password=passwd)
print('成功连接', ip, name,'
')
cmd_file = open('cmd.txt', 'r')
cmds = cmd_file.readlines()
log = open(r'D:BaiduNetdiskDownload est巡检日志\' + ip + name + data + '.txt', 'a')
command = ssh_client.invoke_shell()
command.send('terminal length 0
') # 取消单屏显示
for cmd in cmds:
command.send(cmd+'
')
time.sleep(1)
output = command.recv(65535)
log.write(output.decode('UTF-8'))
print(ip + '日志载入成功'+'
')
ssh_client.close()
log.close()
def main():
device_authentication_failed_list = []
device_not_reachable_list = []
ip_list,name_list,user_list,passwd_list = device_info()
for ip,name,user,passwd in zip(ip_list,name_list,user_list,passwd_list): # 遍历多个列表可以用zip
try:
a = threading.Thread(target=ssh_f,args=(ip,name,user,passwd))
a.start()
except paramiko.ssh_exception.AuthenticationException:
print(name + '(' + ip + ')' + '身份验证登录失败..')
device_authentication_failed_list.append(ip)
except socket.error:
print(name + '(' + ip + ')' + ' 网络无法访问..')
device_not_reachable_list.append(ip)
time.sleep(5)
print('
以下设备身份验证登录失败: ')
if device_authentication_failed_list == []:
print('nothing')
else:
for i in device_authentication_failed_list:
print(i)
print('
网络无法访问以下设备:')
if device_not_reachable_list == []:
print('nothing')
else:
for i in device_not_reachable_list:
print(i)
if __name__ == '__main__':
main()