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…
é exatamente isto…
Cara, mto bom. Vou testar isso aí.
Ele pega um número serial…
Mas pegou o msm numero em 2 maquinas…
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?
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…
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.
pode se fazer isso sem usar scripts nem nada
veja esse exemplo que eu estudei um tempo atras
[code]
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.
-
- Source Forge posting
- http://sourceforge.net/forum/forum.php?thread_id=1785936&forum_id=375946
-
- 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();
}
}[/code]
é 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
gobbo, sua solução com a jacob é show, soh que para windows neh!!!
Existe alguma biblioteca similar a essa para Linux??
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…)
Sim… mais a questão é saber qual .SO se utilizar?
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á!
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
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…
[quote=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á!
[/quote]
[size=20][color=darkblue]TBM quero saber se é isso mesmo[/color][/size]
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!
Também testei e tive como retorno um número negativo, alguém sabe explicar se está correto?
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);
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???
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);
}