这个脚本是为了在一个网段监测主机是否存活,22端口是否开启,并通过统一的用户名和密码是否能成功ssh登录,并将可以登录的主机IP记录到文件中。
不足之处就是这么判断不知是否可以准确测试ssh登录,还有就是一个个ping地址实在是速度太慢了,不过还好有时间写个多线程应该就快多了。
代码如下:
#!/usr/bin/python # -*- coding:utf-8 -*- import os import subprocess import re import socket import paramiko user = ‘root‘ passwd = ‘123456‘ def ip(file,field): ip_field = field ip_file = open(file,‘w‘) for i in range(1,256): ip = ‘%s%s\n‘ % (ip_field,i) ip_file.write(ip) ip_file.close() def test_ip(file): file = open(file,‘r‘) ip_list = [] port = 22 f = open(‘login_ip.txt‘,‘w‘) for line in file.readlines(): line=line.strip(‘\n‘) ip_list.append(line) for ip in ip_list: p = subprocess.Popen(["ping -c 1 "+ ip], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) out = p.stdout.read() regex = re.compile("time=\d*", re.IGNORECASE | re.MULTILINE) if len(regex.findall(out)) > 0: print ip + ‘: Host Up!‘ s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((ip,int(port))) s.shutdown(2) print ‘%d is open‘ % port try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,22,user, passwd) #stdin, stdout, stderr = ssh.exec_command("你的命令") #print stdout.readlines() ssh.close() print ‘Login successful‘ # f = open(‘login_ip.txt‘,‘w‘) ip = ‘%s\n‘ % ip f.write(ip) # return True except: print ‘The login problem, please check your username and password‘ except: print ‘%d is down‘ % port # return False else: print ip + ‘: Host Down!‘ file.close() f.close() ip(‘test‘,‘192.168.209.‘) test_ip(‘test‘)
时间: 2024-10-06 11:46:36