This script is to monitor whether the host is alive in a network segment, whether Port 22 is on, and whether the SSH login can be successfully logged through a unified user name and password, and the host IP that could be logged in is logged to the file.
Shortcomings is that I do not know whether to test SSH login, there is a ping address is really slow, but fortunately there is time to write a multi-threaded should be much faster.
The code is as follows:
#!/usr/bin/python# -*- coding:utf-8 -*-import osimport subprocessimport reimport socketimport paramikouser = ' 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, &nbsP; 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 ()) & nbsp; ssh.connect (IP,22,USER, PASSWD) #stdin, Stdout, stderr = ssh.exec_command ("Your command") #print stdout.readlines () Ssh.close () print ' login successful ' # f = open (' Login_ip.txt ', ' W ') ip = '%s\n ' % ip &nbsP; 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 ')
This article is from the "Eight Miles" blog, so be sure to keep this source http://5921271.blog.51cto.com/5911271/1580968
Python tests whether a network segment IP is alive, if a single port is enabled, and whether it can ssh