daily pastebin goal
10%
SHARE
TWEET

scanhardware

sergkh Jan 26th, 2018 16 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
  40. def detectmb(client):
  41.     """ Detect mother borad model and vendor"""        
  42.     stdin,stdout,stderr = client.exec_command('cat /sys/devices/virtual/dmi/id/board_*')
  43.     mblist = stdout.readlines()
  44.     if len(mblist)>1:
  45.         mbmodel, mbvendor = mblist[1].rstrip(), mblist[3].rstrip()
  46.     else:
  47.         mbmodel=mbvendor="Not detected"
  48.     return mbmodel,mbvendor
  49.    
  50. def detectdrives(client):
  51.     """ """
  52.     stdin,stdout,stderr = client.exec_command('ls /sys/block')
  53.     devicelist = stdout.readlines()
  54.     localdrivelist = []
  55.     drives = {}
  56.     for localdrive  in devicelist:
  57.         m = re.search('(?P<drivename>h|sd.)',localdrive)
  58.         if m  is not None:
  59.             localdrivelist.append(m.group('drivename'))
  60.     for selecteddrive in localdrivelist:
  61.         drives[selecteddrive] = {}          
  62.         stdin,stdout,stderr = client.exec_command('cat /sys/class/block/{0}/device/model'.format(selecteddrive))
  63.         drives[selecteddrive]['model'] = stdout.readlines()[0].rstrip()
  64.         stdin,stdout,stderr = client.exec_command('cat /sys/block/{0}/size'.format(selecteddrive))
  65.         drivesize = int(stdout.readlines()[0])/2028
  66.         drives[selecteddrive]['size'] = drivesize
  67.     return drives
  68. def detectnetworkcards(client):
  69.     """ detect netcar procedure"""
  70.     busvendordict = {}
  71.     namesettingdict = {}
  72.     netcardlist = []
  73.     stdin,stdout,stderr = client.exec_command("lspci")
  74.     etherlist= stdout.readlines()
  75.     for mystr in etherlist:
  76.         m = re.search('(?P<hwid>^[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-9a-fA-F]) Ethernet controller: (?P<vendorname>.*)', mystr)
  77.         if m is not None:
  78.             busvendordict[m.group('hwid')] = m.group('vendorname')
  79.             netcardlist.append({'hardwareid':m.group('hwid'),'vendorname':m.group('vendorname')})
  80.     for hwid in busvendordict:
  81.         stdin,stdout,stderr = client.exec_command('ls /sys/bus/pci/devices/0000\:{0}/net/'.format(hwid))
  82.         systemname = stdout.readlines()[0].rstrip()
  83.         for card in netcardlist:
  84.             if card['hardwareid'] == hwid:
  85.                 card.update({'systemname':systemname})
  86.         namesettingdict[systemname] = {}
  87.         namesettingdict[systemname]['systemname'] = hwid
  88.         namesettingdict[systemname]['vendorname'] = busvendordict[hwid]
  89.         netcard = {'systemname': hwid, 'vendorname':busvendordict[hwid]}
  90.  
  91.     stdin,stdout,stderr = client.exec_command('cat /proc/net/route')
  92.     routestings = stdout.readlines()
  93.     for mystr in routestings:
  94.         st = mystr.split('\t')
  95.         if ((st[2] ==  '00000000') and (st[7] !=  'FFFFFFFF') and (st[1] != '0000FEA9')):
  96.             IPnetwork = '.'.join([str(int(st[1][i-2:i], 16)) for i in reversed(range(2,10,2))])
  97.             IPnetmask = '.'.join([str(int(st[7][i-2:i], 16)) for i in reversed(range(2,10,2))])
  98.             IPnetmaskhex = ''.join([st[7][i-2:i] for i in reversed(range(2,10,2))])
  99.             IPnetmaskshortform = bin(int(IPnetmaskhex,16)).count("1")
  100.             logicalinterfacename = st[0]
  101.             for netcard in netcardlist:
  102.                 if re.match('{0}.*'.format(netcard['systemname']), logicalinterfacename):
  103.                     if not netcard.has_key('logicalname'):
  104.                         netcard.update({'logicalname': list()})
  105.                     netcard['logicalname'].append({'name':logicalinterfacename, 'IPv4':'0.0.0.0', 'IPnetwork':IPnetwork, 'IPnetmask':IPnetmask, 'IPnetmaskshortform': IPnetmaskshortform})
  106.                        
  107.     stdin,stdout,stderr = client.exec_command('cat /proc/net/fib_trie')
  108.     fib_trie_result  = stdout.readlines()
  109.     if (len(fib_trie_result) == 0):
  110.         print( "No information about IPs !")
  111.         return netcardlist
  112.     for pos, mystr in enumerate(fib_trie_result):
  113.         if re.match( r'(.*)host(.*)', mystr):
  114.             localIP = re.search('(?P<IP>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})', fib_trie_result[pos-1])
  115.             if localIP is  None:
  116.                 pass
  117.             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])
  118.             if Network is not None:
  119.                 for netcard in netcardlist:
  120.                     try:
  121.                         if not 'logicalname' in  netcard:
  122.                                 continue
  123.                         for linterface in  netcard['logicalname']:
  124.                             logicalinterface = linterface['name']
  125.                             if (int(Network.group('Netmask')) == linterface['IPnetmaskshortform']) and (Network.group('Network')==linterface['IPnetwork']):
  126.                                 linterface['IPv4'] = localIP.group('IP')
  127.  
  128.                     except:
  129.  
  130.                         print ("Exception netcard structure : {0}   1: {1}".format(netcard, netcard[1]))        
  131.  
  132.     return  netcardlist
  133. def main():
  134.     """ main function for scanning hardware using ssh connection"""
  135.     sshkeyfile, hostlist = scanparams()
  136.     for hostname in hostlist:
  137.         print("="*50)
  138.         print("trying to get information from host: {0}".format(hostname))
  139.         print("="*50)
  140.         client = paramiko.SSHClient()
  141.         client.load_system_host_keys()
  142.         client.load_host_keys(sshkeyfile)
  143.         client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  144.         client.connect(hostname, username='root')
  145.         print("*"*50)
  146.         print("Hostname:{0}".format(detecthostname(client)))
  147.         cpuname, cpucount = detectcpu(client)
  148.         print ("*"*20+"CPU information"+"*"*20)
  149.         print("CPUCount: {0}\n CPU  model: {1}".format(cpucount, cpuname))
  150.         print("*"*30+"Memory information"+"*"*20)
  151.         print(("Memory size in kb: {0}\n"+"="*30).format(detectmemory(client)))
  152.         mbmodel,mbvendor = detectmb(client)
  153.         print("{0}\n MB vendor : {1}\n MB model: {2}\n {0}".format("*"*50, mbvendor, mbmodel))
  154.         print("*"*20+"Netcard's information'"+"*"*20)
  155.         netcardlist = detectnetworkcards(client)
  156.         drives = detectdrives(client)
  157.         print("{0}\n {1}\n {0}".format("#"*50, netcardlist))
  158.        
  159.         print("*"*20+"Drives information"+"*"*20)
  160.         for drive in drives:
  161.             print("Drive system name:/dev/{0}\nDrive vendor:{1}\nDrive size: {2} MB".format(drive, drives[drive]['model'], drives[drive]['size']))
  162.         client.close()
  163. if __name__=="__main__":
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top