Solução para pegar o Serial do HD e o Serial da CPU

23 respostas
H

Uma obeservação importante é que, se você quer utilizar para colocar travas em softwares este é o número que você vai precisar, pois o que tenho visto por aí é o pessoal pesquisando por "Número do Volume do HD" que muda quando é criado um novo volume tipo "Unidade D:", mas o Serial do HD, este não muda, assim pode ser usado para qualquer fim.
Não achei nenhuma solução no fórum e as que achei eram complicadas e pagas, por isto estou postando aqui. Este foi pego no fórum da Sun em Inglês.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;


public class Teste {

	public static String getHDSerial(String drive) {
        String result = "";
        try {
            //File file = File.createTempFile("tmp",".vbs");
            File file = File.createTempFile("tmp", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new java.io.FileWriter(file);
 
            String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n" + "Set colDrives = objFSO.Drives\n" 
                            + "Set objDrive = colDrives.item(\"" + drive + "\")\n" + "Wscript.Echo objDrive.SerialNumber";  
            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input =
                new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
 
        }
        if (result.trim().length() < 1  || result == null) {
            result = "NO_DISK_ID";
 
        }
 
        return result.trim();
    }
 
    public static String getCPUSerial() {
        String result = "";
        try {
            File file = File.createTempFile("tmp", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new java.io.FileWriter(file);
 
            String vbs =
                "On Error Resume Next \r\n\r\n" +
                "strComputer = \".\"  \r\n" +
                "Set objWMIService = GetObject(\"winmgmts:\" _ \r\n" +
                "    & \"{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\") \r\n" +
                "Set colItems = objWMIService.ExecQuery(\"Select * from Win32_Processor\")  \r\n " +
                "For Each objItem in colItems\r\n " +
                "    Wscript.Echo objItem.ProcessorId  \r\n " +
                "    exit for  ' do the first cpu only! \r\n" +
                "Next                    ";
 
 
            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input =
                new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
 
        }
        if (result.trim().length() < 1 || result == null) {
            result = "NO_CPU_ID";
        }
        return result.trim();
    }

	public static void main(String[] args) {
		System.out.println("Serial do HD: " + getHDSerial("c"));
		System.out.println("Serial da CPU: " + getCPUSerial());
	}

}

Atenciosamente,
Leonardo A. Santos

23 Respostas

D

Muito obrigado eu estava procurando isto .
Vc conhece alguma forma de pegar a capacidade e o
nome do processador???

E

Show de bola, já coloquei na minha coleção de códigos, rsrsrs

Pena que pelo jeito apenas funcione com Windows.

T

Para pegar o número de série do HD no Linux é relativamente fácil - execute isto em uma linha de comando:

lshw -xml -class disk | grep serial

Deve aparecer uma linha para cada HD.
O usuário deve ser administrador, senão não consegue obter a informação do número de série do HD.

Se houver 2 discos, devem aparecer 2 linhas. Por exemplo, em uma máquina com 2 discos de marcas diferentes (o primeiro Seagate e o segundo Western Digital), foi mostrado:

<serial>3KB3GL7X</serial>
   <serial>WD-WMAJ2209998</serial>
H

Aeh galera, quando se usar o linux usar-se-á o cmd do linux para descobrir... aí é só encaixar o código neste que listarei abaixo e o programa reconhecerá entre os dois sistemas e executará o código previsto para cada um:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;


public class teste2 {

    private final static String getHDSerial() throws IOException {
        String os = System.getProperty("os.name");

        try {
            if(os.startsWith("Windows")) {
                return getHDSerialWindows("C");
            // } else if(os.startsWith("Linux")) {
            //    return getHDSerialLinux("D");
            } else {
                throw new IOException("unknown operating system: " + os);
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            throw new IOException(ex.getMessage());
        }
    }

    public static String getHDSerialWindows(String drive) {
        String result = "";
        try {
            //File file = File.createTempFile("tmp",".vbs");
            File file = File.createTempFile("tmp", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new java.io.FileWriter(file);
 
            String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n" + "Set colDrives = objFSO.Drives\n" 
                            + "Set objDrive = colDrives.item(\"" + drive + "\")\n" + "Wscript.Echo objDrive.SerialNumber";  
            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
 
        }
        if (result.trim().length() < 1  || result == null) {
            result = "NO_DISK_ID";
 
        }
 
        return result.trim();
    }
    
    // public static String getHDSerialLinux(String drive) {
    	// Código Aqui!!
    // }
    
	public static void main(String[] args) {
		try {
			System.out.println("Serial HD: " + getHDSerial());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
E

Pelo que vi, neste código é criado um arquivo temporário com instruções em vb scrip, em seguida é feita uma chamada de execução deste script e capturado o echo de saída dele…É isso?
Se for, taí uma coisa que não tinha idéia de que Java poderia fazer…

H

é exatamente isto…

R

Cara, mto bom. Vou testar isso aí.

S

Ele pega um número serial…

Mas pegou o msm numero em 2 maquinas…
:confused:

Tentei o número serial do cpu…
O serial do hd ele me retorna um número negativo… mas pra mim só serviria o serial do cpu msm…

Alguém sabe qual o problema?

L

interesante ele usa um vb script para fazer isto… em jav é impossivel mas em vb não… ja tive que usar java + vbscript uma vez… vbscript é show de bola… e o bom e que vc tem uma interface nativa com o hardware sem precisar de JNI… ou algo parecido…

T

A Intel deixou de incluir um número serial nas suas CPUs (que seja acessível por default) faz bastante tempo.
Depois que a processaram por possibilitar a invasão de privacidade, ela solicita a todos os fabricantes de computadores que não usem o tal recurso (embora ele ainda exista). Esse recurso não pode ser mais habilitado na BIOS.

G

pode se fazer isso sem usar scripts nem nada

veja esse exemplo que eu estudei um tempo atras

package br.com.bb.sisbbconnector.connection;

import java.text.DecimalFormat;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 * Example VB script that grabs hard drive properties.
 * <p>
 * Source Forge posting
 * http://sourceforge.net/forum/forum.php?thread_id=1785936&forum_id=375946
 * <p>
 * Enhance by clay_shooter with info from
 * http://msdn2.microsoft.com/en-us/library/d6dw7aeh.aspx
 * 
 * @author qstephenson
 * 
 */
public class DiskUtils {

	/** formatters aren't thread safe but the sample only has one thread */
	private static DecimalFormat sizeFormatter = new DecimalFormat("###,###,###,###");

	/** a pointer to the scripting file system object */
	private ActiveXComponent fileSystemApp = null;

	/** the dispatch that points at the drive this DiskUtil operates against */
	private Dispatch myDrive = null;

	/**
	 * Standard constructor
	 * 
	 * @param drive
	 *            the drive to run the test against.
	 */
	public DiskUtils(String drive) {
		setUp(drive);
	}

	/**
	 * open the connection to the scripting object
	 * 
	 * @param drive
	 *            the drive to run the test against
	 */
	public void setUp(String drive) {
		if (fileSystemApp == null) {
			ComThread.InitSTA();
			fileSystemApp = new ActiveXComponent("Scripting.FileSystemObject");
			myDrive = Dispatch.call(fileSystemApp, "GetDrive", drive)
					.toDispatch();
		}
	}

	/**
	 * Do any needed cleanup
	 */
	public void tearDown() {
		ComThread.Release();
	}

	/**
	 * convenience method
	 * 
	 * @return driver serial number
	 */
	public int getSerialNumber() {
		return Dispatch.get(myDrive, "SerialNumber").getInt();
	}

	/**
	 * Convenience method. We go through these formatting hoops so we can make
	 * the size string pretty. We wouldn't have to do that if we didn't mind
	 * long strings with Exxx at the end or the fact that the value returned can
	 * vary in size based on the size of the disk.
	 * 
	 * @return driver total size of the disk
	 */
	public String getTotalSize() {
		Variant returnValue = Dispatch.get(myDrive, "TotalSize");
		if (returnValue.getvt() == Variant.VariantDouble) {
			return sizeFormatter.format(returnValue.getDouble());
		} else if (returnValue.getvt() == Variant.VariantInt) {
			return sizeFormatter.format(returnValue.getInt());
		} else {
			return "Don't know type: " + returnValue.getvt();
		}
	}

	/**
	 * Convenience method. We wouldn't have to do that if we didn't mind long
	 * strings with Exxx at the end or the fact that the value returned can vary
	 * in size based on the size of the disk.
	 * 
	 * @return driver free size of the disk
	 */
	public String getFreeSpace() {
		Variant returnValue = Dispatch.get(myDrive, "FreeSpace");
		if (returnValue.getvt() == Variant.VariantDouble) {
			return sizeFormatter.format(returnValue.getDouble());
		} else if (returnValue.getvt() == Variant.VariantInt) {
			return sizeFormatter.format(returnValue.getInt());
		} else {
			return "Don't know type: " + returnValue.getvt();
		}
	}

	/**
	 * 
	 * @return file system on the drive
	 */
	public String getFileSystemType() {
		// figure ot the actual variant type
		// Variant returnValue = Dispatch.get(myDrive, "FileSystem");
		// System.out.println(returnValue.getvt());
		return Dispatch.get(myDrive, "FileSystem").getString();
	}

	/**
	 * 
	 * @return volume name
	 */
	public String getVolumeName() {
		return Dispatch.get(myDrive, "VolumeName").getString();
	}

	/**
	 * Simple main program that creates a DiskUtils object and queries for the
	 * C: drive
	 * 
	 * @param args
	 *            standard command line arguments
	 */
	public static void main(String[] args) {
		// DiskUtils utilConnection = new DiskUtils("F");
		DiskUtils utilConnection = new DiskUtils("C");
		System.out.println("Disk serial number is: "
				+ utilConnection.getSerialNumber());
		System.out.println("FileSystem is: "
				+ utilConnection.getFileSystemType());
		System.out.println("Volume Name is: " + utilConnection.getVolumeName());
		System.out.println("Disk total size is: "
				+ utilConnection.getTotalSize());
		System.out.println("Disk free space is: "
				+ utilConnection.getFreeSpace());
		utilConnection.tearDown();
	}
}

é soh baixar o pacote JACOB e ser feliz...
ele controla qualquer componete active do windows com extrema facilidade

esse pacote nada mais é que uma implementacao de JNI

R

gobbo, sua solução com a jacob é show, soh que para windows neh!!!

Existe alguma biblioteca similar a essa para Linux??

G

ola root_
pelo que eu me lembre (ja faz muito tempo xD) a biblioteca Jacob consegue ler .so
Caso contrario, trabalhei com outras (Jenie, JNA…)

R

Sim… mais a questão é saber qual .SO se utilizar?

R

Boa noite pessoal!

Eu fiz testes com os dois modos de pegar o serial do HD aqui citados, e ambos me retornam um número negativo, não é isso né? O que pode estar errado?

Muito obrigado desde já!

P

Pessoal , eu to precisando colcocar este aplicativo pra rodar no browser…estou fazendo um sistema para uso via internet e gostaria de autenticar o usuario , checando a serial do HD. Mas vou lhes dizer, ta dificil de achar a ferramenta certa…

Será que este daria certo? ou vcs tem alguma outra sugestão?

desde ja agradeço a colaboração!

sds

Paulo Wassolowski

B

Caro heiligerstein,

Esta solução realmente funciona. Como aplicativo. Estou tentando fazer um applet seguindo a mesma ideia. consegui fazela imprimir dentro da pagina html os resultados porem a resposta é NO_DISK_ID e NO_CPU_ID. anterior mente vinha tentando uma solução pra pegar o serial que era em javascript e usava vbs tb mas ocorria o seguinte erro “servidor nao pode criar o objeto” esse erro era justamente na parte que usa “scripting.FSO” e agora com a sua solução consigo fazer imprimir mas o resultado no é prenchido acredito que o problema seja o mesmo com o “FyleSystemOobject”. Isso tudo porque estou tentando fazer com queno site, ao usuario acessar o site e fazer o login seja feito um controle por identificação da maquina. Se puder me dar alguma ideia ou mesmo me ajudar a terminar o serviço agradeço, ok.

Vou deixar aqui o arquivo que gerou o applet

############################################

// Java Document

import java.applet.Applet;

import java.awt.*;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileWriter;

import java.io.InputStreamReader;
public class AppletValida extends Applet {

public void init() {}

public static String getHDSerial(String drive) {

String result = oi;

try {

//File file = File.createTempFile(tmp,".vbs");

File file = File.createTempFile(tmp, .vbs);

file.deleteOnExit();

FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n" + "Set colDrives = objFSO.Drives\n"   
                         + "Set objDrive = colDrives.item(\"c\")\n" + "Wscript.Echo objDrive.SerialNumber";    
         fw.write(vbs);  
         fw.close();  
         Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());  
         BufferedReader input =  
             new BufferedReader(new InputStreamReader(p.getInputStream()));  
         String line;  
         while ((line = input.readLine()) != null) {  
             result += line;  
         }  
         input.close();  
     } catch (Exception e) {  

     }  
     if (result.trim().length() < 5  || result == null) {  
         result = "NO_DISK_ID";  

     }  

     return result.trim();  
 }
//cpu

public static String getCPUSerial() {

String result = resultado;

try {

File file = File.createTempFile(tmp, .vbs);

file.deleteOnExit();

FileWriter fw = new java.io.FileWriter(file);
String vbs =  
             "On Error Resume Next \r\n\r\n" +  
             "strComputer = \".\"  \r\n" +  
             "Set objWMIService = GetObject(\"winmgmts:\" _ \r\n" +  
             "    & \"{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\") \r\n" +  
             "Set colItems = objWMIService.ExecQuery(\"Select * from Win32_Processor\")  \r\n " +  
             "For Each objItem in colItems\r\n " +  
             "    Wscript.Echo objItem.ProcessorId  \r\n " +  
             "    exit for  ' do the first cpu only! \r\n" +  
             "Next                    ";  


         fw.write(vbs);  
         fw.close();  
         Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());  
         BufferedReader input =  
             new BufferedReader(new InputStreamReader(p.getInputStream()));  
         String line;  
         while ((line = input.readLine()) != null) {  
             result += line;  
         }  
         input.close();  
     } catch (Exception e) {  

     }  
     if (result.trim().length() < 1 || result == null) {  
         result = "NO_CPU_ID";  
     }  
     return result.trim();  
 }
//impressao

public void paint(Graphics g) {

String teste = testeipm string;

g.drawString(Este é o Serial do seu HDD " + getHDSerial(“c”) + " :::fimmmmmm, 5, 25);

g.drawString(Meu primeiro Aplicativo em Java::: " + getCPUSerial() + " :::fimmmmmm, 5, 45);

}

}

##################################################

e este é a chamada que vai no html

#############################################

Meu Java Applet Informa:


############################

Se estiver falando bobagem, desculpe-me, pois sou iniciante no assunto…

C

rodrigoran:
Boa noite pessoal!

Eu fiz testes com os dois modos de pegar o serial do HD aqui citados, e ambos me retornam um número negativo, não é isso né? O que pode estar errado?

Muito obrigado desde já!

[size=20][color=darkblue]TBM quero saber se é isso mesmo[/color][/size]

T

Testei e funcinou perfeitamente, cheguei a comparar o restultado com um executável que fiz em Delphi para isso há algum tempo e o valor número é o mesmo, a diferença é que no que fiz em Delphi ele retorna em Exadecimal, neste ele retorna em Decimal.

Muito obrigapo por compartilhar, me ajudou muito!

Abraços!

S

Também testei e tive como retorno um número negativo, alguém sabe explicar se está correto?

D

Tb tive retorno de número negativo, oque fiz foi converter para Hexa, me trouxe o valor certinho do volume do hd

DiskUtils utilConnection = new DiskUtils("C");       
    int valor = utilConnection.getSerialNumber();
    String serial =  Integer.toHexString(valor);
E

Para aqueles que como eu pegaram um retorno errado no serial do HD

public static String getHDSerial(String drive) {  
        String result = "";  
        try {  
            File file = File.createTempFile("tmp", ".vbs");  
            file.deleteOnExit();  
            FileWriter fw = new java.io.FileWriter(file);  
  
            String vbs = "strComputer = \".\"\n"+
					"Set objWMIService = GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\")\n"+
					"str = \"\"\n"+
					"disk = \"" + drive.toUpperCase() + ":\"\n"+
					"Set colItems = objWMIService.ExecQuery(\"SELECT * FROM Win32_LogicalDisk\")\n"+
					"For Each objItem In colItems\n"+
					   "If objItem.Name = disk Then\n"+
					       "Wscript.Echo objItem.VolumeSerialNumber\n"+
					   "End If\n"+
					"Next"; 
            fw.write(vbs);  
            fw.close();  
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());  
            BufferedReader input =  
                new BufferedReader(new InputStreamReader(p.getInputStream()));  
            String line;  
            while ((line = input.readLine()) != null) {  
                result += line;  
            }  
            input.close();  
        } catch (Exception e) {  
  
        }  
        if (result.trim().length() < 1  || result == null) {  
            result = "NO_DISK_ID";  
  
        }  
  
        return result.trim();  
    }

isto é para windows, gostaria de ver isto multiplataforma…
Who can do it???

T

Sei que o Post e antigo mas pode ajudar alguém,
eu tinha esse metodo no meu projeto mas ele demorar muito pra retornar o id do processador então criei este que e mais rápido.
ele gasta em torno de 100 milesimos enquanto da outra forma gasta mais de 1000

try {
            Process pid = Runtime.getRuntime().exec("wmic cpu get processorId");
            BufferedReader in = new BufferedReader(new InputStreamReader(pid.getInputStream()));
            String line = "";
            while (in.read() > 0) {
                line += in.readLine();
            }
            line = line.substring(line.indexOf(" "), line.length());
            line =line.replaceAll(" ", "");
            System.out.println(line);
        } catch (IOException ex) {
            Logger.getLogger(LacamentoContasControler.class.getName()).log(Level.SEVERE, null, ex);
        }
Criado 18 de maio de 2008
Ultima resposta 4 de ago. de 2014
Respostas 23
Participantes 19