4rwgf 发表于 2014-11-24 09:11:42

python测试某个网段IP存活、单端口是否开启、是否能ssh

这个脚本是为了在一个网段监测主机是否存活,22端口是否开启,并通过统一的用户名和密码是否能成功ssh登录,并将可以登录的主机IP记录到文件中。
不足之处就是这么判断不知是否可以准确测试ssh登录,还有就是一个个ping地址实在是速度太慢了,不过还好有时间写个多线程应该就快多了。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/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')



页: [1]
查看完整版本: python测试某个网段IP存活、单端口是否开启、是否能ssh