화요일, 7월 10, 2007

UNIX Code Migration Guide

http://msdn2.microsoft.com/ko-kr/library/ms811903.aspx


msdn 자료: unix로 만들어진 프로그램을 win32로 포팅해야하는 경우 읽어보면 좋은 자료입니다.
대충 개념을 잡을 수 있는 좋은 문서입니다.

목요일, 6월 14, 2007

fcntl win32/posix

# portalocker.py - Cross-platform (posix/nt) API for flock-style file locking.
# Requires python 1.5.2 or better.

"""Cross-platform (posix/nt) API for flock-style file locking.

Synopsis:

import portalocker
file = open("somefile", "r+")
portalocker.lock(file, portalocker.LOCK_EX)
file.seek(12)
file.write("foo")
file.close()

If you know what you're doing, you may choose to

portalocker.unlock(file)

before closing the file, but why?

Methods:

lock( file, flags )
unlock( file )

Constants:

LOCK_EX
LOCK_SH
LOCK_NB

I learned the win32 technique for locking files from sample code
provided by John Nielsen in the documentation
that accompanies the win32 modules.

Author: Jonathan Feinberg
Version: $Id: portalocker.py,v 1.3 2001/05/29 18:47:55 Administrator Exp $
"""

import os

if os.name == 'nt':
import win32con
import win32file
import pywintypes
LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0 # the default
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
# is there any reason not to reuse the following structure?
__overlapped = pywintypes.OVERLAPPED()
elif os.name == 'posix':
import fcntl
LOCK_EX = fcntl.LOCK_EX
LOCK_SH = fcntl.LOCK_SH
LOCK_NB = fcntl.LOCK_NB
else:
raise RuntimeError("PortaLocker only defined for nt and posix platforms")

if os.name == 'nt':
def lock(file, flags):
hfile = win32file._get_osfhandle(file.fileno())
win32file.LockFileEx(hfile, flags, 0, 0xffff0000, __overlapped)

def unlock(file):
hfile = win32file._get_osfhandle(file.fileno())
win32file.UnlockFileEx(hfile, 0, 0xffff0000, __overlapped)

elif os.name =='posix':
def lock(file, flags):
fcntl.flock(file.fileno(), flags)

def unlock(file):
fcntl.flock(file.fileno(), fcntl.LOCK_UN)

if __name__ == '__main__':
from time import time, strftime, localtime
import sys
import portalocker

log = open('log.txt', "a+")
portalocker.lock(log, portalocker.LOCK_EX)

timestamp = strftime("%m/%d/%Y %H:%M:%S\n", localtime(time()))
log.write( timestamp )

print "Wrote lines. Hit enter to release lock."
dummy = sys.stdin.readline()

log.close()

수요일, 5월 23, 2007

python dict value sort

count = 0
for i in sorted( MAP.items(), \
lambda x, y: cmp(x[1], y[1]), reverse=True):
print "k[%s] value[%s]" % ( i[0], i[1]);
count += 1;
if count > 10: # 10 상위 열개만 출력함.
break;

월요일, 5월 21, 2007

디버깅 이야기: strace, truss, tusc

디버깅의 시작은 과감히 툴을 먼저 배우는 것이라고 해도 과언이 아닐정도로 툴에
익숙해야합니다. 디버깅 툴은 어떻게 보면, 크게 구분이 되어 있는 것은 아니지만
사뭇 심도있는 분석을 위해서는 해킹에 사용되는 것과 크게 다르지 않습니다.
디버깅과 해킹은 같은 맥락에 있는 것이지요.

먼저 쉽고 재밌게 접근할 수 있는 것이 system call tracer입니다.

linux: strace
solaris: truss
hpux: trace(10.x), tusc(11.x)

로 알려져 있는 것들이지요. 위 프로그램들의 option 들이 대개 비슷합니다.

strace ls

만 해도 나오는 내용이 어떻다는 것을 보실 수 있을텐데요.
이들은 모두 kernel level의 함수들입니다. 즉 system call이라는 것이지요.

직관적으로 이용할 수 있는 방법은 다음과 같은 것들입니다.

1. 어떤 shared library가 사용되는지 알수 있음.
2. 1번과 비슷하지만 어떤 파일을 열다가 실패하는지,
대개 configuration file을 global, home.. 순으로 찾지요.
3. process가 잠시 멈출때, 어떤것을 대기하고 있는지.
4. 전송되고 들어오는 내용은 무엇인지 (-s 1024 option)
5. 어떤 signal을 받는지.
6. ipc 객체들은 어떤것들이 이용되는지.

등등...

system call은 기본적으로 OS를 다루는 방법에 대한 것이므로, 많은 hint를 얻을 수
있습니다.

option 들중에 중요한 것 몇가지만 소개하자면, system call의 가장 대표적인 것중의
하나는 실행되고 있는 daemon의 현재 작업내용을 살펴볼수 있는 것이 있습니다.

strace -p

형태로 실행중인 process를 살펴보는 것이지요. 더불어 daemon의 경우 fork가
일어나는 경우가 많은데,

strace -f -p

-f option을 주어 fork되어 나오는 process까지 trace 하라는 것입니다. fork외에
vfork도 추적할 수 있어야하므로 대개 f를 쓸때는 다음과 같이 사용합니다.

strace -fF -p

더 줄여서

strace -fFp

로 사용하지요.

이것들을 종합하여 다음과 같은 용도로 사용할 수 있습니다.

1. daemon 이 갑자기 멈추었는데, debug 용 printf를 집어 넣지 않았을 때, 알고싶은
경우.
2. socket server가 과연 process가 connection을 접수한 뒤 제대로 fork 되는지.
3. telnet 서버에 접속하였는데, prompt가 떨어지지 않는 경우 inetd가 무슨일을
하는지. (대개 tcp_wrapper에 의해 DNS IP resolve 하는 경우가 많죠.)

지금까지 한 것은 일부분에 지나지 않습니다. 남의 program을 추적할때 system call
trace를 하는 것만으로 process가 하는 일을 상상할 수 있다면, 프로그램을
만든사람은 어느 code를 지나가고 있는지 알 수 있을 것입니다.


----

출처: http://kldp.org/node/900

금요일, 2월 09, 2007

scriptable install system

간단한 스크립트 형태로 setup파일을 만들 수 있는 프로그램

샘플을 보면 여러 형태로 쉽게 만들 수 있어서 배포하기 쉽다.

http://nsis.sourceforge.net/Main_Page

perl2exe - 실행파일 만들기

* 파이션을 이용해서 실행파일을 만든경우
소스가 있는 위치에 setup.py파일을 만들고 실행시키면 dist디렉토리가 생성되면서 실행파일이 생성됨.
실행파일과 MSVCR71.dll을 배포하면됩니다.


* sample - console부분에 작성한 py파일을 입력한다.

from distutils.core import setup
import py2exe
import sys

# If run without args, build executables, in quiet mode.
if len(sys.argv) == 1:
sys.argv.append("py2exe")
sys.argv.append("-q")



setup(
# The first three parameters are not required, if at least a
# 'version' is given, then a versioninfo resource is built from
# them and added to the executables.
version = "0.0.1",
description = "py2exe hello world !!!",
name = "hello world samples",
options = {"py2exe": {"compressed": 1,
"optimize": 2,
"ascii": 1,
"bundle_files": 1}},
zipfile = None,
console = ["a.py"],
)

토요일, 2월 03, 2007

svn diff a.c 를 하면 vimdiff로 바로 보이게 하려면

svn diff a.c
를 하면 vimdiff로 바로 보이게 하려면.

$ more ~/bin/vimdiff.sh
#!/bin/sh
while test $# -gt 2; do shift; done
vimdiff $@


$cat ~/.subversion/config | grep diff-cmd
diff-cmd = vimdiff.sh

PATH에 ~/bin 을 넣어 두면 됩니다.



힛.. 좋네요^^변경하셔가지공 보시면 좋습니다



출처: http://kldp.org/comment/reply/52160/200691

화요일, 1월 02, 2007

pychecker - 문법검사 & 버그 찾기

pychecker - pychecker homepage

python용 버그를 찾아 주는 tool입니다.

perl에 있는 perl -cw의 강력한 기능에 perl에 미련을 못 버리고 있었는데

python에도 이런 기능이 있군요. ㅎㅎ

일단 문법 검사 기능이 있으니깐 좋네요.

간단 사용법: pychecker fileName.py

자세한 설명은 pychecker homepage에서 참고하세요.

목요일, 12월 14, 2006

linux network settting - route

http://kelp.or.kr/korweblog/stories.php?story=01/09/29/1007612


[ 네트워크 설정(두개의 랜카드 잡기) ]

1. IRQ, IO 번호 확인하기
$ cat /proc/pci
$ cat /proc/interrupts
$ cat /proc/ioports
$ dmesg

2. 부팅시 커널차원에서 인식 시키기
# Lan종류 + auto IRQ + auto IO + Lancard Device 번호의 순서로
$ vi /etc/lilo.conf
append="ether=0,0,eth0 ether=0,0,eth1" # PnP 인식
# append="ether=11,0x6100,eth0 ether=5,0x300,eth1" # 특정 인식

3. 일종의 드라이버인 모듈을 올리기
$ ls /lib/modules/kernel-version/net
$ modprobe ne.o io=0x300 irq=5
$ lsmod
$ rmmod
$ vi /etc/conf.modules
alias eth0 rtl8139 # PCI LANCard인 경우
alias eth1 ne # ISA LANCard인 경우
options ne io=0x300 irq=5
$ control-panel
Kernel Daemon Configuration -> Add -> Module Types eth -> OK ->
Which module type? eth1 -> Which module? ne -> OK ->
io=0x300 -> irq=5 -> Done

4. CMOS 차원에서의 IRQ 설정
# CMOS에서 네트워크의 PNP 기능을 없애서 내정 IRQ에 따른 출동을 피한다
[PNP/PCI Configuration]
PNP OS Installed : NO

5. 랜카드 차원에서의 IRQ 설정
# 물리적인 변경
LANCard Jumper move 10 -> 5
# 프로그램을 이용한 변경
Intel Ether Express Pro/10 PNP ISA e10disk.exe sofset2.exe
RealTek 8019 ISA PNP Ethernet(ne2000) rset8019.exe
# Setup
Plug and Play : Disable(or Juper less)
IO and IRQ setting

6. 모듈이 잡혔나 확인하기
$ uname -a # 커널버전 보기
$ ls /lib/modules/2.2.7/net
ne.o rt8139.o
$ /sbin/lsmod # 확실히 이부분이 올라와 있어야 한다
ne, rt8139 Module
$ modprobe ne io=0x300 irq=5 # 모듈을 로드 시키는 명령

7. 네트워크 등록정보 입력
# ip 설정
$ ifconfig # 기존 정보 보기
$ ifconfig eth0 192.168.10.5
$ ifconfig eth0 192.168.10.5 netmask 255.255.255.0 up # ip를 설정하는 명령
$ ifconfig eth0 down
# 라우팅 테이블 설정
$ route # 기존 정보 보기
$ netstat -nr # 기존 정보 보기
$ route add -net 192.168.10.0 netmask 255.255.255.0 dev eth0 # 추가 명령
$ route del default gw 192.168.255.255 eth0 # 삭제 명령
$ route add default gw 203.239.44.50 eth0
# 비주얼 제어판을 통한 설정
$ netcfg # 혹은 "$ linuxconf"
Default Gateway-203.239.44.50
Default Gateway Device-eth0
$ ifdown eth0; ifup eth0

8. 텍스트를 통한 Route, Gateway 설정
$ vi /etc/sysconfig/static-routes
# 각기 다른 게이트웨이를 쓸 경우 or skip
eth0 net 192.168.10.0 netmask 255.255.255.0 gw 192.168.10.1
eth1 net 192.168.11.0 netmask 255.255.255.0 gw 192.168.11.1
eth1:0 net 192.168.12.0 netmask 255.255.255.0 gw 192.168.12.1
# eth1:0 IP-Alias를 적용한 예
$ vi /etc/sysconfig/network-scripts/ifcfg-eth1
DEVICE="eth1"
IPADDR="192.168.100.1"
NETMASK="255.255.255.0"
NETWORK="192.168.100.0"
BROADCAST="192.168.100.255"
ONBOOT="yes"
BOOTPROTO="none"
GATEWAY="192.168.11.1" # 여기다 직접 게이트웨이를 쓸수있다.
GATEWAYDEV="eth1"
$ netcfg
$ ifdown eth1; ifup eth1
$ ifconfig

9. 네트워크를 설정하는데 쓰이는 파일들
# Basic file: hosts, resolv.conf, network, ifcfg-eth0
/etc/HOSTNAME
/etc/host.conf
/etc/hosts
/etc/resolve.conf
/etc/nsswitch.conf
/etc/conf.modules
/etc/sysconfig/network
/etc/sysconfig/static-routes
/etc/sysconfig/network-scripts/ifcfg-eth0

10. 네트워크 테스트 명령들
$ ping; traceroute; nslookup

월요일, 12월 11, 2006

Python memory leaks

Tracking Down Memory Leaks in Python


This Page Mostly Obsolete

Most of the stuff on this page is obsolete nowadays, since Python (since version 2.0, I think) now includes a cyclical-reference garbage collector. Leaks like this are still possible, but usually only because an older Python extension module (implementing a container type) is used, one that doesn't adhere to the new GC API.


Long-running processes have a nasty habit of exposing Python's Achilles' Heel: Memory Leaks created by cycles. (objects that point at each other, either directly or circuitously). Reference counting cannot collect cycles. Here's one way to create a cycle:

class thing:
pass

refcount(a) refcount(b)
a = thing() 1
b = thing() 1 1
a.other = b 1 2
b.other = a 2 2

del a 1 2
del b 1 1

Objects a and b have become immortal.

Large and complex systems may create non-obvious cycles. Here are a few quick hints to avoid various ones that I've run into:

  • Be careful with bound method objects. Bound methods are created whenever you refer to a method object through an instance. This happens safely every time you call a method; but a common programming style ('functional') passes such objects around, stores them in variables, etc... In one case storing a bound method in the object made it immortal. Either del this object manually, or change your code.
  • Tracebacks are very dangerous. To be really safe, del a traceback if you have a handle to it. Another good idea is to assign None to both sys.traceback and sys.exc_traceback.
    Tracebacks can capture a large number of objects, especially within Medusa. For example, any exception handler that is called from within the polling loop (no matter how deeply), should do something like this...
        def my_method (self):
    try:
    do_something()
    except:
    try:
    ei = sys.exc_info()
    [... report error ...]
    finally:
    del ei

    ...otherwise it will capture references to every object in the socket map. I have plugged some really bad leaks this way.
  • Keep track of your objects. Either keep a count of how many are around (in a __del__ method), or keep a dictionary of the addresses of all outstanding objects. This will help locate leaks.
    class thing:

    all_things = {}

    def __init__ (self):
    thing.all_things[id(self)] = 1

    def __del__ (self):
    del thing.all_things[id(self)]
    Here is a module that will let you resurrect leaked objects. Using this module should fill you with shame. Make sure no one is looking.
    for addr in thing.all_things.keys():
    r = resurrect.conjure (addr)
    # examine r...
  • Here's the easiest way to find leaking objects: examine the reference count of each of your class objects. This will be roughly equal to the number of extant instance objects.
    # -*- Mode: Python; tab-width: 4 -*-

    import sys
    import types

    def get_refcounts():
    d = {}
    sys.modules
    # collect all classes
    for m in sys.modules.values():
    for sym in dir(m):
    o = getattr (m, sym)
    if type(o) is types.ClassType:
    d[o] = sys.getrefcount (o)
    # sort by refcount
    pairs = map (lambda x: (x[1],x[0]), d.items())
    pairs.sort()
    pairs.reverse()
    return pairs

    def print_top_100():
    for n, c in get_refcounts()[:100]:
    print '%10d %s' % (n, c.__name__)

    if __name__ == '__main__':
    top_100()

Notes

An interface to malloc_stats() [Linux]

원문: http://www.nightmare.com/medusa/memory-leaks.html

월요일, 10월 30, 2006

Install of Oracle 9i on Fedora Core 4

Install of Oracle 9i on Fedora Core 4

* 요약
fedora에 오라클 9i설치하기....^^

Xmanager이 있으면 원격으로 설치가 가능하다.. xclock이 실행되는지 확인함...

* java 1.3.0 버젼을 미리 설치한다. http://java.sun.com/j2se/1.3/download.html

1. 계정생성
su -
# groupadd dba
# useradd -g dba oracle

2. 환경설정
/etc/sysctl.conf
kernel.sem = 250 32000 100 128
kernel.shmmax = 2147483648
kernel.shmmni = 128
kernel.shmall = 2097152
kernel.msgmnb = 65536
kernel.msgmni = 2878
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000

3. Oracle 환경변수 수정
ORACLE_BASE=/opt/oracle
ORACLE_HOME=$ORACLE_BASE/920
ORACLE_SID=MY_ORACLE
LD_LIBRARY_PATH=$ORACLE_HOME/lib
LD_ASSUME_KERNEL=2.4.1
THREADS_FLAG=native
ORACLE_OEM_JAVARUNTIME=/opt/jre1.3.1_15
PATH=$PATH:$ORACLE_HOME/bin

export ORACLE_BASE ORACLE_HOME ORACLE_SID LD_LIBRARY_PATH LD_ASSUME_KERNEL THREADS_FLAG ORACLE_OEM_JAVARUNTIME PATH

4. 설치 확인
rpm -q gcc glibc-headers glibc-kernheaders glibc-devel compat-libstdc++ cpp compat-gcc

ftp://ftp.kaist.ac.kr/pub/fedora/linux/core/4/i386/os/Fedora/RPMS

5. config 변경후 reboot <-- 꼭 필요함..
/etc/selinux/config and change value of SELINUX to "disabled"

6. Download the Oracle 9i
gunzip ship_9204_linux_disk1.cpio.gz
gunzip ship_9204_linux_disk2.cpio.gz
gunzip ship_9204_linux_disk3.cpio.gz
cpio -idmv < ship_9204_linux_disk1.cpio
cpio -idmv < ship_9204_linux_disk2.cpio
cpio -idmv < ship_9204_linux_disk3.cpio

/install/linux/oraparam.ini and modify JRE_LOCATION
variable and set path to our JRE installation from Step
JRE_LOCATION=/opt/jre1.3.1_15

7. install cd Disk1 ./runInstaller
* 참고 http://ivan.kartik.sk/oracle/install_ora9_fedora.html

fedora 4 pro*c 컴파일

undefined reference to `ECPGget_sqlca' <-- 이 함 수를 못찾는 다고 나오는 경우

이런경우 pc파일에서 c로 변환시 postgressql 함수가 추가되어서 생기는 문제로.
proc설정파일을 수정하면 됩니다...



/oracle/9.2.0/precomp/admin/pcscfg.cfg

* 기존
sys_include=(/usr/include,/usr/lib/gcc-lib/i386-redhat-linux/3.2.3/include)
ltype=short

* 수정

sys_include=(/oracle/9.2.0/precomp/public,/usr/include,/usr/lib/gcc-lib/i386-redhat-linux/3.2.3/include)
ltype=short


* 추가내용: /oracle/9.2.0/precomp/public

컴파일시 시스템함수 못찾는경우 링크하기...^^

1. man 함수명
* 일반적인 경우에 man페이지에 대부분은 링크해야하는 라이브러리가 적혀있음....

2. man으로 알 수 없는경우

# nm -A /usr/lib/*.a | grep 시스템함수
이렇게 파일이 나오는경우
libabc.a
-labc <-- 이렇게 링크시에 적어주면 됩니다. 참고하세요.

VC6에서 PRO*C 설정하기..

FileView 에
Add files to Folder
오라클이 설치되어 있는 디렉토리 밑에 oraSQL8.LIB 파일을 추가
예) G:\PROGRAM~1\ORACLE\ORA81\PRECOMP\LIB\MSVC\oraSQL8.LIB

Tools -> Options -> Directories

Include files
G:\PROGRAM~1\ORACLE\ORA81\PRECOMP\PUBLIC
G:\PROGRAM~1\ORACLE\ORA81\OCI\INCLUDE

Library files
G:\PROGRAM~1\ORACLE\ORA81\PRECOMP\LIB\MSVC
G:\PROGRAM~1\ORACLE\ORA81\OCI\LIB\MSVC


Pro C 컴파일 2가지 방법

첫번째 방법

.pc 파일에서 오른쪽 마우스를 클릭하고 Settings를 선택하고

Custom Build 메뉴에서

Commands 에 및의 내용을 추가하고

G:\program~1\Oracle\Ora81\Bin\proc oraca=yes code=CPP define=d:\Oracle\Precomp\LIB\MSVC sys_include=d:\Oracle\Precom\PUBLIC $(ProjDir)\$(InputName)

Outputs 에 및의 내용을 추가하면
$(ProjDir)\$(InputName).cpp

내용을 추가하고 컴파일하면 됨.

솔라리스 아이피 변경시 확인

솔라리스를 아이피 변경시 확인해야하는 내용.

* Solaris 에서 변경해야 될 파일들
/etc/nodename # if you need to change the name of the machine
/etc/hostname.interface # eg. hostname.hme0
/etc/hosts # Update to reflect new name
/etc/nsswitch.conf # Update if your name resolution
/etc/resolv.conf

# Update if your name servers/domain changed (DNS only)
/etc/defaultdomain # set you default domain
/etc/defaultrouter # Set the default router's IP
/etc/inet/networks # Set your network name
/etc/inet/netmasks # Set your network number
/etc/n/etc/net/ticots/hosts # For the streams-level loopback
/etc/ticlts/hosts # For the streams-level loopback
/etc/net/ticotsord/hosts # For the streams-level loopback

* Solaris 에서 IP 변경 작업

/etc/hosts 파일을 수정함.
/etc/hostname.hme0 랜카드에 적용되는 호스명을 명시

$ ifconfig hme0 [ip] netmask 0xffffff00 broadcast + up

ex)
--- 영구적인 변경
$vi /etc/hostname.hme0
xxxx

$ vi /etc/hosts
127.0.0.1 localhost
xxx.xxx.xxx.xxx xxxx xxxx

--- 임시변경시 (컴퓨터가 켜져있는 동안, 리부팅되면 정보가 사라짐)
$ ifconfig -a
lo0: flags=1000849 mtu 8232 index 1
inet 127.0.0.1 netmask ff000000
hme0: flags=1000843 mtu 1500 index 2
inet xxx.xxx.xxx.xxx netmask ffffff00 broadcast xxx.xxx.xxx.xxx

$ ifconfig hme0 xxx.xxx.xxx.xxx netmask 0xffffff00 broadcast + up

* Solaris 에서 GATEWAY 변경 작업

$ netstat -rn
$ route add default [gateway ip]
$ vi /etc/defaultrouter
[gateway ip]

ex)
--- 영구적인 변경
$ vi /etc/defaultrouter
xxx.xxx.xxx.1

--- 임시적인 변경
route add default xxx.xxx.xxx.1


* Solaris 에서 DNS 변경 작업

ex)
$ vi /etc/resolv.conf
nameserver xxx.xxx.xxx.1
nameserver xxx.xxx.xxx.2

$ vi nsswitch.conf
# hosts: 부분을 수정한다.
# consult /etc "files" only if nis is down.
hosts: files dns

* 설정 변경 후 reboot , 시스템에 관한 내용이 변경된경우
reboot

linux network settting

리눅스 네트웩 설정 - IP 변경시 확인해야하는 파일..
LINUX NETWORK 설정

* 모든 설정은 root 계정으로 실행합니다. *

$ vi /etc/sysconfig/network

NETWORKING=yes
HOSTNAME=vtn01
GATEWAY=xxx.xxx.xxx.1 <-- default G/W IP로 변경함.

$ cd /etc/sysconfig/network-scripts

$ vi ifcfg-eth2

DEVICE=eth2
BOOTPROTO=none
HWADDR=
ONBOOT=yes
TYPE=Ethernet
DHCP_HOSTNAME=vtn01
IPADDR=xxx.xxx.xxx.xxx <-- IP
NETMASK=255.255.255.0
USERCTL=no
PEERDNS=yes
GATEWAY=xxx.xxx.xxx.1 <--- 해당 IP 대역에 G/W를 설정
IPV6INIT=no

$ vi route-eth2
GATEWAY0=xxx.xxx.xxx.1 <--- 해당 서버 GW
NETMASK0=255.0.0.0
ADDRESS0=xxx.0.0.0

$ vi route-eth3
GATEWAY0=xxx.xxx.xxx.1
NETMASK0=255.0.0.0
ADDRESS0=xxx.0.0.0

$ cd /etc/init.d

$ network restart

$ ifconfig <-- 아이피가 변경되었는지 확인

$ route <-- G/W ip가 적용되어 있는지 확인.


-----------------------------------------------------------------------------
이전

* /etc/sysconfig/network-scripts/ifcfg-eth0 파일을 수정함.
방법 1)
$ vi /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
ONBOOT=yes
BOOTPROTO=static
IPADDR=xxx.xxx.xxx.xx
NETMASK=255.255.255.0
GATEWAY=xxx.xxx.xxx.xx

이더넷 확인)
$ ifconfig -a
eth0 Link encap:Ethernet HWaddr
inet addr:xxx.xxx.xxx.xxx Bcast:xxx.xxx.xxx.xxx Mask:xxx.xxx.xxx.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:68620 errors:0 dropped:0 overruns:0 frame:0
TX packets:45782 errors:0 dropped:0 overruns:60 carrier:0
collisions:29821 txqueuelen:100
RX bytes:73725865 (70.3 Mb) TX bytes:12988879 (12.3 Mb)
Interrupt:30

eth1 Link encap:Ethernet HWaddr
inet addr:10.0.0.50 Bcast:10.0.0.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4488 errors:0 dropped:0 overruns:0 frame:0
TX packets:2505 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:100
RX bytes:734304 (717.0 Kb) TX bytes:265288 (259.0 Kb)
Interrupt:29 Base address:0x2000

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:6969 errors:0 dropped:0 overruns:0 frame:0
TX packets:6969 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1097647 (1.0 Mb) TX bytes:1097647 (1.0 Mb)

방법 2) Usage : ifconfig eth0 [ip] netmask 0xffffff00 broadcast + up
$ ifconfig eth0 xxx.xxx.xxx.xxx netmask 0xffffff00 broadcast + up

* Gateway 변경

방법 1)
$ netstat -rn (네트워크 상태 확인)
$ route add default [gateway ip] (게이트웨이 추가)
$ vi /etc/sysconfig/network
[gateway ip]

방법 2)
$ vi /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=node1 # 호스트 네임
GATEWAY=xxx.xxx.xxx.xxx

$vi /etc/sysconfig/static-routes
eth0 net xxx.xxx.xxx.0 netmask 255.255.255.0 gw xxx.xxx.xxx.xxx
eth1 net 10.0.0.0 netmask 255.255.255.0 gw 10.0.0.1

* 리눅스 DNS 변경

방법)
$ vi /etc/resolv.conf
domain xxxx.com
nameserver xxxx.xxx.xx.1
nameserver xxx.xxx.xx.2
nameserver xxx.xxx.xx.xxx


* 모든 작업을 종료하고 network restart 한다.

$ /etc/rc.d/init.d/network stop
$ /etc/rc.d/init.d/network start

수요일, 10월 11, 2006

OS별 패키지 설치 요약

* Linux (www.rpmfind.net)
* 설치
rpm -Uvh 설치패키지
* 설치확인
rpm -qa | grep 설치 패키지
* 삭제
rpm -e 패키지명

* SunOS (www.sunfreeware.com)
* 설치
pkgadd 패키지
* 설치확인
pkginfo | grep 패키지
* 삭제
pkgrm 패키지

* HPUX (hpux.connect.org.uk, www.hp.com)
* 설치
swinstall /절대경로/패키지
* 설치확인
swlist | grep 패키지
* 삭제
swremove 패키지

GNU 소프트웨어 설치하거나 컴파일 해야하는 경우에는
gmake, gcc, automake, autoconf, 기본적으로 4가지 패키지를 설치하고 작업하시면
대부분의 소프트웨어들을 설치됩니다. 설치하시는 패키지의 필요에 따라서 더 설치하시면 됩니다.

월요일, 9월 11, 2006

java execl에 내용 읽어오기.

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

Workbook workbook = Workbook.getWorkbook(new File("fileName"));
Sheet sheet = workbook.getSheet(0); //0번째 시트
for (int i=1; i < sheet.getRows() ; i++ )
{
totalCount++;
Cell[] cells = sheet.getRow(i);
}

* 참고 사이트
http://jxl.sourceforge.net/

Struts 1.1 File upload

다음은 동적 개수의 파일을 업로드 하는 예제이다 (** Struts 1.1 정식 부터는 위와 같은 배열로도 가능하다.!!)

1.입력 Page

<form action=""/upload.do" enctype="multipart/form-data" method="post">
<input name="file[0]" size="20" type="file">
<input name="file[1]" size="20" type="file">
<input value="OK" type="submit">


2.ActionForm private Vector vector = new Vector();

public FormFile getFile(int i) { return (FormFile)vector.elementAt(i); }
public void setFile(int i, FormFile f) { vector.add(i, f); }


3.Action
Class public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {

ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward(); // return value
InputForm inputForm = (InputForm) form;
try {
FormFile file1 = inputForm.getFile(0);
FormFile file2 = inputForm.getFile(1);
save(file1); save(file2); }
catch (Exception e) { e.printStackTrace(); }

forward = mapping.findForward("result");
return (forward); }

private void save(FormFile file) {
byte[] buffer = new byte[2048];
FileOutputStream fos = null;
System.out.println(file.getFileName());
try {
fos = new FileOutputStream(new File("d:\\" + file.getFileName()));
BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
int size = 0;
while ((size = bis.read(buffer)) != -1)
fos.write(buffer, 0, size);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fos != null)
try {
fos.close();
} catch(Exception e2)
{}
}
}


------
구글에서 찾은 내용입니다.

요약하면
1. Form에는 FormFile 형태로 선언해야함.
2. action에서 file.getInputStream()으로 하면 받은 파일내용을 읽을 수 있음.
3. file.getFileName() 파일 이름을 알 수 있음.

Struts 1.1 File upload

다음은 동적 개수의 파일을 업로드 하는 예제이다 (** Struts 1.1 정식 부터는 위와 같은 배열로도 가능하다.!!)

1.입력 Page

/upload.do" enctype="multipart/form-data" method="post">





2.ActionForm private Vector vector = new Vector();

public FormFile getFile(int i) { return (FormFile)vector.elementAt(i); }
public void setFile(int i, FormFile f) { vector.add(i, f); }


3.Action
Class public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {

ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward(); // return value
InputForm inputForm = (InputForm) form;
try {
FormFile file1 = inputForm.getFile(0);
FormFile file2 = inputForm.getFile(1);
save(file1); save(file2); }
catch (Exception e) { e.printStackTrace(); }

forward = mapping.findForward("result");
return (forward); }

private void save(FormFile file) {
byte[] buffer = new byte[2048];
FileOutputStream fos = null;
System.out.println(file.getFileName());
try {
fos = new FileOutputStream(new File("d:\\" + file.getFileName()));
BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
int size = 0;
while ((size = bis.read(buffer)) != -1)
fos.write(buffer, 0, size);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fos != null)
try {
fos.close();
} catch(Exception e2)
{}
}
}


------
구글에서 찾은 내용입니다.

요약하면
1. Form에는 FormFile 형태로 선언해야함.
2. action에서 file.getInputStream()으로 하면 받은 파일내용을 읽을 수 있음.
3. file.getFileName() 파일 이름을 알 수 있음.