• 15 апреля стартует «Курс «SQL-injection Master» ©» от команды The Codeby

    За 3 месяца вы пройдете путь от начальных навыков работы с SQL-запросами к базам данных до продвинутых техник. Научитесь находить уязвимости связанные с базами данных, и внедрять произвольный SQL-код в уязвимые приложения.

    На последнюю неделю приходится экзамен, где нужно будет показать свои навыки, взломав ряд уязвимых учебных сайтов, и добыть флаги. Успешно сдавшие экзамен получат сертификат.

    Запись на курс до 25 апреля. Получить промодоступ ...

Имя машины

  • Автор темы Marriage
  • Дата начала
Статус
Закрыто для дальнейших ответов.
M

Marriage

Не подскажете, как можно узнать имя машины ???(в смысле компьютера)
Я работаю (Пытаюсь) программить с Oracl'ом...
Мне нужно убить все повисшие сессии ... , а для этого мне нужно узнать имя моего компьютера ...
Помогите кто чем может ... :unsure:
 
M

Maniacosaur

Есть функция Windows API GetComputerName (или GetComputerNameEx) Вот она тебе и скажет, как твой комп называется.
 
S

shm

А как ты узнаешь в сети имя машины если она висит?
Повисшие сессии Oracle убивает сам по timeout, только это может быть 30мин - 1час и т.д.
Я использовал dbms_application_info.set_action для установки начала времени транзакции (можно и через стандартные таблицы, но там были проблемы). Имя машины и то, что записано через set_action:
select machine,action from sys.v_$session where audsid=userenv('sessionid');
 
M

Marriage

Все бы конечно хорошо ...

Но GetComputerName не будет работать под 98 виндой, а мне нужно сделать так, чтобы работаль и под 95, и под NT ...

А насчет повисших сессий я делаю по - другому ...

имя машины нужно знать по любому, если не хочешь убить сессии других пользователей...

Во вьюхе V$SESSION есть такая вешь, как время , когда эта сессия была открыта ...
Если повисло приложение, то его нужно либо завершить задачу (сессия при этом завершается), либо перезагрузить комп(тогда сессия остаётся висеть). Просто сравнивать время загрузки виндовоза с LogonTime... , если LogonTime<Времени последней загрузки винды, то KILL ALERT SESSION ...

Я хотел бы спросить такую вешь, можно ли брать в реестре
HKEY_local_machine\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName как имя машины ??? :)
 
?

????

Но GetComputerName не будет работать под 98 виндой, а мне нужно сделать так, чтобы работаль и под 95, и под NT ...
кто сказал?
Код:
GetComputerName

The GetComputerName function retrieves the NetBIOS name of the local computer. This name is established at system startup, when the system reads it from the registry.

If the local computer is a node in a cluster, GetComputerName returns the name of the cluster virtual server.

GetComputerName retrieves only the NetBIOS name of the local computer. To retrieve the DNS host name, DNS domain name, or the fully qualified DNS name, call the GetComputerNameEx function. Additional information is provided by the IADsADSystemInfo interface.


BOOL GetComputerName(
LPTSTR lpBuffer,
LPDWORD lpnSize
);

Parameters
lpBuffer 
[out] Pointer to a buffer that receives a null-terminated string containing the computer name or the cluster virtual server name. The buffer size should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters. 
lpnSize 
[in, out] On input, specifies the size of the buffer, in TCHARs. On output, the number of TCHARs copied to the destination buffer, not including the terminating null character. 
If the buffer is too small, the function fails and GetLastError returns ERROR_MORE_DATA. The lpnSize parameter specifies the size of the buffer required, not including the terminating null character.

Windows Me/98/95: GetComputerName fails if the input size is less than MAX_COMPUTERNAME_LENGTH + 1.
Return Values
If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks
The GetComputerName function retrieves the NetBIOS name established at system startup. Name changes made by the SetComputerName or SetComputerNameEx functions do not take effect until the user restarts the computer.


Windows Me/98/95: GetComputerNameW is supported by the Microsoft Layer for Unicode. To use this, you must add certain files to your application, as outlined in Microsoft Layer for Unicode on Windows Me/98/95 Systems.

Example Code 
For an example, see Getting System Information.

Requirements
Client: Requires Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server: Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Unicode: Implemented as Unicode and ANSI versions. Note that Unicode support on Windows Me/98/95 requires Microsoft Layer for Unicode.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

Вот еще пример из MSDN:
Код:
#include <windows.h>
#include <stdio.h>

TCHAR* envVarStrings[] =
{
"OS     = %OS%",
"PATH    = %PATH%",
"HOMEPATH  = %HOMEPATH%",
"CLIENTNAME = %CLIENTNAME%",
"TMP    = %TMP%"
};
#define ENV_VAR_STRING_COUNT (sizeof(envVarStrings)/sizeof(TCHAR*))
#define INFO_BUFFER_SIZE MAX_PATH+4
void printError( TCHAR* msg );

void main( )
{
DWORD i;
TCHAR infoBuf[INFO_BUFFER_SIZE];
DWORD bufCharCount = INFO_BUFFER_SIZE;

// Get and display the name of the computer. 
bufCharCount = INFO_BUFFER_SIZE;
if( !GetComputerName( infoBuf, &bufCharCount ) )
 printError( "GetComputerName" ); 
printf( "\nComputer name:   %s", infoBuf ); 

// Get and display the user name. 
bufCharCount = INFO_BUFFER_SIZE;
if( !GetUserName( infoBuf, &bufCharCount ) )
 printError( "GetUserName" ); 
printf( "\nUser name:     %s", infoBuf ); 

// Get and display the system directory. 
if( !GetSystemDirectory( infoBuf, INFO_BUFFER_SIZE ) )
 printError( "GetSystemDirectory" ); 
printf( "\nSystem Directory:  %s", infoBuf ); 

// Get and display the Windows directory. 
if( !GetWindowsDirectory( infoBuf, INFO_BUFFER_SIZE ) )
 printError( "GetWindowsDirectory" ); 
printf( "\nWindows Directory: %s", infoBuf ); 

// Expand and display a few environment variables. 
printf( "\n\nSmall selection of Environment Variables:" ); 
for( i = 0; i < ENV_VAR_STRING_COUNT; ++i )
{
 bufCharCount = ExpandEnvironmentStrings( envVarStrings[i], infoBuf, INFO_BUFFER_SIZE ); 
 if( bufCharCount > INFO_BUFFER_SIZE )
  printf( "\n  (Warning: buffer too small to expand: \"%s\")", envVarStrings[i] );
 else if( !bufCharCount )
  printError( "ExpandEnvironmentStrings" );
 else
  printf( "\n  %s", infoBuf );
}
}

void printError( TCHAR* msg )
{
DWORD eNum;
TCHAR sysMsg[256];
TCHAR* p;

eNum = GetLastError( );
FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL, eNum,
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
    sysMsg, 256, NULL );

// Trim the end of the line and terminate it with a null
p = sysMsg;
while( ( *p > 31 ) || ( *p == 9 ) )
 ++p;
do { *p-- = 0; } while( ( p >= sysMsg ) &&
            ( ( *p == '.' ) || ( *p < 33 ) ) );

// Display the message
printf( "\n WARNING: %s failed with error %d (%s)", msg, eNum, sysMsg );
}

HKEY_local_machine\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName как имя машины

Имхо GetComputerName там и берёт (не уверен).
 
M

Marriage

<!--QuoteBegin-????+13:04:2004, 23:39 -->
<span class="vbquote">(???? @ 13:04:2004, 23:39 )</span><!--QuoteEBegin-->кто сказал?[/quote]
:blink: Сказал HElp,

QUICK INFO
WINNT YES
WIN95 YES
WIN32S no
 
A

admin

Marriage
Раз вопрос по делфам, то вот как. Специально для тебя написал :blink:
Код:
// Получение Имени компа
function GetComputerName : string; 
var 
 buffer:array[0..MAX_COMPUTERNAME_LENGTH+1] of Char; 
length:Cardinal; 
begin 
length:=MAX_COMPUTERNAME_LENGTH+1; 
windows.GetComputerName (@buffer,length);
result := buffer; 
end;

// Есть ли у юзера права админа
const 
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = 
 (Value: (0, 0, 0, 0, 0, 5)); 
SECURITY_BUILTIN_DOMAIN_RID = $00000020; 
DOMAIN_ALIAS_RID_ADMINS   = $00000220; 

function IsAdmin: Boolean; 
var 
hAccessToken: THandle; 
ptgGroups: PTokenGroups; 
dwInfoBufferSize: DWORD;
psidAdministrators: PSID;
x: Integer; 
bSuccess: BOOL; 
begin 
Result := False; 
bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, 
 hAccessToken); 
if not bSuccess then 
begin 
 if GetLastError = ERROR_NO_TOKEN then 
 bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, 
  hAccessToken); 
end; 
if bSuccess then 
begin 
 GetMem(ptgGroups, 1024); 
 bSuccess := GetTokenInformation(hAccessToken, TokenGroups, 
  ptgGroups, 1024, dwInfoBufferSize); 
 CloseHandle(hAccessToken); 
 if bSuccess then 
 begin 
  AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, 
   SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 
   0, 0, 0, 0, 0, 0, psidAdministrators); 
  {$R-} 
  for x := 0 to ptgGroups.GroupCount - 1 do 
   if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then 
   begin 
    Result := True; 
    Break; 
   end; 
  {$R+} 
  FreeSid(psidAdministrators); 
 end; 
 FreeMem(ptgGroups); 
end; 
end;
 
M

Maniacosaur

Win32s это случайно не NT3.5 немного апгредженая? :p
 
M

Marriage

WIN32s - это 32-х разрядная винда (98, Me)... WINDOWS95 - 16 - ти....
GetConputerName не работает под 98!!!!!! :) (Ставил, проверял, выдаёт абракадабру ,даже количество символов не сходиться ...)
В общем, решил брать из реестра ...
 
M

Maniacosaur

Уточнил. Win32s это 3.11 винды с каким то там хитрым обновлением, которое позволяет некоторые вещи делать.
Но то, что следующий код работает под Windows 95/98/ME/2000/XP я отвечаю!!!
Код:
procedure CompName;
var
 p: PChar;
 s: Cardinal;
begin
 s:=MAX_COMPUTERNAME_LENGTH+1;
 GetMem(p,s);

 GetComputerName(p,s);  // Функция Windows API
 ShowMessage(p);
 FreeMem(p);
end;

Про функцию в MSDN много чего написано, но вот системные требования ее:
Requirements
Windows NT/2000/XP: Included in Windows NT 3.1 and later.
Windows 95/98/Me: Included in Windows 95 and later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000/XP. Also supported by Microsoft Layer for Unicode.
А еще там написано, что эта функция не срабатывает под Windows 95/98/ME только в случае если размер буфера под имя компа меньше чем MAX_COMPUTERNAME_LENGTH + 1.
Вот.

ЗЫ: А что такое WIN32s я еще уточню
 
G

Guest

Хрен его знает, я проверял на 2-х 98-х - не работает, абракадабра получается ....
Лучше брать из реестра .. :rolleyes:
 
A

admin

Guest
Бери. Учти то в NT системах такая фишка не пройдет. Может праф не хватить.
 
M

Maniacosaur

Нашел и я винду, в которой это не срабатывает. Но из 30 компов, это был один, достаточно старинный, с 98-й чуть ли не бета версии.
 
G

Guest

Maniacosaur
кстати у меня всё работает замечательно в 98 SE.
 
M

Maniacosaur

В SE и у меня работает. Я говорил про сырую 98ю. И на 95 у меня тоже работает. Странно, однако.
 
S

Shnur

так а как
то все узнать по сетке т.е. по айпи???
 
Статус
Закрыто для дальнейших ответов.
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!