2012/08/28

c#, Security 이벤트로그에서 로그온 뽑기

다음 예는,.  서버에 로그온한 내역을 뽑아 달라는 요청이 있어서 급조한 내용이며, Message  문자열에서 정규편식을 통해서 로그온 이름과, IP주소(원격로그인) 와 로그온 시간을 뽑는 것.
c# 이기는 하지만,. PowerShell 로도 가능.^^

이벤트로그의 Message 문자열에서 필요한 것만 정규편식으로 파싱.
- Windows 2000
4624 (성공) , 4648(시도)
계정 이름:  UpdatusUser
원본 네트워크 주소: xxx.xxx.xxx.xxx
- Windows 2008 / R2
528(성공), 552 (시도)
사용자 이름: yeonpil
원본 네트워크 주소: xxx.xxx.xxx.xxx
로그온 유형:   5

운영체제 종류에 따라서 이벤트 코드가 다르므로 운영체제 구분 코드로 조건절 추가.


Version _ver = Environment.OSVersion.Version;
string _osVer = _ver.Major.ToString() + "." + _ver.Minor.ToString(); // 5.2 , 6.1


ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT Message, TimeGenerated FROM Win32_NTLogEvent
        WHERE Logfile = 'Security' AND(" + _evtCode + ")");
        string _Message; string _TimeGenerated; 
        string _Account = ""; 
        string _IpAddress = ""; 
        foreach(ManagementObject obj in searcher.Get()) {
            _Message = obj["Message"].ToString();
            _TimeGenerated = obj["TimeGenerated"].ToString();
            Regex regex1 = new Regex(_AccountString + ":(.+)\r");
            Regex regex2 = new Regex("원본 네트워크 주소:(.+)\r");
            MatchCollection match1 = regex1.Matches(_Message);
            if (match1.Count > 0) {
                _Account = match1[1].Groups[1].Value.Trim();
            }
            Match match2 = regex2.Match(_Message);
            if (match2.Success) {
                _IpAddress = match2.Groups[1].Value.Trim();
            }
            Console.WriteLine(_Account + ":" + _IpAddress +
                "\t" + wmiDateConvert(_TimeGenerated));
        }

아래와 같은 코드도 사용 가능



        foreach(System.Diagnostics.EventLogEntry entry in _evt.Entries) {
            string _EventCode = Convert.ToString(entry.InstanceId & 0xFFFF);
            if (_EventCode == "552") {}
        }


참 쉽죠잉~~~ ? 헐.

닷넷프레임워크 3.5 / 4.0 인 경우에는 System.Diagnostics.Eventing.Reader  클래스를 이용해서도 가능

참고 http://phejndorf.wordpress.com/2011/03/31/using-c-and-linq-to-read-a-windows-eventlog-file-evtx/




2012/08/27

c#, NETWORKLIST.NetworkListManager 예

Vista 이후에, 네트워크 연결 관리자에서 현재 연결된 활성 네트워크 조회 코드 예제.
서버 모니터링에 필요해서... 어렵지 않아요~~^^

msdn. http://msdn.microsoft.com/en-us/library/windows/desktop/aa370803(v=vs.85).aspx


NETWORKLIST.NetworkListManager _nlManager = new NETWORKLIST.NetworkListManager();

foreach(NETWORKLIST.INetwork _network 
  in _nlManager.GetNetworks(NETWORKLIST.NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED)) {
    Console.WriteLine(_network.GetName());
    Console.WriteLine(_network.GetCategory());

    foreach(NETWORKLIST.INetworkConnection c in _network.GetNetworkConnections()) {
        var k = from _nis in NetworkInterface.GetAllNetworkInterfaces() 
              where _nis.Id == c.GetAdapterId().ToString("B").ToUpper() select _nis;

        if (k != null & k.Count() > 0) {
            NetworkInterface _ni = k.FirstOrDefault();
            Console.WriteLine(_ni.Id);
            Console.WriteLine(_ni.Name);
        }
    }
}


네트워크
NLM_NETWORK_CATEGORY_PUBLIC
{465ac774-d5f4-4a3f-9351-51440256a6bb}
{465AC774-D5F4-4A3F-9351-51440256A6BB}
로컬 영역 연결 3


2012/08/14

maxJsonLength JavaScriptSerializer 예외

ASP.NET 사이트에서 json 데이터 요청을 ASP.NET 에서 처리를 하는 경우, 요청에 대한 응답값이 너무 큰 경우  "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property." 와 같은 예외가 발생할수 있음.

maxJsonLength  의 기본값은, 2097152 characters. 102400 (100k).

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.maxjsonlength.aspx

web.config 에서 허용 값을 더 늘려줄수 있음.
<configuration>
       <system.web.extensions>
          <scripting>
              <webServices>
                  <jsonSerialization maxJsonLength="50000000"/>
              </webServices>
          </scripting>
      </system.web.extensions>
   </configuration>   




Delete Symantec Shared\VirusDefs Subfolders

시만텍 안티바이러스가 설치되어 있는 경우, 아래 폴더에 바이러스 정의가 저장 됨.
C:\Program Files\Common Files\Symantec Shared\VirusDefs

그런데,. 정의 파일이 지속적으로  쌓여서(몇 G 됨) 디스크 공간이 부족할때에
오래된 정의 파일을 삭제 하려면 해당 서비스를 중지후에 삭제 하면 됨.
삭제 대상은, 날짜별 폴더  및 .tmp 확장자 파일만 삭제해야 함.

 

[Symantec Endpoint Protection] 서비스 중지를 서비스 관리자 GUI 에서 disable 상태인 경우에는

C:\Program Files\Symantec\Symantec Endpoint Protection>Smc.exe -stop
C:\Program Files\Common Files\Symantec Shared\VirusDefs  하위 정의파일 폴더 삭제
C:\Program Files\Symantec\Symantec Endpoint Protection>Smc.exe -start

 


2012/08/10

HP P2000 G3 iSCSI Storage

스토리지 장비 최초 셋업을 하기 위해서 스토리지 Management Tool 에 접근해야 함. 가장 쉽게 할수 있는 방법은, IP로 WEB UI 에 접근해서 설정하는 방법으로, 엔클로져의 관리 모드용 랜으로 연결하여 접근.

스토리지의 컨트롤러의 기본 설정값은 아래와 같음.
 - Controller A : 10.0.0.2 / 255.255.255.0
 - Controller B : 10.0.0.3 / 255.255.255.0
 - Default Gateway : 10.0.0.1

 

 

위와 같은 랜 환경(동일 대역)을 갖춘 PC를 통해서 WEB UI 에 접근이 가능.
(물론, Console(CLI) 모드를 통해서도 설정도 가능하며, 위 컨트롤러의 IP 변경도 가능)

만약 콘솔(CLI) 모드로 연결하려는 경우 아래와 같은 설정값으로 연결 가능 함.
(가능하면, 콘솔 모드보다는 WEB UI 모드가 쉽고 편하므로 WEB 모드 권장)
  - Connector : COM3
  - Baud rate : 115,200
  - Data bits : 8
  - Parity : None
  - Stop bits : 1
  - Flow control : None

   CLI 에서 IP 설정
   # set network-parameters ip 192.168.0.10 netmask 255.255.255.0 gateway 192.168.0.1 controller a
   # set network-parameters ip 192.168.0.11 netmask 255.255.255.0 gateway 192.168.0.1 controller b
   # show network-parameters
   # restart mc both

위와 같은 방법으로 연결이 완료되면 기본 로그인 manage / !manage 를 통해서 로그인 완료.

 


 

 

 

 



p2000-network-config.png
p2000-21.png
p2000-1.png
p2000-3.png

2012/08/08

PHP for IIS 8 (update)

설치파일 : http://windows.php.net/download/#php-5.4 에서 VC9 x86 Non Thread Safe 버젼
(가능하면, 그냥 zip 파일 설치를 권장 함)

 

설치후, 

1. 모듈 매핑에 php 추가

  • Request path: *.php
  • Module: FastCgiModule  (IIS 모듈에서 CGI 설치되어 있어야 함)
  • Executable: "C:[Path to your PHP installation]php-cgi.exe"  (설치경로)
  • Name: PHP via FastCGI
  • Method : GET / POST / HEAD

2. PHP 설치 경로에 ApplicationPoolIdentity 계정의 실행권한 설정 필요.   
     특정 풀 계정 아니면, 그냥 IIS_USRS 를 줘도 크게 문제 없음.

3. FastCGI 에 등록 및 설정에서 "파일의 변경 내용 모니터" 에서 php.ini 파일 지정     
     php.ini 설정 변경시 바로 적용이 가능하도록.

4. php.ini 설정

  • Set fastcgi.impersonate = 1
  • Set cgi.fix_pathinfo=1
  • Set cgi.force_redirect = 0
  • extension_dir = "./ext"
  • extension=php_mssql.dll (mssql 연동시, SQL Native PHP Driver 사용시 모듈 별도 추가
  • extension=php_mysql.dll (mysql 연동시)
  • date.timezone = Asia/Seoul

 


서버 관련 무료 서적 pdf(en)

Understanding Microsoft Virtualization R2 Solutions
http://ligman.me/N1Bx4H

Introducing Windows Server 2012
http://ligman.me/N1CgTz

Introducing Microsoft SQL Server 2012
http://ligman.me/H8d9P3

Microsoft SQL Server AlwaysOn Solutions Guide for
High Availability and Disaster Recovery

http://ligman.me/N1I2o4

SQL Server 2012 Upgrade Technical Guide
http://ligman.me/N1Jo27

Backup and Restore of SQL Server Databases
http://ligman.me/N1HEpM

Master Data Services Capacity Guidelines
http://ligman.me/N1HX3Q

 


Tomcat JSP, java.lang.ClassNotFoundException

java.lang.ClassNotFoundException: org.apache.jsp.main_jsp
    at java.net.URLClassLoader$1.run(URLClassLoader.java:198)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:186)

org.apache.jasper.JasperException: /main.jsp(8,0) The value for the useBean class attribute xxx is invalid.

 

환경 : 기존 Resin 기반으로 개발된 Jsp 사이트를 Tomcat 기반으로 마이그레이션시 오류 발생

오류 :  Tomcat 에서 Jsp 코드내 선언된 Class 를 찾지 못함
          <jsp:useBean id="bbean" scope="request" class="xxx"  />

해결 :  Resin 에서는 WEB-INF\classes 내 클래스를 클래스 이름으로만으로도 참조가 가능하지만, Tomcat 에서는 패키지 이름까지 정확하게 지정을 해줘야 함. (Tomcat 5.5 기준)

 


가장 많이 본 글