sergkh

Untitled

Sep 13th, 2017
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.12 KB | None | 0 0
  1. import re
  2. import argparse
  3. import paramiko
  4. from netaddr import IPAddress
  5.  
  6.  
  7.  
  8.  
  9. def scanparams():
  10.     parser = argparse.ArgumentParser(description='scan hardware at remote host using /proc /sys data via ssh connection.')
  11.     parser.add_argument("scanedhost", help="IP or hostname for detecting hardware", type = str, default = '127.0.0.1')
  12.     parser.add_argument("-s", "--sshkey", help="path to the ssh private file ", default = './.ssh/id_rsa')
  13.    
  14.     args = parser.parse_args()
  15.     hostlist = args.scanedhost.split(",")
  16.     print("args: {0}; {1}".format(args.scanedhost, args.sshkey))
  17.     return args.sshkey, hostlist
  18.    
  19. def detecthostname(client):
  20.     """ """
  21.     stdin,stdout,stderr = client.exec_command('hostname')
  22.     return stdout.readlines()[0]
  23. def detectcpu(client):
  24.     """ detecting cpu models and count it"""
  25.     stdin,stdout,stderr = client.exec_command('cat /proc/cpuinfo')
  26.     cpuinfotext = stdout.readlines()
  27.     cpucount = 0
  28.     cpuname = 'not detected'
  29.     for mystr in cpuinfotext:
  30.         m = re.search('(^model\ name\t)(?P<cpuname>.*)', mystr)
  31.         if m is not None:
  32.             cpucount +=1
  33.             cpuname = m.group('cpuname')
  34.     return cpuname, cpucount
  35. def detectmemory(client):
  36.     """ """
  37.     stdin,stdout,stderr = client.exec_command('cat /proc/meminfo')    
  38.     return stdout.readlines()[0].split()[1]
  39. def detectdrives(client):
  40.     """ """
  41.     stdin,stdout,stderr = client.exec_command('ls /sys/block')
  42.     devicelist = stdout.readlines()
  43.     localdrivelist = []
  44.     drives = {}
  45.     for localdrive  in devicelist:
  46.         m = re.search('(?P<drivename>h|sd.)',localdrive)
  47.         if m  is not None:
  48.             localdrivelist.append(m.group('drivename'))
  49.     for selecteddrive in localdrivelist:
  50.         drives[selecteddrive] = {}          
  51.         stdin,stdout,stderr = client.exec_command('cat /sys/class/block/{0}/device/model'.format(selecteddrive))
  52.         drives[selecteddrive]['model'] = stdout.readlines()[0].rstrip()
  53.         stdin,stdout,stderr = client.exec_command('cat /sys/block/{0}/size'.format(selecteddrive))
  54.         drivesize = int(stdout.readlines()[0])/2028
  55.         drives[selecteddrive]['size'] = drivesize
  56.     return drives
  57. def detectnetworkcards(client):
  58.     """ detect netcar procedure"""
  59.     busvendordict = {}
  60.     namesettingdict = {}
  61.     netcardlist = []
  62.     stdin,stdout,stderr = client.exec_command("lspci")
  63.     etherlist= stdout.readlines()
  64.     for mystr in etherlist:
  65.         m = re.search('(?P<hwid>^[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-9a-fA-F]) Ethernet controller: (?P<vendorname>.*)', mystr)
  66.         if m is not None:
  67.             busvendordict[m.group('hwid')] = m.group('vendorname')
  68.             netcardlist.append({'hardwareid':m.group('hwid'),'vendorname':m.group('vendorname')})
  69.     for hwid in busvendordict:
  70.         stdin,stdout,stderr = client.exec_command('ls /sys/bus/pci/devices/0000\:{0}/net/'.format(hwid))
  71.         systemname = stdout.readlines()[0].rstrip()
  72.         for card in netcardlist:
  73.             if card['hardwareid'] == hwid:
  74.                 card.update({'systemname':systemname})
  75.         namesettingdict[systemname] = {}
  76.         namesettingdict[systemname]['systemname'] = hwid
  77.         namesettingdict[systemname]['vendorname'] = busvendordict[hwid]
  78.         netcard = {'systemname': hwid, 'vendorname':busvendordict[hwid]}
  79.  
  80.     stdin,stdout,stderr = client.exec_command('cat /proc/net/route')
  81.     routestings = stdout.readlines()
  82.     for mystr in routestings:
  83.         st = mystr.split('\t')
  84.         if ((st[2] ==  '00000000') and (st[7] !=  'FFFFFFFF') and (st[1] != '0000FEA9')):
  85.             IPnetwork = '.'.join([str(int(st[1][i-2:i], 16)) for i in reversed(range(2,10,2))])
  86.             IPnetmask = '.'.join([str(int(st[7][i-2:i], 16)) for i in reversed(range(2,10,2))])
  87.             IPnetmaskhex = ''.join([st[7][i-2:i] for i in reversed(range(2,10,2))])
  88.             IPnetmaskshortform = bin(int(IPnetmaskhex,16)).count("1")
  89.             logicalinterfacename = st[0]
  90.             for netcard in netcardlist:
  91.                 if re.match('{0}.*'.format(netcard['systemname']), logicalinterfacename):
  92.                     if not netcard.has_key('logicalname'):
  93.                         netcard.update({'logicalname': list()})
  94.                     netcard['logicalname'].append({'name':logicalinterfacename, 'IPv4':'0.0.0.0', 'IPnetwork':IPnetwork, 'IPnetmask':IPnetmask, 'IPnetmaskshortform': IPnetmaskshortform})
  95.                        
  96.     stdin,stdout,stderr = client.exec_command('cat /proc/net/fib_trie')
  97.     fib_trie_result  = stdout.readlines()
  98.     if (len(fib_trie_result) == 0):
  99.         print( "No information about IPs !")
  100.         return netcardlist
  101.     for pos, mystr in enumerate(fib_trie_result):
  102.         if re.match( r'(.*)host(.*)', mystr):
  103.             localIP = re.search('(?P<IP>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})', fib_trie_result[pos-1])
  104.             if localIP is  None:
  105.                 pass
  106.             Network = re.search('(?P<Network>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})/(?P<Netmask>\d{1,2})', fib_trie_result[pos-5])
  107.             if Network is not None:
  108.                 for netcard in netcardlist:
  109.                     try:
  110.                         if not 'logicalname' in  netcard:
  111.                                 continue
  112.                         for linterface in  netcard['logicalname']:
  113.                             logicalinterface = linterface['name']
  114.                             if (int(Network.group('Netmask')) == linterface['IPnetmaskshortform']) and (Network.group('Network')==linterface['IPnetwork']):
  115.                                 linterface['IPv4'] = localIP.group('IP')
  116.  
  117.                     except:
  118.  
  119.                         print ("Exception netcard structure : {0}   1: {1}".format(netcard, netcard[1]))        
  120.  
  121.     return  netcardlist
  122.  
  123. def main():
  124.     """ main function for scanning hardware using ssh connection"""
  125.     sshkeyfile, hostlist = scanparams()
  126.     for hostname in hostlist:
  127.         print("="*50)
  128.         print("trying to get information from host: {0}".format(hostname))
  129.         print("="*50)
  130.         client = paramiko.SSHClient()
  131.         client.load_system_host_keys()
  132.         client.load_host_keys(sshkeyfile)
  133.         client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  134.         client.connect(hostname, username='root')
  135.         print("*"*50)
  136.         print("Hostname:{0}".format(detecthostname(client)))
  137.         cpuname, cpucount = detectcpu(client)
  138.         print ("*"*20+"CPU information"+"*"*20)
  139.         print("CPUCount: {0}\n CPU  model: {1}".format(cpucount, cpuname))
  140.         print("*"*30+"Memory information"+"*"*20)
  141.         print(("Momory size in kb: {0}\n"+"="*30).format(detectmemory(client)))
  142.         print("*"*20+"Netcard's information'"+"*"*20)
  143.         netcardlist = detectnetworkcards(client)
  144.         drives = detectdrives(client)
  145.         print("{0}\n {1}\n {0}".format("#"*50, netcardlist))
  146.        
  147.         print("*"*20+"Drives information"+"*"*20)
  148.         for drive in drives:
  149.             print("Drive system name:/dev/{0}\nDrive vendor:{1}\nDrive size: {2} MB".format(drive, drives[drive]['model'], drives[drive]['size']))
  150.         client.close()
  151. if __name__=="__main__":
  152.     main()
Advertisement
Add Comment
Please, Sign In to add comment