Pegar informações do PC com Java (Serial processador, hd, placa mãe)

3,279 views
Skip to first unread message

Rafaell Pinheiro

unread,
Jan 8, 2009, 7:06:09 AM1/8/09
to pb...@googlegroups.com
Olá pessoal, bom dia!

Estou pesquisando possibilidades em Java para capturar informações da máquina, como serial do processador, serial do hd e placa mãe.Só tenho encontrado opções que escrevem trechos VisualBasic e o executam, porém quero um solução puramente JAVA, pois preciso de um código que funcione também no linux.

Vcs já viram algo do tipo? Baixei um pacote, chamado JACOB mas os resultados não foram satisfatórios.

Grato,

--
Rafaell Pinheiro Sousa

Herval Freire

unread,
Jan 8, 2009, 7:39:28 AM1/8/09
to pb...@googlegroups.com
Voce nao vai encontrar solucoes puramente Java. Ou você usa JNI, ou alguma linguagem na VM que implemente acesso a hardware (JRuby, talvez).

[]s


2009/1/8 Rafaell Pinheiro <rafa...@gmail.com>

Eduardo Colaço

unread,
Jan 13, 2009, 5:21:04 PM1/13/09
to pb...@googlegroups.com
Off-topic bem on-toppic. Trabalhei num projeto que precisava do serial do hd ou algo do tipo, e encontramos um post com a "solução".

"Don't listen to these fools, of course you can!"

http://forums.sun.com/thread.jspa?forumID=31&threadID=683640

2009/1/8 Herval Freire <herval...@gmail.com>

Rafaell Pinheiro

unread,
Jan 13, 2009, 8:13:23 PM1/13/09
to pb...@googlegroups.com

Opa, valeu cumpade :)
2009/1/13 Eduardo Colaço <eduar...@gmail.com>



--
Rafaell Pinheiro Sousa

Herval Freire

unread,
Jan 14, 2009, 2:51:09 AM1/14/09
to pb...@googlegroups.com
Eduardo,

Sinto muito informar, mas o codigo do seu exemplo utiliza chamadas de VB para pegar a identificacao do HD. Ele depende inclusive da app estar rodando no windows (Exatamente como o Rafael falou inicialmente).

http://technet.microsoft.com/en-us/library/bb490887.aspx

Ler a thread as vezes ajuda...

[]s
Herval

2009/1/14 Rafaell Pinheiro <rafa...@gmail.com>

Erick Moreno

unread,
Jan 14, 2009, 6:16:47 AM1/14/09
to pb...@googlegroups.com
Ninguém leu o off topic no e-mail de Eduardo nem entendeu a piada da Lessie?

Sinto muito informar, Herval, mas essa era uma thread engraçada.

[]'s
Erick Moreno

2009/1/14 Herval Freire <herval...@gmail.com>

Luiz Augusto B. Florentino Filho

unread,
Jan 14, 2009, 6:54:04 AM1/14/09
to pb...@googlegroups.com
Rafael, para resolver o problema, você poderia utilizar o
Runtime.getRuntime().exec() para executar um comando.

Inicialmente você verifica qual o sistema operacional que está sendo
utilizado. Em seguida executa algum comando do shell. Esse comando
pode ser um script .bat ou um shell script do linux mesmo.

A solução não é lá a das melhores, mas pelo tempo que você esteve
pesquisando acho que vale a pena tentar.

Segue em anexo um exemplo de um código que utiliza o comando "vol" do
Windows para recuperar o serial de um HD. Meio gambiarra, mas serve
como exemplo.


2009/1/14 Erick Moreno <erick...@gmail.com>:
Main.java

Rafaell Pinheiro

unread,
Jan 14, 2009, 6:55:47 AM1/14/09
to pb...@googlegroups.com

Joia. Para linux so vi soluçõe baseadas em scripts para shell mesmo, deve então ser a unica alternativa. Gostei do exemplo, obrigado!

abs

Rafaell

2009/1/14 Luiz Augusto B. Florentino Filho <luizflo...@gmail.com>



--
Rafaell Pinheiro Sousa

Thiago D. Freitas

unread,
Jan 14, 2009, 7:03:04 AM1/14/09
to pb...@googlegroups.com
lassie.haveABiscuit();

:)


2009/1/14 Luiz Augusto B. Florentino Filho <luizflo...@gmail.com>
Rafael, para resolver o problema, você poderia utilizar o

Herval Freire

unread,
Jan 14, 2009, 7:36:55 AM1/14/09
to pb...@googlegroups.com
Ainda bem que voces nao sao humoristas... ;-)


2009/1/14 Erick Moreno <erick...@gmail.com>

Marcelo Zurita

unread,
Jan 14, 2009, 7:48:14 AM1/14/09
to pb...@googlegroups.com
O interessante foi a resposta do cara:

hi,

it gives the error package javax.haXXerZ..* does not exist.
plz help me how can I solve this problem.


Ele tentou compilar o programa da Lessie!!!!


2009/1/14 Herval Freire <herval...@gmail.com>



--

Atenciosamente,

Marcelo Zurita
mzu...@cnnt.com.br
83 9926 1152

--------------------------------------
Connect Soluções Integradas
Ed. Maximum Shopping Empresarial
Av. Juarez Távora, 522, sala 716
Torre - João Pessoa - Paraíba
www.cnnt.com.br
83 3243 0931

Rafaell Pinheiro

unread,
Jan 23, 2009, 12:00:36 PM1/23/09
to pb...@googlegroups.com
Ai pessoal, depois de muita consulta consegui fazer uma classe, com metodos especificos para windows e linux.

Quem precisar eh so aproveitar.

/*
 * Autor: Rafaell Pinheiro Sousa
 * contato: rafa...@gmail.com
 * criado em : 23/01/2009
 */


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class SerialUtils {

    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();
            } else {
                throw new IOException("unknown operating system: " + os);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new IOException(ex.getMessage());
        }
    }

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

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

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

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

    // Implementacoes
   
    /*
     * Captura serial de placa mae no WINDOWS, atraves da execucao de script visual basic
     */
    public static String getMotherboardSerialWindows() {
        String result = "";
        try {
            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new java.io.FileWriter(file);

            String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                    + "Set colItems = objWMIService.ExecQuery _ \n"
                    + "   (\"Select * from Win32_BaseBoard\") \n"
                    + "For Each objItem in colItems \n"
                    + "    Wscript.Echo objItem.SerialNumber \n"
                    + "    exit for  ' do the first cpu only! \n" + "Next \n";

            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) {
            e.printStackTrace();
        }
        return result.trim();
    }
   
   
    /*
     * Captura serial de placa mae em sistemas LINUX, atraves da execucao de comandos em shell.
     */
    public static String getMotherboardSerialLinux() {
        String result = "";
        try {
            String[] args = {"bash", "-c", "lshw -class bus | grep serial"};
            Process p = Runtime.getRuntime().exec(args);
            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 filtraString(result, "serial: ");
       
    }

    /*
     * Captura serial de HD no WINDOWS, atraves da execucao de script visual basic
     */
    public static String getHDSerialWindows(String drive) {
        String result = "";
        try {
            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();
    }

    /*
     * Captura serial de HD em sistemas Linux, atraves da execucao de comandos em shell.
     */
    public static String getHDSerialLinux() {
        String result = "";
        try {
            String[] args = {"bash", "-c", "lshw -class disk | grep serial"};
            Process p = Runtime.getRuntime().exec(args);
            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 filtraString(result, "serial: ");
       
    }
   
    /*
     * Captura serial da CPU no WINDOWS, atraves da execucao de script visual basic
     */
    public static String getCPUSerialWindows() {
        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();
    }

    /*
     * Captura serial de CPU em sistemas Linux, atraves da execucao de comandos em shell.
     */
    public static String getCPUSerialLinux() {
        String result = "";
        try {
            String[] args = {"bash", "-c", "lshw -class processor | grep serial"};
            Process p = Runtime.getRuntime().exec(args);
            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 filtraString(result, "serial: ");
    }
   
   
    public static String filtraString(String nome, String delimitador){
        return nome.split(delimitador)[1];
    }
   
    public static void main(String[] args) {
        try {
            System.out.println("Serial do HD: " + getHDSerial());
            System.out.println("Serial da CPU: " + getCPUSerial());
            System.out.println("Serial da Placa Mae: " + getMotherboardSerial());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

2009/1/14 Marcelo Zurita <mzu...@cnnt.com.br>



--
Rafaell Pinheiro Sousa

Emmanuel Alves

unread,
Jan 23, 2009, 12:17:26 PM1/23/09
to pb...@googlegroups.com
Rafaell,

Eu implementei também recentemente uma função para captura destas informações, mas no meu caso o sistema é Web e precisei utilizar applets assinados digitalmente, para que seja possível a execução.

Alguns pontos que você deve considerar em relação ao ID do processador e da placa mãe. Vi muitas mensagens de usuários em fóruns, inclusive na documentação oficial da microsoft.

O ProssessorId pode não ser único. Em alguns casos, diferentes máquinas possuíram códigos iguais que já torna falha esta propriedade.

Mesma coisa do serial da placa mãe. Em alguns casos, o "serial number" não é preenchido por sua fabricante, retornando uma mensagem do tipo "To be filled by O.E.M.", portanto, falho também.

O que achei de solução foi a utilização de mais de um dos "códigos", gerando um hash md5 da união dos dois. No meu caso, eu utilizei o ID do processador (por ser quase raro se repetir) e o MAC Address da placa de rede.

[]s

Emmanuel Alves
mane...@gmail.com

Rafaell Pinheiro

unread,
Jan 23, 2009, 2:04:58 PM1/23/09
to pb...@googlegroups.com
Joia Emmanuel,
 
Se eu for usar pra web, com certeza a saída será com applet. Legal saber em relação da repetição dos dados, ou seja, na falha em se autenticar por alguns dados do pc. Mas da mesma forma que vc está fazendo, o uso é feito em conjunto, calculando um hash dos tres parametros, por exemplo. Como é combinação, pra gerar um resumo, no caso o hash, eu insisti no projeto que o uso do MAC conjugado com outros parametros, seria interessante, mas o pessoal nao aceitou o argumento.
 
Sua solução com aplets, vc usou JNI ou chamadas de shell e vbscript?
 
Abs
 
Rafaell

2009/1/23 Emmanuel Alves <mane...@gmail.com>

Emmanuel Alves

unread,
Jan 23, 2009, 2:22:10 PM1/23/09
to pb...@googlegroups.com
VBScript mesmo.

Da mesma forma que vc fez aí para Windows. No meu caso não é necessário o suporte para Windows.

Até li alguma coisa sobre JNI, mas preferi utilizar o vbscript mesmo.

Tem um programinha feito em .Net aberto que lista todos os objetos do WMI (Windows Managemente Instrumentation) e é interessante para quando queremos visualizar quais são as propriedades que existem num objeto destes.

To mandando ele em anexo, mas caso queira ver mais alguma coisa, basta pegar os fontes no link: http://www.codeproject.com/KB/system/GetHardwareInformation.aspx

[]s

Emmanuel Alves
mane...@gmail.com


2009/1/23 Rafaell Pinheiro <rafa...@gmail.com>
hardwareinfo.rar

Artur Dal Pra

unread,
Jul 9, 2019, 10:45:31 AM7/9/19
to PBJug
Caro Rafael e colegas.

Grande é minha alegria em contribuir.

  Dim s as shell
  s = new shell
  s.Execute "wmic bios get serialnumber"
  EditField1.Text=s.Result

Encontrei isto num livro de RealBasic, testei e funciona. 
Resultou:
SerialNumber
NFQ36AL089473J4F39501

Depois vc substitui strings para tirar o "SerialNumber"

Boa programação a todos.
Abraço,
Artur A Dal Prá
Florianópolis (SC)
Reply all
Reply to author
Forward
0 new messages