'분류 전체보기'에 해당되는 글 122건

  1. 2008.08.29 ref-NICspeedconfiguration 1
  2. 2008.08.29 ref_ethernet
  3. 2008.08.29 ref_icmp
  4. 2008.08.29 ref_ipmp
  5. 2008.08.29 ref_ndd
  6. 2008.08.29 product
  7. 2008.08.29 product
  8. 2008.08.28 c++ . 상속-1 . inheritance
  9. 2008.08.27 c++ pointer object arry
  10. 2008.08.25 c++ . static
  11. 2008.08.22 c++ this . const .
  12. 2008.08.21 c++ , 생성자 / 소멸자
  13. 2008.08.20 c++/ 객체 지향
  14. 2008.08.19 c++/filedivision
  15. 2008.08.18 c=+
  16. 2008.08.18 c++
  17. 2008.08.16 gdb
  18. 2008.08.11 국회의원을 꿈꾸는 정직한청년입니다.나라당 공천가능할까요? 1
  19. 2008.08.11 꼴깝떤다
  20. 2008.08.11 Chapter 9. 원격 접속과 파일전송
  21. 2008.08.08 Chapter 8. 프로세스 관리
  22. 2008.08.08 Chapter 7. Korn Shell Characteristic
  23. 2008.08.07 Chapter 6. Vi 편집기
  24. 2008.08.07 Chapter 5. Unix Basic Commands _ 아카이브/압축 관련 명령어
  25. 2008.08.07 Chapter 5. Unix Basic Commands _ 링크 관련 명령어
  26. 2008.07.22 Chapter 5. Unix Basic Commands _ 파일/디렉토리 검색 관련 명령어
  27. 2008.07.22 Chapter 5. Unix Basic Commands _ 자주 사용되지는 않는 명령어
  28. 2008.07.21 Chapter 5. Unix Basic Commands _ 파일 속성 정보 변경 명령어
  29. 2008.07.21 Chapter 5. Unix Basic Commands _ 사용자와 통신할때 사용하는 명령어
  30. 2008.07.21 Chapter 5. Unix Basic Commands _ 기타 관리용 명령어
2008. 8. 29. 17:36

ref-NICspeedconfiguration



  Network Interface Parameter Administration



INDEX
____________________________________________________

1. NIC(Network Interface Card) Instance Name
2. Network Interface Parameter Configuration Problem
3. Network Interface Parameter Configuration
4. Network Interface Status Verification
5. Driver Parameters, Status
6. Auto-Negotiation
7. Reference URL



1. NIC(Network Interface Card) Instance Name
_______________________________________________

썬에서 지원하는 NIC 인스턴스 이름은 다음과 같다. 아래의 NIC 인스턴스 이름은 솔라리
스10 버전을 기준으로 작성되었다.

-----------------------------------------------------------------------------------
NIC     Description
-----------------------------------------------------------------------------------
bge - SUNW,bge Gigabit Ethernet driver for Broadcom BCM57xx
ce - Cassini Gigabit-Ethernet device driver
chxge - Chelsio Ethernet network interface controllers
dmfe - Davicom Fast Ethernet driver for Davicom DM9102A
dnet - Ethernet driver for DEC 21040, 21041, 21140 Ethernet cards
elxl - 3Com Ethernet device driver
eri - eri Fast-Ethernet device driver
ge - GEM Gigabit-Ethernet device driver
hme - SUNW,hme Fast-Ethernet device driver
ipge - PCI-E Gigabit-Ethernet device driver for Intel 82571?based ethernet
   controller.
ixgb - SUNWixgb, 10 Gigabit Ethernet driver for Intel 82597ex controllers
   and Sun Kirkwood adapters
nge - Nvidia ck8-04 Gigabit Ethernet driver
nxge - Sun 10/1 Gigabit Ethernet network driver
pcelx - 3COM EtherLink III PCMCIA Ethernet Adapter
pcn - AMD PCnet Ethernet controller device driver
qfe - SUNW,qfe Quad Fast-Ethernet device driver
rge - Realtek Gigabit Ethernet Network Adapter driver
rtls - Realtek Fast Ethernet 8139?based network interface controllers
sk98sol - SysKonnect Gigabit Ethernet SK-98xx device driver
spwr - SMC EtherPower II 10/100 (9432) Ethernet device driver
xge - Neterion Xframe 10Gigabit Ethernet Network Adapter driver
-----------------------------------------------------------------------------------

위의 표는 다음을 참고 하였습니다.
http://docs.sun.com
Solaris 10 Reference Manual Collection
>> man pages section 7: Device and Network Interfaces
>> Device and Network Interfaces



2. Network Interface Parameter Configuration Problem
________________________________________________________

서버의 Network Interface는 기본적으로 Auto Negotiation 기능이 활성화 되어 허브의 포
트와 동기화 되게 된다. 10/100/1000, Half/Full Duplex에 맞게 설정이 된다. 하지만 이
기능(Auto Negotiation) 없는 장비나 또는 다른 이유로 하여 Negotiation을 하지 못하는
경우가 존재한다. 이런 경우 Network Interface가 활성화 되지 않거나 다운로드 속도가
엄청 느리게 된다. 이 경우에는 Auto Negotiation 기능을 사용하지 말고 연결된 장비의
설정에 맞추어 수동으로 설정하여야 한다.

만약 아래와 같이 서로 통신하는 방식이 틀리게 설정이 된경우 파일 다운로드 속도는 현
저하게 떨어지게 된다. Server 쪽의 NIC가 10/100Mbps를 지원하고 Half/Full Duplex을 지
원하는 인터페이스라면 HUB의 Port쪽은 당연히 100M로 설정이 될것이다. 그럼 Server 쪽
도 100M 설정이 될것이다. 하지만 Auto Neg. 설정이 비정상적으로 동작하게 되어서 설정
이 잘못되는 경우가 발생할 수 있다. 이런 경우 네트워크 통신이 원할하게 진행되지 않는
다.

해결책은 HUB에 콘솔 케이블을 연결하고 HUB Port 설정을 NIC쪽에 맞추던지, NIC를 HUB
Port쪽에 맞추어 주어야 한다. 아니면 둘다 설정을 고정으로 맞추어 주면 된다.


       [HUB] Port ---------------------- NIC [Server]
            Auto Neg.                    Auto Neg.
            100M Full Duplex             10M Half Duplex

             [그림] NIC Auto Negotiation 문제


link mode   전송모드 half / full duflex
lind speed  전송속도 10/100/1000m

3. Network Interface Parameter Configuration
_______________________________________________

다음은 hme Interface에 관련해 설정하는 예를 들었다.

(1). How to Network Interface Device Driver Parameter Configuration

방식은 3가지가 존재한다.
- ndd 명령어를 사용하는 방법
- /etc/system 파일을 사용하는 방법
- hme.conf 파일을 사용하는 방법


(2). ndd 명령어를 사용하는 방법

ndd 명령어를 통해서 hme 인터페이스에 관해서 (a)Autho Negotiation Mode로 동작을 시킬
수도 있고 Local Transceiver를 (b)Force Mode로 설정할 수도 있다.


(a) Auto Negotiation Mode로 동작시키는 방법

다음의 패러미터 중 한개이상의 1로 설정이 되어야 한다.
* adv_100T4_cap
* adv_100fdx_cap
* adv_100hdx_cap
* adv_10fdx_cap
* adv_10hdx_cap

위의 패러미터 중 한개이상의 1이 설정이 되면, 1로 설정된 값을 Link Partner에게 전달
하게 된다. Link Partner도 이 전달된 값을 참고하여 우선순위가 높은 가장 좋은 방법을
택하게 된다. 우선순위는 가장 성능이 잘 나는 형태가 높다.

10,100은 전송속도이고 T4, fdx, hdx는 전송모드이다.

(예) 100Mbps Full-duplex로 사용할 경우
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg_cap 1
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 1
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 0

(예) 100 Mbps half-duplex 로 사용할 경우
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg_cap 1
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 0
ndd -set /dev/hme adv_100hdx_cap 1
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 0

(예) 10Mbps full-duplex 로 사용할 경우
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg_cap 1
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 0
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 1
ndd -set /dev/hme adv_10hdx_cap 0

(예) 10Mbps half-duplex로 사용할 경우
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg 1
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 0
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 1


(b) Local Transceiver Force Mode로 동작시키는 방법

다음의 패러미터 중 한개가 설정이 되어야 한다.
* adv_100T4_cap
* adv_100fdx_cap
* adv_100hdx_cap
* adv_10fdx_cap
* adv_10hdx_cap

(예) 100Mbps Full-duplex로 사용할 경우
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg_cap 0
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 1
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 0

(예) 100 Mbps half-duplex 로 사용할 경우
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg_cap 0
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 0
ndd -set /dev/hme adv_100hdx_cap 1
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 0

(예) 10Mbps full-duplex 로 사용할 경우
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg_cap 0
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 0
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 1
ndd -set /dev/hme adv_10hdx_cap 0

(예) 10Mbps half-duplex로 사용할 경우
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg 0
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 0
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 1


(c) 설정을 부팅시에도 적용하기 위해서 스크립트 생성

ndd 명령어로 설정한 값은 리부팅이 되면 없어지는 값이 된다. 그래서 부팅시에 실행할수
있도록 Startup Script을 생성하여 설정 하면된다.

# vi /etc/init.d/nddset.sh
----------------------------------------
#!/sbin/sh
ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg_cap 0
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 1
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 0
----------------------------------------
# ln -s /etc/init.d/nddset /etc/rc2.d/S98nddset


(d) Instance Number

만약 NIC가 여러개 존재하는 경우 각 네트워크 인터페이스마다 설정을 해야 한다.
instance의 기본값은 0이다. 0은 첫번째 인터페이스를 나타낸다.

다음은 NIC가 2개 존재하는 경우 Force Mode, 100Mbps, Full-duplex로 설정하는 예이다.

ndd -set /dev/hme instance 0
ndd -set /dev/hme adv_autoneg_cap 0
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 1
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 0

ndd -set /dev/hme instance 1
ndd -set /dev/hme adv_autoneg_cap 0
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 1
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 0

ndd -set /dev/hme instance 2
ndd -set /dev/hme adv_autoneg_cap 0
ndd -set /dev/hme adv_100T4_cap 0
ndd -set /dev/hme adv_100fdx_cap 1
ndd -set /dev/hme adv_100hdx_cap 0
ndd -set /dev/hme adv_10fdx_cap 0
ndd -set /dev/hme adv_10hdx_cap 0



(3). /etc/system 파일을 사용하는 경우

/etc/system 파일을 설정하는 것도 (a)Autho Negotiation Mode로 동작을 시킬수도 있고
Local Transceiver를 (b)Force Mode로 설정할 수도 있다. ndd 명령어를 사용하는 방법과
거의 흡사하다. 설정하는 패러미터의 이름만 약간 틀릴뿐이다. /etc/system 파일은 부팅
시에 커널에 의해 읽혀지는 파일이므로 설정 후 적용하기 위해서 반드시 리부팅을 해야
한다.

다음은 /etc/system 파일에 Force Mode로 설정한 예이다.


(예) 10MB full duplex로 설정
set hme:hme_adv_autoneg_cap=0
set hme:hme_adv_100T4_cap=0
set hme:hme_adv_100fdx_cap=0
set hme:hme_adv_100hdx_cap=0
set hme:hme_adv_10fdx_cap=1
set hme:hme_adv_10hdx_cap=0

(예) 10MB half duplex로 설정
set hme:hme_adv_autoneg_cap=0
set hme:hme_adv_100T4_cap=0
set hme:hme_adv_100fdx_cap=0
set hme:hme_adv_100hdx_cap=0
set hme:hme_adv_10fdx_cap=0
set hme:hme_adv_10hdx_cap=1

(예) 100MB full duplex로 설정
set hme:hme_adv_autoneg_cap=0
set hme:hme_adv_100T4_cap=0
set hme:hme_adv_100fdx_cap=1
set hme:hme_adv_100hdx_cap=0
set hme:hme_adv_10fdx_cap=0
set hme:hme_adv_10hdx_cap=0

(예) 100MB half duplex로 설정
set hme:hme_adv_autoneg_cap=0
set hme:hme_adv_100T4_cap=0
set hme:hme_adv_100fdx_cap=0
set hme:hme_adv_100hdx_cap=1
set hme:hme_adv_10fdx_cap=0
set hme:hme_adv_10hdx_cap=0


(4). hme.conf 파일을 사용하는 방법

이 부분에 관해서는 생략한다. 다음 문서를 참고하기 바란다.
http://docs.sun.com/source/816-2348-10/paramset.html#pgfId-640749



4. Network Interface Status Verification
__________________________________________

테스트는 hme 인터페이스를 예로 들었습니다.

(1). dmesg 명령어를 사용하여 현재 Network Interface의 스피드 설정 확인

# dmesg | grep hme
...
Oct  1 17:42:03 atmsw-27 genunix: [ID 936769 kern.notice] hme0 is
                            /sbus@1f,0/SUNW,hme@e,8c00000Oct
Oct  1 17:42:07 atmsw-27 hme: [ID 517527 kern.notice] SUNW,hme0 :
                            Internal Transceiver Selected.Oct 
Oct  1 17:42:07 atmsw-27 hme: [ID 517527 kern.notice] SUNW,hme0 :
                            Auto-Negotiated  100 Mbps Half-Duplex Link Up


(2). ndd 명령어를 사용하여 현재 Network Interface의 스피드 설정 확인

# ndd /dev/hme \?
# ndd -set /dev/hme instance 0
# ndd -get /dev/hme link_speed
1
# ndd -get /dev/hme link_mode
1

* link_speed가 0 이면 10Mbps, 1 이면 100Mbps이다. link_mode가 0 이면 half-duplex,
  1 이면 full-duplex이다.

* 만약 한개의 hme 인터페이스가 더 존재한다면 다음과 같이 instance을 1로 설정하여 점
  검하면 된다. 만약 또 다른 hme가 존재한다면 instance을 2로 설정하여 점검하면 된다.
  아무런 설정이 없는 경우 기본값인 instance는 0이다.

# ndd -set /dev/hme instance 1
# ndd -get /dev/hme link_speed
1
# ndd -get /dev/hme link_mode
1


(3). netstat -k 명령어를 사용하여 현재 Network Interface 스피드 설정 확인

# netstat -k hme0
hme0:
ipackets 317522 ierrors 0 opackets 9790 oerrors 0 collisions 43
defer 0 framing 0 crc 0 sqe 0 code_violations 0 len_errors 0
ifspeed 100000000 buff 0 oflo 0 uflo 0 missed 0 tx_late_collisions 0
retry_error 0 first_collisions 0 nocarrier 0 nocanput 0
allocbfail 0 runt 0 jabber 0 babble 0 tmd_error 0 tx_late_error 0
rx_late_error 0 slv_parity_error 0 tx_parity_error 0 rx_parity_error 0
slv_error_ack 0 tx_error_ack 0 rx_error_ack 0 tx_tag_error 0
rx_tag_error 0 eop_error 0 no_tmds 0 no_tbufs 0 no_rbufs 0
rx_late_collisions 0 rbytes 141596475 obytes 1237354 multircv 0 multixmt 9
brdcstrcv 307824 brdcstxmt 59 norcvbuf 0 noxmtbuf 0   newfree 0
ipackets64 317522 opackets64 9790 rbytes64 141596475 obytes64 1237354 align_errors 0
fcs_errors 0   sqe_errors 0 defer_xmts 0 ex_collisions 0
macxmt_errors 0 carrier_errors 0 toolong_errors 0 macrcv_errors 0
link_duplex 0 inits 12 rxinits 0 txinits 0 dmarh_inits 0
dmaxh_inits 0 link_down_cnt 0 phy_failures 0 xcvr_vendor 524311
asic_rev 193

- ifspeed 패러미터는 100Mbps을 의미한다.
- link_duplex는 half-duplex을 의미한다.



5. Driver Parameters, Status
_______________________________

hme 인터페이스에 대한 예를 들었다.

-----------------------------------------------------------------------------------
Parameter          Status           Description
-----------------------------------------------------------------------------------
transceiver_inuse  Read only        Defines the current status
link_status        Read only        Defines the current status
link_speed         Read only        Defines the current status
link_mode          Read only        Defines the current status
ipg1               Read and write   Inter-packet gap parameter
ipg2               Read and write   Inter-packet gap parameter
use_int_xcvr       Read and write   Operational mode parameter
pace_size          Read and write   Operational mode parameter
adv_autoneg_cap    Read and write   Operational mode parameter
adv_100T4_cap      Read and write   Operational mode parameter
adv_100fdx_cap     Read and write   Operational mode parameter
adv_100hdx_cap     Read and write   Operational mode parameter
adv_10fdx_cap      Read and write   Operational mode parameter
adv_10hdx_cap      Read and write   Operational mode parameter
autoneg_cap        Read only        Local transceiver auto negotiation capability
100T4_cap          Read only        Local transceiver capability of the hardware
100fdx_cap         Read only        Local transceiver capability of the hardware
100hdx_cap         Read only        Local transceiver capability of the hardware
10fdx_cap          Read only        Local transceiver capability of the hardware
10hdx_cap          Read only        Local transceiver capability of the hardware
lp_autoneg_cap     Read only        Link partner auto negotiation capability
lp_100T4_cap       Read only        Link partner capability
lp_100fdx_cap      Read only        Link partner capability
lp_100hdx_cap      Read only        Link partner capability
lp_10fdx_cap       Read only        Link partner capability
lp_10hdx_cap       Read only        Link partner capability
instance           Read and write   Device instance
lance_mode         Read and write   Additional delay before transmitting a packet
ipg0               Read and write   Additional delay before transmitting a packet
-----------------------------------------------------------------------------------


(Table) Read-Only Parameters Defining the Current Status
-----------------------------------------------------------------------------------
Parameter          Description                    Values
-----------------------------------------------------------------------------------
link_status        Current link status            0 = Link down
                                                  1 = Link up

transceiver_inuse  Current transceiver status     0= Internal transceiver
                                                  1= External transceiver

link_speed         Valid only if the link is up   0 = 10 Mbps
                                                  1 = 100 Mbps

link_mode          Valid only if the link is up   0 = Half duplex
                                                  1 = Full duplex
-----------------------------------------------------------------------------------


(Table) Read-Write Inter-Packet Gap Parameter Values and Descriptions
-----------------------------------------------------------------------------------
Parameter          Values             Description
                   (Byte-time)
-----------------------------------------------------------------------------------
ipg1               0, 255             ipg1 = 8 (default at initialization)
ipg2               0, 255             ipg2 = 4 (default at initialization)
-----------------------------------------------------------------------------------


(Table) Parameters Defining lance_mode and ipg0
-----------------------------------------------------------------------------------
Parameter    Values   Description
-----------------------------------------------------------------------------------
lance_mode     0      lance_mode disabled
               1      lance_mode enabled (default)

ipg0           0-31   Additional IPG before transmitting a packet (after receiving
                      a packet) -- Note The default value is 16 nibble-times, which
                      is 6.4 microseconds for 10 Mbps and 0.64 microseconds for
                      100 Mbps
-----------------------------------------------------------------------------------


(Table) Operational Mode Parameters
-----------------------------------------------------------------------------------
Parameter          Descrition
-----------------------------------------------------------------------------------
adv_autoneg_cap    Local transceiver capability advertised by the hardware
                   0 = Forced mode
                   1 = Auto-negotiation (default)

adv_100T4_cap      Local transceiver capability advertised by the hardware;
                   read/write parameter
                   0 = Not 100BASE-T4 capable (default)
                   1 = 100BASE-T4 capable

adv_100fdx_cap     Local transceiver capability advertised by the hardware;
                   read/write parameter
                   0 = Not 100 Mbit/sec full-duplex capable
                   1 = 100 Mbit/sec full-duplex capable (default)
 
adv_100hdx_cap     Local transceiver capability advertised by the hardware;
                   read/write parameter
                   0 = Not 100 Mbit/sec half-duplex capable
                   1 = 100 Mbit/sec half-duplex capable (default)
 
adv_10fdx_cap      Local transceiver capability advertised by the hardware;
                   read/write parameter
                   0 = Not 10 Mbit/sec full-duplex capable
                   1 = 10 Mbit/sec full-duplex capable (default)
 
adv_10hdx_cap      Local transceiver capability advertised by the hardware;
                   read/write parameter
                   0 = Not 10 Mbit/sec half-duplex capable
                   1 = 10 Mbit/sec half-duplex capable (default)
 
use_int_xcvr       Local transceiver capability selected for networking by the user
                   0 = External transceiver is used if connected
                   1 = Internal transceiver is used, even if the external transceiver
                       is connected (default)
-----------------------------------------------------------------------------------



(Table) Read-Only Transceiver Capabilities
-----------------------------------------------------------------------------------
Parameter           Descrition
-----------------------------------------------------------------------------------
autoneg_cap         Local transceiver capability of the hardware
                    0 = Not capable of auto-negotiation
                    1 = Auto negotiation capable

100T-4_cap          Local external transceiver capability of the hardware
                    0 = Not 100BASE-T4 capable
                    1 = 100BASE-T4 capable
 
100fdx_cap          Local transceiver capability of the hardware; initialized at
                    startup
                    0 = Not 100 Mbit/sec full-duplex capable
                    1 = 100 Mbit/sec full-duplex capable
 
100hdx_cap          Local transceiver capability of the hardware; initialized at
                    startup
                    0 = Not 100 Mbit/sec half-duplex capable
                    1 = 100 Mbit/sec half-duplex capable
 
10fdx_cap           Local transceiver capability of the hardware; initialized at
                    startup
                    0 = Not 10 Mbit/sec full-duplex capable
                    1 = 10 Mbit/sec full-duplex capable
 
10hdx_cap           Local transceiver capability of the hardware; initialized at
                    startup
                    0 = Not 10 Mbit/sec half-duplex capable
                    1 = 10 Mbit/sec half-duplex capable
 
-----------------------------------------------------------------------------------


(Table)
-----------------------------------------------------------------------------------
Parameter           Values
-----------------------------------------------------------------------------------
lp_autoneg_cap      0 = No auto-negotiation
                    1 = Auto-negotiation
 
lp_100T4_cap        0 = No 100BASE-T4
                    1 = 100BASE-T4
 
lp_100fdx_cap       0 = No 100 Mbit/sec full-duplex transmission
                    1 = 100Mbit/sec full-duplex
 
lp_100hdx_cap       0 = No 100 Mbit/sec half-duplex transmission
                    1 = 100 Mbit/sec half-duplex
 
lp_10fdx_cap        0 = No 10 Mbit/sec full-duplex transmission
                    1 = 10 Mbit/sec full-duplex
 
lp_10hdx_cap        0 = No 10 Mbit/sec half-duplex transmission
                    1 = 10 Mbit/sec half-duplex
 
-----------------------------------------------------------------------------------



6. Auto-Negotiation
______________________

Auto-Negotiation?

Auto-negotiation matches the local device speed and mode with the link partner
capability.

The auto-negotiation protocol does the following.
- Identifies all link partner-supported modes of operation
- Advertises its capabilities to the link partner
- Selects the highest common denominator mode of operation based on the following
  priorities
     (EX) 100BASE-T4  => 100M Full-duplex => 100M Half-duplex =>
          10M Full-duplex => 10M Half-duplex

The link partner is the networking device (system, Ethernet hub, or Ethernet switch)
at the other end of the link or cable.  



7. Reference URL
_____________________

http://docs.sun.com/source/816-2348-10/index.html
http://ntech.in/blog/index.php/post/14
http://www.5gibsons.com/scripts_etc/ce_admin.txt
http://docs-pdf.sun.com/819-3159/819-3159.pdf
http://docs-pdf.sun.com/817-7634-10/817-7634-10.pdf
http://www.tek-tips.com/faqs.cfm?fid=5832
http://oldfaq.phoneboy.com/gurus/200403/msg00057.html
http://sysunconfig.net/unixtips/set_nic_settings.txt
http://www.webservertalk.com/archive103-2006-1-1361811.html
http://www.sun.com/bigadmin/scripts/submittedScripts/network-config.sh.txt
http://www.bsdconsulting.no/tools/netlink
http://www.wowunix.com/cgi-bin/CrazyWWWBoard.cgi?mode=read&num=249&db=solaris&fval
                                         =%C1%B6%C8%B8&backdepth=1

2008. 8. 29. 17:34

ref_ethernet



  Fast Ethernet / Gigabit Ethernet



1. Fast Ethernet
___________________


(1). 개요
패스트 이더넷은 스위치를 중심으로 실제 데이터를 전송한다.이때 스위치는 리피터
기능을 수행하여 송신 시스템으로 부터 오는 모든 신호를 증폭 시킬 수 있으며 동
시에 여러 포트로 부터 오는 모은 수신되는 신호에 대하여 다른 모든 포트로 중계한
다.


(2). 동작
- 패스트 이더넷 네트워크에 참여하는 모든 호스트는 신호를 스위치에게 보내게 된다.
- 스위치는 수신되는 모든 신호를 동시에 해당 수신 시스템에게 전송한다.
- 스위치는 충돌을 감지할 필요가 없는 CSMA/CD Free 방식을 사용한다.


(3). 특징
- 10Mbps NIS을 장착한 시스템도 Fast Ethernet에 접속될수 있다.
- 스타형의 토폴로지를 사용한다.
- 스위치 네트워크의 경우 CAMA/CD Free 방식을 사용한다.
- 일반 패스트 이더넷은 CAMA/CD Backoff 방식을 사용한다.


(4). 종류
[100Base-TX]
- 카테고리 5 UTP 케이블 사용
- 4쌍의 동선 중 2쌍만 사용
- 10Base-T, 100Base-TX 2쌍의 동선을 사용하므로 호환가능하다.

[100Base-T4]
- 카테고리 3,4,5 UTP 케이블 사용
- 4쌍의 동선을 모두 사용

[100Base-FX]
- 2쌍의 다중 모드 광섬유 케이블을 사용
- UTP을 이용하는 이더넷이 광섬유를 사용하는 경우보다 거리 제한이 더 크다.



2. Gigabit Ethernet
_______________________

(1). 개요
IEEE의 표준안 802.3z(1000Base-X)와 802.3ab(1000Base-T) 규격으로 1Gbps의 대용량
대역폭을 제공하며 이더넷 표준과 완벽하게 호환된다.


(2). 특징
- 스타형의 토플로지를 사용한다.
- 전송매체는 광섬유 케이블, UTP를 모두 지원한다.


(3). 종류
[1000Base-LX]
- 1Gbps의 속도, 베이스 밴드 전송
- 2쌍의 장파장 다중모드 또는 단일모드 광섬유 사용 가능

[1000Base-SX]
- 1Gbps의 속도, 베이스 밴드 전송
- 2쌍의 단파장 다중 모드 광섬유를 사용

[1000Base-CX]
- 1Gbps의 속도, 베이스 밴드 전송
- 2쌍의 STP 사용

[1000Base-TX]
- 1Gbps의 속도, 베이스 밴드 전송
- 4쌍 또는 8쌍의 카테고리 5 UTP 사용



2008. 8. 29. 17:34

ref_icmp



  ICMP(Internet Control Messages Protocol)



1. ICMP?
IP 프로토콜의 문제점을 해결하기 위해 생성된 프로토콜로 데이터 전송시 제어 정보 전달
을 위한 프로토콜을 의미한다.

[Ref.] IP 프로토콜의 문제점
송신자 시스템이 수신자 시스템에게 데이터그램을 전송할때 비 연결성에 주안점을 둔 IP
프로토콜은 오류제어와 같은 메커니즘이 없으므로 이로 인해 다음과 같은 데이터 그램 전
송시 문제가 생길수 있다.
- 최종 목적지 도달불가나 호스트 사용불가를 탐지 불가능
- 경로 설정 루프의 오류로 인한 TTL 매캐변수 만료 전달 불가능
- 데이터그램 단편의 사라짐으로 인한 데이터그램이 전달되지 않을 가능성
- 단편화가 혀용되지 않고 데이터그램 크기가 중간 네트워크에 비해 너무 커서 데이터 그
  램을 발송 불가능
- 라우터에서 네트워크 혼잡으로 인한 수신 데이터그램을 처리 할 수 없을 경우가 발생



2. ICMP의 주요 기능
- 모든 IP 구현은 ICMP를 동반해야 한다.
- ICMP는 IP 패킷과 함께 실행된다. 즉 ICMP는 비록 IP 모듈에서 구현되지만 IP의 클라이언
  트라고 할 수 있다.
- ICMP는 오류보고나 제어 목적이지 IP 데이터 패킷을 신뢰할 수 있는 전송을 가능하게 하
  는 것은 아니다.
- ICMP는 첫번째 IP 데이터그램 단편화에 대해서만 오류를 보고한다. 즉, 단편 오프셋 필
  드가 0(zero)으로 설정된 IP 데이터그램 단편만을 보고한다는 의미이다. 나머지 데이터
  그램 단편에 대해 ICMP 메세지를 보내지 않게 하는 것이다.
- ICMP는 IP 데이터그램에 관한 오류보고 메커니즘이지 데이터그램 문제에 관한 오류 메시
  지는 생성하지 않는다.


[Ref.] ICMP 프로토콜 사용시 오류보고를 할수 없는 상황
- ICMP 메시지의 경로 설정 또는 전달시
  ICMP 오류메시지 생성시 메시지 개수가 늘고 네트워크 트래픽 발생 우려가 있다.
- IP 동보전송 또는 다중 전송 데이터그램 전송시
  동보전송이나 다중 전송시 발생하는 ICMP 오류메시지는 브로드캐스팅, 멀티캐스팅 데이터
  그램을 수신하는 각 노드가 ICMP 메시지를 생성하여 네트워크 트래픽 발생 우려
- 데이터링크 계층 동보전송 또는 다중 전송시
  위의 경우와 같음
- 루프백 주소 127.x.x.x 나 0.0.0.0과 같은 고유 IP 노드를 식별하지 않는 출발지 주소
  또는 네트워크 접두어가 0인 주소를 가진 데이터그램 전송시



3. ICMP 구조

송신 시스템에게 IP 전달에 대한 다양한 메시지를 전달하기 위한 프로토콜이다.


(1). 메시지 종류

오류보고 메시지(Error Reporting Messages)
 Type 3 : 목적지 도달 불가
 Type 4 : 발신지 억제
 Type 5 : 경로 재지정
 Type 11: 시간 초과
 Type 12: 매개변수 문제

질의 메시지(Query Messages)
 Type 8 : Echo Request
 Type 0 : Echo Reply
 Type 9 : Router 광고
 Type 10: Router 요청
 Type 13: Timestamp Request
 Type 14: Timestamp Reply
 Type 15: IP 정보 요구(구형)
 Type 16: IP 정보 응답(구형)
 Type 17: 주소마스크 요구
 Type 18: 주소마스크 응답


(2). 메시지 형식

총 8Bytes 헤더로 구성되어 있으며 처음 4Bytes는 모든 ICMP에서 동일하며 나머지 4Bytes
는 조금씩 다르게 구성되어 있다.


+------------+------------+---------------------------------+
|   Type     |    Code    |    Checksum                     |
+-----------------------------------------------------------+
|                Type 별로 다른 부분                        |
+-----------------------------------------------------------+
|                          데이터                           |
+-----------------------------------------------------------+

                   [그림] ICMP 메시지 형식


(3). ICMP & IP 상관 관계

ICMP는 TCP/IP 모델 중 Internet 계층에 속하며 IP 모듈 내 ICMP 모듈이 포함된 형태의 관
계성을 갖는다.

-------------------------------------------
Application Layer        (예) ping 명령어

-------------------------------------------
Transport Layer                |
                               V
-------------------------------------------
Internet Layer               ICMP
                             IP
-------------------------------------------
Network Interface Layer      Packet

-------------------------------------------
Hardware Layer               Signal

-------------------------------------------


(3-1) ICMP 캡슐화

ICMP 메시지는 인터넷과 라우터를 거쳐서 운반되어야 하므로 IP에 의해 캡슐화 되어 진다.
즉, IP가 없으면 상위 계층 프로토콜 데이터는 라우터 경계에 도달할 수 없게 된다. 이는
ICMP 메시지가 IP 데이터 그램의 데이터 부분에 포함된다는 것을 의미한다.

(특징) ICMP는 IP 데이터그램의 일부에 포함
       IP 헤더 중 프로토콜 종류 번호는 1로 명시


                  +-------------------------------------------+
                  |         ICMP 데이터         |
                  +-------------------------------------------+
                                                            
         +--------+-------------------------------------------+
         | IP헤더 |         IP 데이터그램        |
         +--------+-------------------------------------------+
                                                            
+--------+----------------------------------------------------+
|DataLink|                  프레임 데이터        |
|Header  |                      (MTU)                         |
+--------+----------------------------------------------------+

                    [그림] ICMP Encapsulation


(4). ICMP 유형


■ ICMP 유형 8, 0
에코 요청/응답(Echo Request/Reply Header)


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
|   Type=8   |   Code=0   |    Checksum                     |
+-----------------------------------------------------------+
|       Identifier        |    Sequence Number              |
+-----------------------------------------------------------+
|                          데이터                           |
+-----------------------------------------------------------+

                [그림] ICMP Echo Request

Identifire 필드와 Sequence Number 필드는 프로토콜에 의해 전형적으로 정의되지는 않았
으며 송신자에 의해 임의로 사용될 수 있음.


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
|   Type=0   |   Code=0   |    Checksum                     |
+-----------------------------------------------------------+
|       Identifier        |    Sequence Number              |
+-----------------------------------------------------------+
|                          데이터                           |
+-----------------------------------------------------------+

                [그림] ICMP Echo Reply


■ ICMP 유형 3
목적지 미도달(Destination Unreachable)

IP패킷은 최적의 경로를 통해 목적지에 도착하려고 하지만 모든 패킷이 전달되지는 않는다.
일반적인으로 이 경우 패킷이 전달되지 않은 라우터에서 탐지되고 ICMP 유형 3을 출발지
호스트에게 전달한다.


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
|   Type=3   | Code=0~15  |    Checksum                     |
+-----------------------------------------------------------+
|                       Not Used                            |
+-----------------------------------------------------------+
|                          데이터                           |
+-----------------------------------------------------------+

                [그림] Network Unrereachable Messages


코드(Code)는 다음표를 참고하자.

[표] 코드 유형(Code)
----------------------------------------------------------------------------------
Code Description
----------------------------------------------------------------------------------
0 - 하드웨어 고장등의 이유로 네트워크에 도달할 수 없음. 라우터만 생성가능
1 - 호스트에 도달할 수 없음. 라우터에 의해서만 생성 가능
2 - 프로토콜에 도달할 수 없음. 즉, IP 데이터그램이 도착했으나 상위 TCP 프로토
   콜이 수행되지 않고 있다면 이 메시지가 보내짐. 목적지 호스트만 생성 가능
3 - 포트에 도달할 수 없음. 데이터그램이 향하고 있는 응용프로세스가 수행되지
   않고 있음. 목적지 호스트만 생성 가능함.
4 - 단편화가 필요하나 데이터그램의 DF 필드가 설정되어 있음. 즉 다른 네트워크로
   보내기 위해서는 데이터그램을 잘라야 하는데 자를 수 없음.
5 - 발신지 라우팅이 수행될수 없음. 발신지 라우팅 옵션에 정의된 한개 이상의 라
   우터를 방문 할 수 없음(엄격한 소스 라우팅이 설정된 경우에 발생)
6 - 목적지 네트워크가 알려져 있지 않음. 0번과는 다르게 목적지 네트워크에 대한
   정보를 가지고 있지 않은 경우 발생.
7 - 목적지 호스트가 알려져 있지 않음. 0번과는 다르게 목적지 호스트의 존재를 라
   우터가 알고 있지 못하는 경우 발생.
8 - 발신지 호스트가 고립되어 있음.
9 - 목적지 네트워크와의 통신이 관리상의 이유로 금지되어 있음.
10 - 목적지 호스트로의 통신이 관리상의 이유로 금지되어 있음.
11 - 명시된 서비스 유형에 대해 네트워크에 도달할 수 없음.
12 - 명시된 서비스 유형에 대해 호스트에 도달할 수 없음.
13 - 관리자가 필터를 유형에 대해 호스트에 도달할 수 없음.
14 - 호스트 우선순위가 위반되었기 때문에 호스트에 도달할 수 없음. 요청된 우선순
   위가 목적지를 향해서는 허용되지 않을 경우 발생.
15 - 우선순위가 충분히 높지 않아서 호스트에 도달할 수 없음. 네트워크 관리자가
   네트워크의 운용을 위해 우선 순위의 최소값을 설정하였는데 데이터그램의 우선
   순위가 최소값보다 낮을때 발생.
----------------------------------------------------------------------------------


■ ICMP Type 4
출발지 억제(Source Quench)

라우터 집중?

송신시스템이 100Mbps급 이더넷을 통해 라우터로 패킷을 보내지만 라우터 외부 이더넷 인
터페이스가 1.544Mbps 밖에 되지 않는다면 일시적으로 라우터 버퍼는 더 이상 송신 시스템
에서 보내온 패킷을 받지 못한 상태에 빠지게 된다. 이것을 라우터 집중이라고 한다.


해결책

집중현상을 보이고 있는 라우터가 송신자 시스템에게 버퍼가 가득차 더 이상 패킷을 받을
수 없다는 메시지를 보냄으로써 해결할 수 있으며, 이는 ICMP 유형 4를 사용하여 전달하면
된다.


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
|   Type=4   |   Code=0   |    Checksum                     |
+-----------------------------------------------------------+
|                       Not Used                            |
+-----------------------------------------------------------+
|                          데이터                           |
+-----------------------------------------------------------+

                [그림] Route Source Quench



■ ICMP Type 5
라우트 재지정(Route Redirection)

라우터간에 서로 경로 설정표를 주고 받음으로써 경로 설정에 관한 최적의 정보 또는 최
적에 가까운 정보를 갖게 되지만 호스트는 최소한 경로 설정 정보를 갖도록 설계 된다.
이 때 호스트는 데이터그램을 전달하도록 하기 위해 라우터에서 제공하는 최적의 경로로
데이터그램을 전달하도록 하기 위해 라우터에서 제공하는 최적의 경로로 데이터그램을 전
달하려고 하며 라우터가 자기 구간의 부하나 트래픽으로 인해 다른 라우터에게 데이터그
램을 전송하기 위해 생성되는 메시지이다.

라우터가 송신하고자 하는 데이터그램을 좀 더 좋은 경로로 보내기 위해 다수 라우터 중
최적의 라우터를 탐지할 경우 이를 알리고자 위해서다.


                                RIP/OSPF
Internet -------- Router1 ------------------ Router2 --------- Internet
               172.16.8.254       |        172.16.0.1
                                  |
                            HOSTA(172.16.8.XXX)

- RIP(Routing Information Protocol)
- OSPF(Open Shortest Path First)


■ ICMP Type 9
라우터 광고(Route Advertisement)

ICMP 유형 9, 10은 호스트들이 직접 연결된 네트워크의 모든 라우터를 동적으로 발견할
수 있게 해 주는 ICMP 라우터 발견 메커니즘을 구현하기 위해서 사용한다. 라우터가 사용
하는 설정 프로토콜과 상관없이 모든 라우터를 찾을 수 있다.


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
|   Type=9   |   Code=0   |        Checksum                 |
+-----------------------------------------------------------+
| Number of  | Address    |        Life Time                |
| Address    | Entry Size |                                 |
+-----------------------------------------------------------+
|             Router Address 1                              |
+-----------------------------------------------------------+
|             Router Preference 1                           |
+-----------------------------------------------------------+
|             Router Address 2                              |
+-----------------------------------------------------------+
|             Router Preference 2                           |
+-----------------------------------------------------------+
|             .....                                         |
+-----------------------------------------------------------+

                [그림] Route Advertisement


한 세그먼트에 존재하는 호스트들은 기본 게이트웨이 IP 주소를 구성할 필요가 없다. 라우
터는 ICMP 유형 9를 이용하여 매 7분 ~ 10분 간격으로 세그먼트내에 존재하는 시스템에게
메시지를 송부한다.


■ ICMP Type 10
라우터 선택 메시지(Route Solicitation)

ICMP 유형 10 즉, 라우터 선택 메시지는 호스트 시스템이 지역에 존재하는 IP 주소를 획득
하기 위해 사용되어 진다. 호스트가 라우터의 주소를 발견하기 위해 사용한다. 호스트는
같은 세그먼트내에 존재하는 라우터를 발견하기 위해 ICMP 유형 10을 브로드캐스트나 멀
티게스트를 이용하여 전송한다. 그럼 라우터는 이 메시지를 받고, 라우터는 ICMP 유형 9
(라우터 광고 메시지)를 통해 응답한다. 이 때 호스트는 매 7분 ~ 10분 간격으로 부터
ICMP 유형 9 메시지를 받게 된다.


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
|   Type=10  |   Code=0   |    Checksum                     |
+-----------------------------------------------------------+
|       Identifier        |    Sequence Number              |
+-----------------------------------------------------------+
|                          데이터                           |
+-----------------------------------------------------------+

                [그림] ICMP Echo Reply


■ ICMP Type 11
시간 초과(Time Exceeded)

(a) ICMP 시간 초과 메시지 생성 상황(1)
TTL 필드의 원래 설정값이 너무 낮거나 데이터그램의 여행 경로가 너무 길거나 무한 루프
가 발생한 경우에 생성된다.

(b) ICMP 시간 초과 메시지 생성 상황(2)
데이터그램이 단편화 되어 있음에도 불구하고 단편화된 데이터그램이 모두 도달하지 않아
재조립이 불가능한 경우에 생성된다. 특정 데이터그램이 단편화 되면 최종 호스트는 단편
화된 데이터그램에 대해 재조립에 책을을 져야 한다. 단편화된 데이터그램은 개별적으로
라우터를 통과하여 목적지까지 여행을 하게 된다. 만약 특정 단편화된 데이터그램이 경로
여행 중 없어진다면 호스트는 데이터그램을 재조립할 수 없으므로 전체 데이터그램을 삭
제하게 된다.


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
|   Type=11  |  Code=0~1  |    Checksum                     |
+-----------------------------------------------------------+
|                       Not Used                            |
+-----------------------------------------------------------+
|                          데이터                           |
+-----------------------------------------------------------+

                [그림] Time Exceeded

Code 0 : TTL 만료로 인한 시간 초과
Code 1 : 데이터그램의 미도착으로 인한 시간 초과


■ ICMP Type 13, 14
시간 요청, 응답(Timestamp Request / Reply)

IP 노드는 자체의 시계를 유지하고 있다. ICMP 유형 13과 14 메시지는 원격 IP 노드로 부
터 시간을 알아 보기 위해 사용된다. 이는 NTP라는 프로토콜이 존재하지만 가장 단순화된
IP 노드의 시간을 동기화 한다.


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
| Type=13,14 |   Code=0   |    Checksum                     |
+-----------------------------------------------------------+
|       Identifier        |    Sequence Number              |
+-----------------------------------------------------------+
|                 Original Timestamp                        |
+-----------------------------------------------------------+
|                 Receive Timestamp                         |
+-----------------------------------------------------------+
|                 Transmit Timestamp                        |
+-----------------------------------------------------------+

                [그림] Timestamp Request / Reply


Type 필드 13 : 시간 요청
Type 필드 14 : 시간 응답
협정 시계시(UT) 자정으로 부터 계산함. 밀리초 단위로 계산
시작 시간(Original Timestamp)은 송신 호스트에서 지정
수신 시간(Receive Timestamp)은 수신 호스트에서 지정
변화 시간(Transmit Timestamp)은 ICMP 응답 메시지가 출발하는 시점의 시간을 지정


■ ICMP Type 15, 16
정보 요청, 응답(Information Request, Reply)

ICMP 요청 15는 요청 호스트의 IP 주소를 알아내기 위한 거이며, 유형 16은 응답을 되돌려
주기 위해 사용된다. 더이상 사용치 않고 있으며 RFC 1122에서 사용하지 말것 을 권장하고
있다. RARP, BOOTP 또는 DHCP를 사용할 것을 권장하고 있다.

- ICMP 유형 15 : 요청한 호스트 IP 주소를 알기 위함
- ICMP 유형 16 : 요청한 호스트 IP 주소에 대한 응답


■ ICMP Type 17, 18
주소 마스크 요청, 응답(Address Mask Request / Reply)

ICMP 유형 17, 18은 특정 호스트가 요청한 서브넷 마스크를 획득하고 사용하기 위해 생성
된다. 메시지가 생성되는 위치는 호스트이다. 디스크 없는 워크스테이션과 같은 자체 구성
시스템이 부트 할 때 자체의 서브넷 마스크를 발견할 수 있도록 하기 위함.

- ICMP 유형 17 : 요청한 호스트의 서브넷 마스크를 알아 보기 위함
- ICMP 유형 18 : 요청한 호스트의 서브넷 마스크에 대한 응답


    1Bytes       1Bytes                  2Bytes
|<---------->|<---------->|<------------------------------->|
+------------+------------+---------------------------------+
| Type=17,18 |   Code=0   |    Checksum                     |
+-----------------------------------------------------------+
|       Identifier        |    Sequence Number              |
+-----------------------------------------------------------+
|                     Address Mask                          |
+-----------------------------------------------------------+

                [그림] ICMP Address Mask

2008. 8. 29. 17:27

ref_ipmp

          

     
  IPMP(Internet Protocol Multi-Pathing, IP Multi-Pathing)
     



INDEX
_____________________

1. IPMP Feature
2. IPMP Overview
3. IPMP Configuration Type
4. IPMP Implementation
5. Reference



현재 썬에서는 (a)IPMP, (b)Sun Trunking Software 등을 제공함으로써 썬 고객들의 네트워
크 대역폭에 대한 요구를 충족시키고 있다. IPMP Software는 운영체제에 기본 내장 되어
있지만 Sun Trunking Software는 기본 내장되어 있지 않다.



0. IPMP의 필요성
______________________

현재 사용하고 있는 방식의 NIC 카드의 문제점은 Hub, Switch 같은 장치와 연결되는 케이
블에 이상이 있는 경우 서버의 통신은 문제가 발생되게 된다. 그리고 NIC 카드가 노후화로
인해 이상이 있다고 하더라도 문제가 발생된다.

이런 문제점을 해결하기 위해서는 같은 네트워크에 여러개의 네트워크 인터페이스(NIC)를
달고 IPMP 설정을 통해서 높은 대역폭을 제공하면서 각 NIC의 Failover 기능을 수행할 수
있도록 설정하면 문제가 해결된다.


------+-----+-----+-----+-----------------+-----------
      |     |     |     |                 |
      |     |     |     |                 |
  +--qfe0--qfe1--qfe2--qfe3--+          CLINET
  |                          |
  |          SERVER          |
  |                          |
  +--------------------------+

       [그림] IP Multipath Configuration


[Ref.] Sun Trunking Software
Sun Trunking Software는 솔라리스 운영체제에 기본 내장되어 있는 프로그램이 아니므로
라이센스 비용을 들여서 사야 한다.

Sun Trunking software is not part of the Solaris OE and must be purchased separately.
Sun Trunking software is an aggregation technology that:

* Up to eight full-duplex ports on two Sun Quad FastEthernet™ (qfe) adapters to 
  obtain 800-Mbps full-duplex performance
* Links up to two full-duplex ports on a Sun™ Gigabit Ethernet Adapter (ge) to
  obtain 2-Gbps full-duplex performance between a Sun server and a Sun Trunking
  compatible switch.


                        SERVER

                       ||||||||
                       ||||||||
                       ||||||||        Network links are aggreagted
                       ||||||||  ----> in to a fat network pipe.
                       ||||||||
                       ||||||||
                       ||||||||

                        Switch

                           |
   ------------------------+---------------------------
         |       |       |       |       |      |
       ClientA ClientB ClientC ClientD ......



1. IPMP Feature
______________________

솔라리스 9버전부터 내장되기 시작했는데 9버전이 나올당시에 출시 되었던 8버전에도 기술
이 내장되었다.


(1). IPMP Feature

■ Eliminates a single network adapter as a single point-of-failure in these cases:
   * Network adapter failure detection (failover)
   * Network adapter repair detection  (failback)

■ Provides outbound load spreading when traffic is flowing to multiple destinations.

■ Enables interfaces to failover within approximately 10 seconds when using the
   default configuration.

■ Can be configured by adjusting the parameters in the /etc/default/mpathd file.

■ Can be configured for both IPv4 and IPv6.

■ Allows interfaces to be configured as Standby Interfaces. These types of
   interfaces are only used for failover and are not used for outbound load
   spreading, unless they are explicitly chosen by an application.


(2). IPMP Requirements

■ The Solaris 8 10/00 OE, as a minimum.

■ Unique media access control (MAC) addresses must be configured on each network
   interface.

   - The default configuration for most Sun network adapters has all network
     interfaces on a specific server using the same MAC address.
   - IPMP requires that all interfaces exist on the same network. Switched
     configurations use MAC addresses when making network decisions.
   - Therefore, you must change the system’s default configuration for MAC
     addresses to avoid a MAC address conflict.

■ Multiple network adapter interfaces must be connected on each subnet.
   - You can configure IPMP with a single network interface to take advantage of
     network failure detection. To use the full benefit ofIPMP, make sure that two
     or more network interfaces are connected to the same subnet.

■ A network adapter group name must be assigned to IPMP interfaces.

   - Interfaces that are to be deployed as multipath interfaces must belong to a
     multipath group. The in.mpathd multipath process uses the multipath group.
     Use a meaningful name that does not include spaces when you choose a group
     name. The multipath name is local to the system and is not used across the
     network.

■ A test address is assigned to an interface.

   - The multipath process uses test addresses, which must be routable addresses,
     to monitor the status of each individual interface. Use the test addresses to
     detect failure and recovery of an interface. These addresses are deprecated at
     configuration time to make sure that they cannot be used to pass network
     traffic from other applications.

■ Additional hosts must exist on the same subnet.

    - The test interfaces use ICMP echo request, reply, or both to hosts that they
      reach by addressing the 224.0.0.1 multicast group or the default router, as
      listed in the /etc/defaultrouter file.


솔라리스 8 10/00(2000.10) 버전부터 이 기능이 내장 되었습니다.
■ SUNWcsr(운영체제 core 패키지)에 포함되어 있습니다.
■ 각 NIC는 유일한 MAC 주소를 가져야 한다.
■ in.mpathd 데몬의해서 동작 된다.
■ 각 NIC에 Test Address가 존재해야 한다.
■ Test NIC는 각 NIC와 224.0.0 또는 동일한 Default router 접근할수 있
  어야 한다.


(3). Interface Failure Detection and Repair

The in.mpathd process can detect both the failure and the repair of an interface by:

* Sending and receiving ICMP echo requests and responses through the interface.
* Monitoring the internal IFF_RUNNING flag on the interface.



2. IPMP Overview
_______________________

IPMP는 다음과 같은 2가지 기능을 갖습니다.
- Failover
- Failback

(1). Failover
는 하나의 시스템에 여러개의 NIC(Network Interface Card)를 사용할때 NIC 카드를
Grouping 해서 그 중 하나의 NIC가 통신 실패(Fail)하는 경우 이를 점검하고 정상적인
다른 NIC로 Failover 해 주는 기능입니다.

(2). Failback
장애(통신 실패, Fail)가 발생한 NIC를 복구한 후(Failover 기능), 관리 자의 특별한 설
정 없이 자동으로 원래 설정으로 돌려 주는 기능입니다.



3. IPMP Configuration Type
______________________________

IPMP를 설정 하는 방법은 다음과 같이 2가지가 존재합니다.
- Standby NIC 갖는 환경     (Active-Standby)
- Standby NIC 갖지 않는 환경(Active-Active)


(1). Standby NIC 갖는 IPMP 환경
서비스를 하는 NIC와 서비스를 하지 않는 NIC를 그룹으로 묶고(Grouping) 실제 서비스를
하지 않는 NIC로 서비스를 하고 있는 NIC에 대해 Failover 기능을 제공해 주기 위한 환경
입니다. 다시 말해서 서비스를 안정적으로 가지고 가기 위해서 백업 NIC를 갖는 것과 같
습니다.


(2). Standby NIC 갖지 않는 IPMP 환경
그룹으로 묶여있는 NIC들이 네트워크 서비스를 각각하고 있다가 그룹내의 NIC 하나가 통신
실패(Fail)이 발생한 경우 남아있던 정상적인 NIC로 Failover 하는 환경입니다. 다시 말해
서 서비스를 안정적으로 가지고 가기 위해서 그룹내의 모든 NIC가 활성화 상태에 있다가
하나의 NIC가 이상이 있지만 다른 NIC가 정상 서비스를 하는 것입니다.


(3). 두 가지 방법의 차이점
<Standby NIC 갖지 않는 IPMP 환경>
- 그룹내의 하나의 NIC가 이상이 있는 경우(통신 실패가 있는 경우) 다른 NIC가 다른 NIC
  들이 서로 Failover 기능을 제공한다.

<Standby NIC 갖는 IPMP 환경>
- 그룹내의 NIC 중 Standby NIC가 서비스 NIC의 Failover 기능을 제공하지만 반대로
  Standby NIC에 대한 Failover 기능은 제공되지 않는다.


[Ref.] Failover, Failback 기능을 사용하기 위해서는 Test NIC(Logical Interface) 필요
<Standby NIC 갖지 않는 IPMP 환경>
- 그룹내 모든 NIC에 Test NIC(Logical Interface) 필요
 
<Standby NIC 갖는 IPMP 환경>
- Test NIC(Interfaec)로만 설정한다.



4. IPMP Implementation
______________________________

(1). Standby NIC 갖는 IPMP 설정

    +=======HOSTA=======+
    |                   |
    |               hme0   (192.168.8.100)
    |               hme0:1 (192.168.8.101)
    |
    |               hme1   (192.168.8.200)
    |               hme1:1 (192.168.8.201)
    |                   |
    +===================+

    Grouping : hme0, hme1 (testgroup)
    Test NIC : hme0:1(For hme0), hme1:1(For hme1)



(현재 설정)
# cat /etc/release
솔라리스 8 버전 이상(Solaris 8 10/00 이상)

# eeprom local-mac-address?=true

# ifconfig hme0 down unplumb
# ifconfig hme1 down unplumb

# ifconfig hme0 plumb 192.168.8.100 group testgroup up
# ifconfig hme0 addif 192.168.8.101 deprecated -failover up
(# ifconfig hme0 addif 192.168.8.101 deprecated netmask + broadcast + -failover up)

# ifconfig hme1 plumb 192.168.8.200 group testgroup up
# ifconfig hme1 addif 192.168.8.201 deprecated -failover up
(# ifconfig hme1 addif 192.168.8.201 deprecated netmask + broadcast + -failover up)

# pgrep -lf in.mpathd

(주의) 만약 in.mpathd 데몬이 떠 있지 않은 경우 띄워 준다.
# ps -ef | grep in.mpathd
# /sbin/in.mpathd


-------------------------- Solaris 9 x86 on VMWare TEST ---------------------------
[EX] Active-Active IPMP 설정(Solaris 9 x86 on VMWare)

    +=======HOSTA=======+
    |                   |
    |               pcn0   (192.168.8.100)
    |               pcn0:1 (192.168.8.101)
    |
    |               pcn1   (192.168.8.200)
    |               pcn1:1 (192.168.8.201)
    |                   |
    +===================+

    Grouping : pcn0, pcn1 (testgroup)
    Test NIC : pcn0:1(For pcn0), pcn1:1(For pcn1)


0. 전제 조건
- NIC 2장 모두 NAT Device에 연결한다.


1. 작업 순서
- NIC1 -> (Bridge -> NAT)
- IPMP 설정
 pcn0   (192.168.10.100)
 pcn0:1 (192.168.10.101)
 pcn1   (192.168.10.200)
 pcn1:1 (192.168.10.201)
- TEST

(a) NIC1 (Bridge -> NAT)

(b). IPMP Configuration
# cat /etc/release
                         Solaris 9 9/05 s9x_u8wos_05 x86
           Copyright 2005 Sun Microsystems, Inc.  All Rights Reserved.
                        Use is subject to license terms.
                            Assembled 01 August 2005

# ifconfig pcn0 down unplumb
# ifconfig pcn1 down unplumb

# ifconfig pcn0 plumb 192.168.10.100 group testgroup up
# ifconfig pcn0 addif 192.168.10.101 deprecated -failover up

# ifconfig pcn1 plumb 192.168.10.200 group testgroup up
# ifconfig pcn1 addif 192.168.10.201 deprecated -failover up

# pgrep -lf in.mpathd


(c). TEST

(At Clinet)
# ping -s 192.168.10.100
-> 메세지 확인

(At Server)
# if_mpadm -d pcn0
-> Clinet 확인
# ifconfig -a
-> pcn0 설정 값 확인

# if_mpadm -r pcn0
-> Client 확인
# ifconfig -a
-> pcn0 설정 값 확인

(At Client)
# ping -s 192.168.10.200

(At Server)
# if_mpadm -d pcn1
-> Client 확인
# ifconfig -a
-> pcn1 설정 값 확인

# ip_mpadm -r pcn0
-> Client 확인
# ifconfig -a
-> pcn0 설정 값 확인

------------------------------------------------------------------------------------




(부팅시 설정)
# cat /etc/release
# eeprom local-mac-address?=true

# cat /etc/hosts
.....
192.168.8.100      solaris100        # Data address for hme0
192.168.8.101      solaris100-hme0   # hme0:1 Test address for hme0
192.168.8.200      solaris200        # Data address for hme1
192.168.8.201      solaris200-hme1   # hme1:1 Test address for hme1


# cat /etc/hostname.hme0
192.168.8.100 broadcast + netmask + group testgroup up \
addif 192.168.8.101 deprecated netmask + broadcast + -failover up

# cat /etc/hostname.hme1
192.168.8.200 broadcast + netmask + up group testgroup \
addif 192.168.8.201 deprecated netmask + broadcast + -failover up


* 192.168.8.XXX or solarisXXX    Assigns the address associated with the solarisXXX
                                 name.

* netmask +                      Looks up the mask in the netmasks database.

* broadcast +                    Results in a default broadcast address appropriate
                                 for the address and netmask.

* group testgroup                Assigns testgroup as the name for a IPMP group.

* up                             Marks the interface as “up,” and initializes the
                                 hardware.

* addif 192.168.8.XXX            Creates the next unused logical interface, and
                                 assigns it the IP address associated with the
                                 solarisXXX-hmeX name.

* deprecated                     Marks the address as a deprecated address.
                                 Addresses that are marked as deprecated are not
                                 used as source addresses for outbound packets
                                 unless either there are no other addresses
                                 available on this interface or the application is
                                 bound to this address explicitly. The output from
                                 the ifconfig -a command shows DEPRECATED as
                                 one of the flags associated with this interface.

* -failover                      Marks the address as a non-failover address.
                                 Addresses that are marked in this way do not fail
                                 over when the interface fails. The output from the
                                 ifconfig -a command shows NOFAILOVER as
                                 one of the flags associated with this interface.


(2). Test (Failover, Failback)


    ======= HOSTA =======      |      ======= HOSTB =======
         Active    hme0 -------|------hme0  # ping -s HOSTA       
                   hme0:1      |
         Active    hme1 -------|
                   hme1:1      |
    =====================      |      =====================

(a). HOSTB에서 HOSTA로 ping 명령어에 -s 옵션을 사용하여 hme0(192.168.8.100)
     으로 연속적인 ICMP echo reply 신호를 받는다.
(b). HOSTA에서 hme0의 NIC의 LAN 선을 뽑는다.
(c). HOSTB에서 계속된 ping 시도가 되고 있는지 확인한다.
     (잠시 끊김현상이 발생하기는 하지만 바로 복구되는 것을 확인한다.)
(d). HOSTA에서 ifconfig 명령어를 사용하여 hme0에 대한 IP 설정값을 확인한다.
     (0.0.0.0 으로 설정된것을 확인할수 있다.)
(e). 잠시후에 HOSTA에서 ifconfig 명령어를 사용하여 hme0에 대한 IP 설정값을
     확인한다.(Failback 기능으로 인해 IP가 원래대로 설정이 돌아 온것을 확인
     한다.)
   


(3). Standby NIC를 갖는 IPMP 설정

(현재 설정)
부팅시의 설정 사항을 보면 알수 있을 것이다.

(부팅시 설정)
* /etc/hostname.hme0
192.168.8.100 netmask + broadcast + group testgroup deprecated -failover up

* /etc/hostname.hme1
192.168.8.200 netmask + broadcast + group testgroup up \
addif 192.168.8.201 deprecated netmask + broadcast + standby up


(4). Test(Failover, Failback)
테스트도 "4.(2)" 테스트와 비슷하게 수행한다.



5. /etc/default/mpathd & in.mpathd
____________________________________


The starting of the in.mpathd daemon is controlled by the
TRACK_INTERFACES_ONLY_WITH_GROUPS parameter in the
/etc/default/mpathd file.

If the TRACK_INTERFACES_ONLY_WITH_GROUPS variable is set to yes, the
ifconfig utility’s group option starts the in.mpathd process
automatically. That is, as soon as you use the ifconfig utility with the
group option in the command, the in.mpathd process starts. If the
TRACK_INTERFACES_ONLY_WITH_GROUPS variable is set to no, the
/etc/rcS.d/S30network.sh run control script starts the in.mpathd
process at boot time.

# cat /etc/default/mpathd
#
#pragma ident   "@(#)mpathd.dfl 1.2     00/07/17 SMI"
#
# Time taken by mpathd to detect a NIC failure in ms. The minimum time
# that can be specified is 100 ms.
#
FAILURE_DETECTION_TIME=10000
#
# Failback is enabled by default. To disable failback turn off this option
#
FAILBACK=yes
#
# By default only interfaces configured as part of multipathing groups
# are tracked. Turn off this option to track all network interfaces
# on the system
#
TRACK_INTERFACES_ONLY_WITH_GROUPS=yes



6. TEST 하기 위한 명령어
_________________________

To verify the system’s failover configuration, or to change the operational
status of IPMP interfaces, use the if_mpadm utility. You can use this utility
to take an interface offline (detach), by forcing a failover, and verifying
that an alternate interface takes over as expected. If configuration errors
occur, they appear at this stage. Also, use the if_mpadm utility to reattach
a detached interface.

# if_mpadm -d hme0  (Detach an online interface)
# if_mpadm -r hme0  (Reattach an offline interface)

[Ref.] 메세지 모니터링을 위해서 console window를 띄어 놓고 테스트 하면 좋다.
# dtterm -C &



7. Reference
________________

Sun Book : Network Administration for the Solaris 9 Operating Environment
           (SA-399) "Modules 6" Reference

2008. 8. 29. 16:39

ref_ndd

 

                                         

 

                     ndd CMD

 

 

 

 

 

1. ndd Overview

__________________

 

get and set driver configuration parameters

 

     ndd gets and sets selected configuration parameters in  some

     kernel  drivers.  Currently,  ndd  only supports the drivers

     that implement the TCP/IP  Internet  protocol  family. Each

     driver  chooses  which parameters to make visible using ndd.

     Since these parameters are usually tightly  coupled  to  the

     implementation,  they  are  likely to change from release to

     release. Some parameters may be read-only.cl

 

     If the -set option is omitted, ndd queries the named driver,

     retrieves the value associated with the specified parameter,

     and prints it. If the  -set  option  is  given,  ndd  passes

     value,  which  must  be  specified, down to the named driver

     which assigns it to the named parameter.

 

     By convention, drivers that support ndd also support a  spe-

     cial  read-only  parameter  named ``?'' which can be used to

     list the parameters supported by the driver.

 

ndd 명령어를 통해 많은 네트워크 설정값을 설정할 수 있다. 하지만 ndd 명령어로 설정한

값은 부팅시에는 적용되지 않고 현재 적용만된다. 부팅시에도 적용하도록 설정하기 위해

서는 /etc/init.d/inetinit 시작 스크립트를 사용해도 되고 또는 /etc/rc2.d 디렉토리에

개인적인 시작 스크립트를 생성하여 기능을 추가해도 된다.

 

 

 

 

 

2. 네트워크 장치 & 프로토콜

 

(1). 네트워크 프로토콜

 

/dev/arp

/dev/rarp

/dev/icmp

/dev/tcp

/dev/ip

 

 

(2). 네트워크 장치

 

/dev/hme

/dev/qfe

 

 

(3). 사용예

 

# ndd /dev/arp \?

# ndd /dev/rarp \?

# ndd /dev/icmp \?

# ndd /dev/tcp \?

# ndd /dev/ip \?

 

 

 

 

 

3. ndd 명령어

___________________

 

(3.1) 기본사용법

 

ndd [ -get | -set ] /dev/ip [ \? | ip_forwarding ]

                      /dev/arp

 

# ndd /dev/ip \?

# ndd -get /dev/ip \?

 

# ndd /dev/ip ip_forwarding

# ndd -get /dev/ip ip_forwarding

 

# ndd -set /dev/ip ip_forwarding 1

 

 

 

(3.2) 대표적인 인자(Driver Parameter)

 

# ndd -get /dev/ip ip_forwarding

0                    IP Forwarding : Off

1                    IP Forwarding : On

 

# ndd -get /dev/hme link_speed

0                    NIC Link Speed : 10Mbps

1                    NIC Link Speed : 100Mbps

 

# ndd -get /dev/hme link_mode

0                    NIC Link Mode : Half Duplex

1                    NIC Link Mode : Full Duplex

 

# ndd –get /dev/hme link_status

0                    NIC is down

1                    NIC is up

 

# ndd –get /dev/hme instance

0                    NIC 1st

1                    NIC 2nd

2                    NIC 3rd

...

 

Instance NIC카드 넘버

 

[참고] Virtual Interface Number

To set more than 256 virtual ip addresses. By default solaris can have 256 virtual

ip addresses per interface. This default can be be change using this command.

 

# ndd -get /dev/ip ip_addrs_per_if

256

 

# ndd -set /dev/ip ip_addrs_per_if <Number>    (Number 1 ~ 8192)

 

 

 

 

 

 

 

 

2008. 8. 29. 15:57

product

#ifndef _PRODUCT_H_
#define _PRODUCT_H_
#include"date.h"

class Product:public Date
{
public:
 Product(char *pN, char *fN, int _price, int _year, int _month, int _day);
 ~Product();
 void OutProduct()const;
 Product(const Product &pro) ;
private:
 char *p_name;
 char *f_name;
 int price;
};

#endif
--

//#include"date.h"
#include"product.h"
#include<iostream>

using std::cout;
using std::endl;

Product::Product(char *pN, char *fN, int _price, int _year, int _month, int _day):Date(_year, _month,_day)
{
 p_name = new char[strlen(pN)+1];
 strcpy(p_name,pN);
 f_name = new char[strlen(fN)+1];
 strcpy(f_name,fN);
 price = _price;
}
Product::~Product()
{
 delete []p_name;
 delete []f_name;
}
void Product::OutProduct()const
{
 cout<<"\t\t******** 상품정보 ******** "<<endl;
 cout<<"상품명 : "<<p_name<<endl;
 cout<<"제조사 : "<<f_name<<endl;
 cout<<"가  격 : "<<price<<endl;
 cout<<"제조 년/월/일 : "<<GetYear()<<'/'<<GetMonth()<<'/'<<GetDay()<<'/'<<endl;
}
Product::Product(const Product &pro) : Date(pro.GetYear(), pro.GetMonth(), pro.GetDay())
{// Date(pro)
 p_name = new char[strlen(pro.p_name)+1];
 strcpy(p_name,pro.p_name);
 f_name= new char[strlen(pro.f_name)+1];
 strcpy(f_name,pro.f_name);
 
 price= pro.price;
}

--

#ifndef _DATE_H_
#define _DATE_H_

class Date
{
public:
 Date(int _year, int _month, int _day);
 int GetYear()const;
 int GetMonth()const;
 int GetDay()const;
private:
 int year, month, day;
};

#endif


--

#include"date.h"

Date::Date(int _year, int _month, int _day)
{
 year=_year;
 month=_month;
 day=_day;
}
int Date::GetYear()const
{
 return year;
}
int Date::GetMonth()const
{
 return month;
}
int Date::GetDay()const
{
 return day;
}


--





#include<iostream>
#include"date.h"
#include"product.h"

int main()
{

 Product p("새우깡","농심",700,2005,3,4);
 Product p1("새우깡","농심",700,2005,3,4);
 Product p2 =p1;
 
 p.OutProduct();
 p1.OutProduct();
 p2.OutProduct();
 
 return 0;
}

2008. 8. 29. 15:57

product

#ifndef _PRODUCT_H_
#define _PRODUCT_H_
#include"date.h"

class Product:public Date
{
public:
 Product(char *pN, char *fN, int _price, int _year, int _month, int _day);
 ~Product();
 void OutProduct()const;
 Product(const Product &pro) ;
private:
 char *p_name;
 char *f_name;
 int price;
};

#endif
--

//#include"date.h"
#include"product.h"
#include<iostream>

using std::cout;
using std::endl;

Product::Product(char *pN, char *fN, int _price, int _year, int _month, int _day):Date(_year, _month,_day)
{
 p_name = new char[strlen(pN)+1];
 strcpy(p_name,pN);
 f_name = new char[strlen(fN)+1];
 strcpy(f_name,fN);
 price = _price;
}
Product::~Product()
{
 delete []p_name;
 delete []f_name;
}
void Product::OutProduct()const
{
 cout<<"\t\t******** 상품정보 ******** "<<endl;
 cout<<"상품명 : "<<p_name<<endl;
 cout<<"제조사 : "<<f_name<<endl;
 cout<<"가  격 : "<<price<<endl;
 cout<<"제조 년/월/일 : "<<GetYear()<<'/'<<GetMonth()<<'/'<<GetDay()<<'/'<<endl;
}
Product::Product(const Product &pro) : Date(pro.GetYear(), pro.GetMonth(), pro.GetDay())
{// Date(pro)
 p_name = new char[strlen(pro.p_name)+1];
 strcpy(p_name,pro.p_name);
 f_name= new char[strlen(pro.f_name)+1];
 strcpy(f_name,pro.f_name);
 
 price= pro.price;
}

--

#ifndef _DATE_H_
#define _DATE_H_

class Date
{
public:
 Date(int _year, int _month, int _day);
 int GetYear()const;
 int GetMonth()const;
 int GetDay()const;
private:
 int year, month, day;
};

#endif


--

#include"date.h"

Date::Date(int _year, int _month, int _day)
{
 year=_year;
 month=_month;
 day=_day;
}
int Date::GetYear()const
{
 return year;
}
int Date::GetMonth()const
{
 return month;
}
int Date::GetDay()const
{
 return day;
}


--





#include<iostream>
#include"date.h"
#include"product.h"

int main()
{

 Product p("새우깡","농심",700,2005,3,4);
 Product p1("새우깡","농심",700,2005,3,4);
 Product p2 =p1;
 
 p.OutProduct();
 p1.OutProduct();
 p2.OutProduct();
 
 return 0;
}

2008. 8. 28. 15:52

c++ . 상속-1 . inheritance

--------------------------------------------------------------------------------------
human.h
--------------------------------------------------------------------------------------

#ifndef _HUMAN_H_

#define _HUMAN_H_

class Human
{
public:
 void SetHuman(char *sN, int _sage);
 const char* GetName()const ;
 int GetAge() const;
protected:
 
private:
 char name[20];
 int age;
};

class Student:public Human
{
public:
 void SetStudent(char *pN, int _age, int _id, int _score);
 void ShowStudent() const;
private:
 int id;
 int score;
};

#endif



--------------------------------------------------------------------------------------
human.cpp
--------------------------------------------------------------------------------------
#include<iostream>
#include"human.h"

using std::cout;
using std::endl;

void Student::SetStudent(char *pN, int _age, int _id, int _score)
{
 //strcpy(name,pN);
 //age=_age;
 SetHuman(pN,_age);
 id=_id;
 score=_score;  
}
//상수화된 함수에서는 일반함수의 호출이 불가능
//상수화된 함수만 호출 할 수 있다.
void Student::ShowStudent()const
{
 cout<<GetName()<<"\t"<<GetAge()<<"\t"<<id<<"\t"<<score<<endl;
}


void Human::SetHuman(char *sN, int _sage)
{
 strcpy(name,sN);
 age=_sage;
}
//상수화된 함수에서는 멤버 변수의 주소 리턴이 불가능
//포인터가 가리키는 값을 상수화 시켜서 리턴하면 가능
const char* Human::GetName()const
{
 return name;
}
int Human::GetAge()const
{
 return age;
};


--------------------------------------------------------------------------------------
main.cpp
--------------------------------------------------------------------------------------
#include <iostream>
#include"human.h"
using std::cout;
using std::endl;
 
/************************************************
    다음과 같은 클래스를 디자인해보자.
 
    1. Human클래스
 
       - protected 멤버변수 : 이름, 나이       
         
    2. Student클래스 : Human클래스 상속
   
       - private 멤버변수 : 학번, 점수         
       - public 멤버함수 : SetStudent - 이름, 나이, 학번, 점수 초기화                         
                           ShowStudent - 이름, 나이, 학번, 점수 출력                         
     
    3. 파일분할하여 프로그램을 작성한다.
************************************************/
 

int main()
{
    Student s1, s2, s3; //객체생성
    s1.SetStudent("김수현", 25, 1111, 100); //초기화 함수 호출
    s2.SetStudent("장동건", 27, 1112, 90);
    s3.SetStudent("김태희", 32, 1113, 50);
   
    s1.ShowStudent(); //출력함수 호출
    s2.ShowStudent();
    s3.ShowStudent();
    return 0;
}

2008. 8. 27. 15:58

c++ pointer object arry

/********     객체 포인터       *********/

#include<iostream>

using std::cout;
using std::endl;
using std::cin;


class A
{
public:
 A(int _a,int _b)
 {
  a=_a;
  b=_b;
 }
 void show()
 {
  cout<<"a= "<<a<<", b= "<<b<<endl;
 }
private:
 int a,b;
};

int main()
{
 A *p[5];   // A 타입의 객체를 가리키는 포인터배열 5개
 
 for(int i=0;i<5;i++)
 {
  int a,b;
  cout<<"정수 두개입력 : ";
  cin >> a>>b;
  p[i] = new A(a,b*10);
 }

 for(i=0;i<5;i++)
 {
  p[i]->show();
 }
 
 for( i=0;i<5;i++)
 {
  delete p[i];
  // delete []p 는 []<- 이 가리키는 타입이 배열일경우 사용
 }

 return 0;
}


#include<iostream>

using std::cout;
using std::cin;
using std::endl;


class Telephone
{
public:
 Telephone(char *pN, char *pH)
 {
  strcpy(name,pN);
  strcpy(pnum,pH);

 }
 void showdata()
 {
  cout<<"이   름: "<<name<<"\t전화번호 : "<<pnum<<endl;
 }

private:
 
 char name[20];
 char pnum[20];
};

int main()
{
 Telephone *T[5];

 cout<<" ** 전화번호 입력 **"<<endl;

 for(int i=0;i<5;i++)
 {
  char name[20];
  char pnum[20];

  cout<<"이름 : ";
  cin>>name;
  cout<<"전화번호:";
  cin>>pnum;
  T[i]= new Telephone(name,pnum);
 }
 
 for(i=0;i<5;i++)
 {
  T[i]->showdata();
 }

 for(i=0;i<5;i++)
 {
  delete T[i];
 }


 return 0;
}

2008. 8. 25. 15:54

c++ . static


#ifndef _STUDENT_H_
#define _STUDENT_H_

class Student
{
public:
 //생성자 선언
 Student(char *pN, int _age);
 void OutStudentInfo() const;
 //정적 멤버 함수
 static void OutStudentCount();

private:
 char pn[20];
 int age;
 
 //멤버함수 상수화
 const int id;
 
 static int cnt;
 
};

#endif


------------------------------------------------------------------------
// student.cpp
------------------------------------------------------------------------
#include<iostream>
#include<string.h>
#include"student.h"

using std::cout;
using std::endl;
//   정적 멤버
//1. main 함수가 생성 되기 전에 메모리 할당 된다.
//2.객체 생성과 관계없이 사용할 수 있다.
//3. 클래스 내에 선언 되었지만 클래스 멤버가 아니다.
//4. 정적 멤버 변수의 초기화는 외부에서만 된다.
//5. 정적 멤버 외부 정의시 static 은 선언부에만
//6. 정적 멤버 함수는 정적 멤버 변수만 접근 가능하다.
//   (일반 멤버 변수는 접근 불가능 - const 멤버함수가 될 수 없다.)
////////////////////////////////////////////////////

//정적 멤버 초기화.
int Student::cnt=0;
void Student::OutStudentCount()
{


 cout<<"전체 학생수는 "<< cnt<<"입니다\n"<<endl;
}

//생성자 정의
Student::Student(char *pN, int _age):id(20041111+cnt)
{
 strcpy(pn,pN);
 age = _age;
 //학번 = 20041111+cnt;
 ++cnt;
}

void Student::OutStudentInfo() const
{
 cout<<"학번 : "<< id<<endl;
 cout<<"이름 : "<< pn << endl;
 cout<<"나이 : "<< age<<endl;
 cout<<"\n\n\n"<<endl;
}

------------------------------------------------------------------------
// main.cpp
------------------------------------------------------------------------
/*
    아래의 main함수가 수행될 수 있는 Student클래스를 구현해보자.
    
    - 학생정보는 학번, 이름, 나이로 구성된다.    
    - 학번은 20041111부터 차례로 1씩 증가 하도록 생성자에서 구현한다.
    
    - 멤버함수
        OutStudentCount : 전체 학생수를 출력
        OutStudentInfo :  학생정보를 출력
*/

 
#include <iostream>
#include "student.h"
using std::cout;
using std::cin;
using std::endl;

int main()
{
    Student st1("이순신", 25);
    Student st2("아무개", 38);
 
    Student::OutStudentCount();
 
    Student st3("홍길동", 29);
 
    Student::OutStudentCount();
 
    st1.OutStudentInfo();
    st2.OutStudentInfo();
    st3.OutStudentInfo();
 
    return 0;
}


2008. 8. 22. 15:42

c++ this . const .

/***************************
    this포인터
         
    - 객체선언 시 멤버 변수만 각각 할당되며, 멤버 함수는 공유한다.
      때문에 멤버 함수 호출 시 어떤 객체가 멤버 함수를 호출했는지 알 수 있도록
      함수의 인자로 객체의 주소를 전달한다.
       
    - 때문에 모든 클래스의 멤버 함수는 객체의 주소를 받을 수 있는 포인터를 인자로
      가지고 있어야 하는데 이 포인터 변수를 this포인터라 한다.
       
    - 즉, this포인터는 멤버 함수를 호출한 객체의 주소를 가리키는 포인터다.
***************************/


#include <iostream>
using std::cout;
using std::cin;
using std::endl;
 
class MyClass
{
public:   
    void Set(int _i, int _j) //void Set(MyClass *this, int _i, int _j)                            
    {
        i = _i;
        j = _j;
    }
 
    void Out() //void Out(MyClass *this)
    {
        cout << "i = " << i << ", j = " << j << endl;
    }
private:
    int i, j;
};

 
int main()
{
    MyClass ob;
    ob.Set(1, 10);  //Set(&ob, 1, 10)
    ob.Out();       //Out(&ob);
 
    return 0;
}

-----------------------------------------------------------------------------------------------------
Date.h
-----------------------------------------------------------------------------------------------------
#ifndef _DATE_H_
#define _DATE_H_

class Date
{
public:
 Date(int _y, int _m, int _d);
 void OutDate() const;
 int GetYear() const;
 int GetMonth() const;
 int GetDay() const;
private:
 int year;
 int month;
 int day;
};

#endif


-----------------------------------------------------------------------------------------------------
Date.cpp
-----------------------------------------------------------------------------------------------------

#include<iostream>
#include"Date.h"
using std::cout;
using std::endl;
 
Date::Date(int _y, int _m, int _d):year(_y),month(_m),day(_d)
{
}
void Date::OutDate() const
{
 cout<<year<<'/'<<month<<'/'<< day<<endl;
}
int Date::GetYear() const
{
 return year;
}
int Date::GetMonth() const
{
 return month;
}
int Date::GetDay() const
{
 return day;
}
-----------------------------------------------------------------------------------------------------
main.cpp
-----------------------------------------------------------------------------------------------------
#include <iostream>
#include"date.h"
using std::cout;
using std::endl;
using std::cin;

void main()
{   
    Date d1(2007, 3, 5);   
   
    d1.OutDate();
    cout << d1.GetYear() << '/' << d1.GetMonth() << '/' << d1.GetDay() << endl;
}

2008. 8. 21. 15:57

c++ , 생성자 / 소멸자

#include <iostream>
using std::cout;
using std::endl;
using std::cin;
 
//  ******* class 선언******
class T
{
public:
 T();
 T(int a);
 T(int a, double b, char c);
 T(char c);
 T(char *p);
 T(int a, int b, char *p);
};
//  ******* class 멤버함수 외부 정의******
T::T()
{
 cout<<"생성자"<<endl;
}
T::T(int a)
{
 cout<<a<<"생성자"<<endl;
}
T::T(int a, double b, char c)
{
 cout<<a<<' '<<b<<' '<<c<<"생성자"<<endl;
}
T::T(char c)
{
 cout<<c<<"생성자"<<endl;
}
T::T(char *p)
{
 cout<<p<<"생성자"<<endl;
}
T::T(int a, int b, char *p)
{
 cout<<a<<' ' <<b<<' '<<p<<"생성자"<<endl;
}
int main()
{
    T ob, ob2, ob3;   //객체 생성
    T ob4(100);       //객체 생성 시 인수전달
    T ob5(10, 20.34, 'B');
    T ob6('a');
    T ob7;
    T ob8("Hello");
    T ob9(50, 60, "Happy Birthday");
    return 0;
}


/***********************************
    ACC클래스를 다음과 같이 수정해보자.
    - 멤버 변수를 private으로 변경한 후,
 생성자를 추가하여 변수를 초기화 하여라.
************************************/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
 
class ACC
{
private:
    int accId;              //계좌번호
    char pw[5];             //비밀번호
    char name[20];          //이름
    int bal;                //잔액
public:     
 ACC(int ac, char *pW, char *pN ,int money);
    void deposit();         //입금
    void withdraw();        //출금
    void showData();        //잔액조회
};     
 
///////////////////////////////////////////main
int main()
{
    //ACC ac = {1111, "1234", "김수현", 5000}; //객체 생성 후, 초기화
    ACC ac(1111, "1234", "김수현", 5000); //객체 생성 후, 초기화
    ac.showData();  //잔액조회
    ac.deposit();   //입금
    ac.withdraw();  //출금
    ac.showData();  //잔액조회
   
    return 0;
}
 
///////////////////////////////////////////ACC 멤버함수 외부정의
ACC::ACC(int ac, char *pW, char *pN ,int money)
{
 accId =ac;
 strcpy(pw,pW);
 strcpy(name,pN);
 bal=money;
 cout<<"생성자"<<endl;
}

void ACC::deposit()
{
    int m;
   
    cout << "\n입금금액 입력 : ";
    cin >> m;
   
    bal += m;
   
    cout << "\t\t" << m << "원 입금완료~!!\n";
}
 
void ACC::withdraw()
{
    int m;
   
    cout << "\n출금금액 입력 : ";
    cin >> m;
   
    bal -= m;
   
    cout << "\t\t" << m << "원 출금완료~!!\n";
}
 
void ACC::showData()
{
    cout << "\n계좌번호 : " << accId << endl;
    cout << name << "회원님의 잔액은 " << bal << "입니다.\n";
}

-------------------------------------------------------------------------
**********************     Triangle.h


//헤더의 중복을 방지하기 위한 구문
//만약에 _TRIANGLE_H_가 정의 되지 않았다면 #endif까지 수행 아니라면 #endif로 점프
#ifndef _TRIANGLE_H_
// 정의 _TRIANGLE_H_
#define _TRIANGLE_H_
class Triangle
{
private:
 int b,h;
public:
 Triangle(int _b, int _h);
 double GetArea();
};
#endif

********************         Triangle.cpp
#include<iostream>
#include"Triangle.h"

using std::endl;
using std::cout;

//Triangle::Triangle(int _b, int _h)
//생성자에서만 가능한 초기화 방법 -> 콜론(:)을 이용한 초기화
Triangle::Triangle(int _b, int _h):b(_b),h(_h)
{
 /*
 b=_b;
 h=_h;
 */
 cout<<"생성자"<<endl;
}
double Triangle::GetArea()
{
 return (b+h)/2.0;
}

****************************     main.cpp

#include <iostream>
#include"Triangle.h"
using std::cout;
using std::cin;
using std::endl; 
 
/*
    아래와 같은 Triangle클래스를 디자인해보자.
    1. Triangle클래스 디자인
       ▶ private 멤버변수
          밑변, 높이
       ▶ public 멤버함수
          생성자 - 멤버변수 초기화
          GetArea - 삼각형 넓이 리턴
      
    2. 파일분할하여 프로그램을 작성해보자.   
*/


int main()
{
    int base, height;
    cout << "\n *** 삼각형 넓이 구하기 ***\n\n";
    cout << "밑변 : ";
    cin >> base;
    cout << "높이 : ";
    cin >> height;
 
    Triangle tri(base, height); //객체 생성 시 인수 전달
                                //삼각형 넓이 리턴
    cout << "삼각형의 넓이는 " << tri.GetArea() << "입니다.\n";
    return 0;
}


 

2008. 8. 20. 15:44

c++/ 객체 지향

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
/*
    아래와 같은 main함수가 수행될 수 있는 Point클래스를 디자인해보자.
    
    1. Point클래스 디자인       
       ▶ 멤버 변수
          x, y좌표
          
       ▶ 멤버 함수
          SetPoint -  입력 데이터가 0~100사이 좌표라면 멤버변수에 설정하고,
                      좌표 범위를 벗어나면 -1을 저장
          ShowPoint - 멤버변수의 저장된 좌표가 -1이 아니라면 출력하고,
                      -1이면 오류 메시지 출력
          
    2. 클래스 멤버함수는 외부정의한다.
*/

// struct  에서 class 로 넘어가면서 접근 지정자를 설정할 수 잇게 된다.
// default private !!!!!
class Point
{
public:
 //멤버변수
 int x,y;
 //멤버 함수
 void SetPoint(int _x,int _y);
 void ShowPoint();
};

void Point::SetPoint(int _x,int _y)
{
 if(_x>=0 && x<=100 && _y>=0 && _y<=100 )
 {
  x=_x;
  y=_y;
 }
 else
 {
  x=y=-1;
 }
 //0~100 사이 값이 아니라면 -1 셋팅
 
}
void Point::ShowPoint()
{
 if(x==-1)
  cout<<"잘못된좌표정보"<<endl;
 else
 {
  cout << "\n\nx 좌표 : "<<x<<endl;
  cout << "y 좌표 : "<<y<<endl;
 }
}

int main()
{
    int x, y;
    cout << "x 좌표 : ";
    cin >> x;
    cout << "y 좌표 : ";
    cin >> y; 
    Point p;            //클래스 변수 선언
    p.SetPoint(x, y);   //포인터 설정함수 호출
    p.ShowPoint();      //포인터 출력함수 호출
   
    return 0;
}

-----------------------------------------------------------------------------
/* [ 실습과제 3]            
//   UML    -->  class 를 도식화
------------------------------------
  class name
------------------------------------
--------\
attribute
--------\
-년 : int
-월 : int
-일 : int

--------\
method
--------\
+ setdate
+ getdate
------------------------------------
+ public
- private
--------------------------------------------------------------------
  아래와 같은 main함수가 수행될 수 있는 Date클래스를 디자인해보자.
    1. Date클래스 디자인       
       ▶ private 멤버 변수
          년, 월, 일
       ▶ public 멤버 함수
          SetDate - 년, 월, 일 초기화
          GetDate - 년, 월, 일 출력
    2. 파일분할하여 프로그램을 작성한다.
*/
#include<iostream>
using std::cout;
using std::cin;
using std::endl;

class Date
{
private:
 int year, month, day;

public:
 void SetDate(int _y, int _m, int _d);
 void GetDate();

};
void Date::SetDate(int _y, int _m, int _d)
{
 year = _y;
 month = _m;
 day = _d;
}
void Date::GetDate()
{
 cout <<year<<"년 "<<month<<"월 "<<day<<"일 "<<endl;
}

int main()
{
    int year, month, day;
    cout << "년 / 월 / 일 입력 (ex. 2004 3 4) : ";
    cin >> year >> month >> day;
    
    Date date;  //Date 객체생성
    date.SetDate(year, month, day); //날짜 설정함수 호출
    date.GetDate();                 //날짜 출력함수 호출
    return 0;
}

2008. 8. 19. 15:12

c++/filedivision

/*
    아래와 같은 main함수가 수행될 수 있는 Calculator클래스를 디자인해보자.
     1. Calculator클래스 디자인  
       ▶ 멤버 변수
          덧셈연산횟수, 뺄셈연산횟수, 곱셈연산횟수, 나눗셈 연산횟수
       ▶ 멤버 함수
          Init - 멤버변수 초기화
          Sum, Sub, Mul, Div - 각각 덧셈, 뺄셈, 곱셈, 나눗셈 연산
          CountResult - 연산 횟수 출력
          
    2. 클래스 멤버함수는 외부정의한다.
*/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

class Calculator
{
public:
 //멤버 변수, 멤버 변수 선언시 초기화 안된다.(java, c#은됨)
 int sumc, subc, mulc, divc;

 //초기화 함수
 //멤버 함수
 void Init();
 void CountResult();
 double Sum(double _a, double _b);
 double Sub(double _a, double _b );
 double Mul(double _a, double _b);
 double Div(double _a , double _b);
 
};
void Calculator::Init()
{
 sumc=subc=mulc=divc=0;
}
void Calculator::CountResult()
{
 cout<<"\t\t** [연산횟수] **\n"<<endl;
 cout<<"\t\t덧셈  횟수 : "<<sumc<<endl;
 cout<<"\t\t뺄셈  횟수 : "<<subc<<endl;
 cout<<"\t\t곱셈  횟수 : "<<mulc<<endl;
 cout<<"\t\t나눗셈횟수 : "<<divc<<endl;
}
double Calculator::Sum(double _a, double _b)
{
 double sum;
 sum = _a + _b;
 //sumc++;
 ++sumc;//성능상 가장 좋다.
 return sum;
}
double Calculator::Sub(double _a, double _b )
{
 double sub;
 sub = _a - _b;
 subc++;
 return sub;
}
double Calculator::Mul(double _a, double _b)
{
 double mul;
 mul = _a * _b;
 mulc++;
 return mul;
}
double Calculator::Div(double _a , double _b)
{
 double div;
 div = _a / _b;
 divc++;
 return div;
}

int main()
{
    double d1, d2;
 
    cout << "\n\n*** 사칙 연산 프로그램 ***\n";       
    cout << "\n\n두 수 입력 : ";
    cin >> d1 >> d2;     
    
    Calculator ca; //클래스 변수 선언
    ca.Init();     //멤버변수 초기화
    
    cout << endl << endl;
    cout << d1 << " + " << d2 << " = " << ca.Sum(d1, d2) << endl;
    cout << d1 << " - " << d2 << " = " << ca.Sub(d1, d2) << endl;
    cout << d1 << " * " << d2 << " = " << ca.Mul(d1, d2) << endl;
    cout << d1 << " + " << d2 << " = " << ca.Sum(d1, d2) << endl;
    cout << d1 << " * " << d2 << " = " << ca.Mul(d1, d2) << endl;
 
    ca.CountResult(); //연산 횟수 출력   
    return 0;
}

2008. 8. 18. 15:51

c=+

int *p1
p1 = &b[1];


int a ={10,20,30}
int *p[3];    int 형 주소 3개를 담는 배열~?
p[0]= &a[0];

  a[0] a[1]    a[2]
    |   |      |
  p[0]   |   p[1] | p[2]


배열 이름 == 시작 주소

■ 2차원 배열의 특징
배열 이름 == 시작 주소
배열이름[행 ]  -> 행의 시작 주소

// 이차원 배열을 이용한 메모 입력과 출력
// 2008_8_14
#include<iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
 char memo[5][1024];
 // 5 * 1024
 int i=0;

 for(i=0;i<5;i++)
 {
  cout<<"put memo : ";
  // char pointer  = 주소부터 입력한수 널문자까지 ('\0')입력 된


  // cin >> memo ; // 널(공백) 이전까지
  cin.getline(memo[i],1024);
 }

 cout<<"\n\n\t\t________memo";
 for(i=0;i<5;i++)
 {
  // char 포인터 = 주소를 출력 하는게 아니라 주소부터 시작해서

널까지 !
  cout<<memo[i];

 }

}
동적메모리 할당을 이용한 메모체크

// 동적 메모리 할당 - 이차원 배열을 이용한 메모 입력과 출력
#include<iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
 //char memo[5][1024];
 // 5 * 1024
 char buf[1024];
 char *p[5];
 int i=0;
//int *p = new int;
 for(i=0;i<5;i++)
 {
  cout<<"put memo : ";
  // char pointer  = 주소부터 입력한수 널문자까지 ('\0')입력 된


  // cin >> memo ; // 널(공백) 이전까지
  //cin.getline(memo[i],1024);
  cin.getline(buf,1024);

  p[i] = new char[strlen(buf)+1];
  strcpy(p[i],buf);// ?????????????????????
 }

 cout<<"\n\n\t\t________memo";
 for(i=0;i<5;i++)
 {
  // char 포인터 = 주소를 출력 하는게 아니라 주소부터 시작해서

널까지 !
  //cout<<memo[i];
  cout<<p[i]<<endl;
 }

 cout<<"\n\n\t\t________buf";
 for(i=0;i<5;i++)
 {
  delete []p[i];  //    +형식 delete []pointer
  cout<<"동적 메모리 해제\n";
 }
 return 0;
}

// 동적 메모리 할당 - 이차원 배열을 이용한 메모 입력과 출력
#include<iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
 //char memo[5][1024];
 // 5 * 1024
 char buf[1024];
 char *p[5];
 int i=0;
 int llen[5];
 int b=0;

//int *p = new int;
 for(i=0;i<5;i++)
 {
  cout<<"put memo : ";
  // char pointer  = 주소부터 입력한수 널문자까지 ('\0')입력 된


  // cin >> memo ; // 널(공백) 이전까지
  //cin.getline(memo[i],1024);
  cin.getline(buf,1024);

  p[i] = new char[strlen(buf)+1];
  strcpy(p[i],buf);// ?????????????????????
  llen[i] = strlen(buf);
 }
 
 for(i=0;i<4;i++)
 {
  if( llen[i] < llen[i+1])
  {
   llen[0]= llen[i+1] ;
  }
  else
  {
   llen[0]= llen[i];
  }

 }
 cout<<"\n\n\t\t________memo";
 for(i=0;i<5;i++)
 {
  // char 포인터 = 주소를 출력 하는게 아니라 주소부터 시작해서

널까지 !
  //cout<<memo[i];
  cout<<llen[0]<<endl;
 }
 cout<<"\n\n\t\t________buf";
 cout<<"가장긴놈"<<p[b-1]<<endl;

 cout<<"\n\n\t\t________buf";
 for(i=0;i<5;i++)
 {
  delete []p[i];  //    +형식 delete []pointer
  cout<<"동적 메모리 해제\n";
 }
 return 0;
}

int *p = new int;
문자열 동적 할당
 - 포인터가 동적 메모리를 가리켜야 한다.
 - 성능 부담, 잘못된 메모리를 할당할 수 도 있다.
 - 단지 메모리 효울을 위해 쓰인다.
 
 - 길이가 일정한 경우 배열이용
 - 데이터가 적을경우 배열이용

#include <iostream>


using std::cout;
using std::cin;
using std::endl;
 
int main()
{
   
 return 0;
}



레퍼런스-- 별칭??????????
&변수 //선언시
메모리공유


#include <iostream>

using std::cout;
using std::cin;
using std::endl;

struct AAC
{
 int accid;  //계좌번호
 char pw[5];  // 비밀번호
 char name[20]; // 이름
 int bal;  // 잔액
};

void showdata(AAC &a);
void putcash(AAC &a);
void getcash(AAC &a);// &a    레퍼런스 - 메모리 공간의 다른이름을 붙여서 같

이 공유함

int main()
{
 AAC ac={1111, "1234","abc", 50000};

 showdata(ac);
 
 putcash(ac);
 showdata(ac);
 
 getcash(ac);
 showdata(ac);
 
    return 0;
}

void showdata(AAC &a)
{
 
 cout<<"\n\n\n계좌번호 : "<<a.accid<<endl;
 cout<<"잔액     : "<<a.bal<<endl;
}

void putcash(AAC &a)
{
 int temp;
 cout<<"\n\n입금금액 : ";
 cin>>temp;
 a.bal+=temp;
 cout<<temp<<" 원 입금 완료"<<endl;
}
void getcash(AAC &a)
{
 int temp;
 cout<<"\n\n출금 금액 : ";
 cin>>temp;
 a.bal-=temp;
 cout<<temp<<" 원 출금 완료"<<endl;
}

tip. alt +f8  정렬
---------------------------------------------------------------------
class 로 전환
---------------------------------------------------------------------
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

//struct AAC
class AAC
{
public:
 int accid;  //계좌번호
 char pw[5];  // 비밀번호
 char name[20]; // 이름
 int bal;  // 잔액
void showdata()
{
 
 cout<<"\n\n\n계좌번호 : "<<accid<<endl;
 cout<<"잔액     : "<<bal<<endl;
}

void putcash()
{
 int temp;
 cout<<"\n\n입금금액 : ";
 cin>>temp;
 bal+=temp;
 cout<<temp<<" 원 입금 완료"<<endl;
}
void getcash()
{
 int temp;
 cout<<"\n\n출금 금액 : ";
 cin>>temp;
 bal-=temp;
 cout<<temp<<" 원 출금 완료"<<endl;
}
};
/*
void showdata(AAC &a);
void putcash(AAC &a);
void getcash(AAC &a);// &a    레퍼런스 - 메모리 공간의 다른이름을 붙여서 같

이 공유함
*/
int main()
{
 AAC ac={1111, "1234","abc", 50000};

 ac.showdata();
 
 ac.putcash();
 ac.showdata();
 
 ac.getcash();
 ac.showdata();
 
    return 0;
}
/*
void showdata(AAC &a)
{
 
 cout<<"\n\n\n계좌번호 : "<<a.accid<<endl;
 cout<<"잔액     : "<<a.bal<<endl;
}

void putcash(AAC &a)
{
 int temp;
 cout<<"\n\n입금금액 : ";
 cin>>temp;
 a.bal+=temp;
 cout<<temp<<" 원 입금 완료"<<endl;
}
void getcash(AAC &a)
{
 int temp;
 cout<<"\n\n출금 금액 : ";
 cin>>temp;
 a.bal-=temp;
 cout<<temp<<" 원 출금 완료"<<endl;
}*/

---------------------------------------------------------------------
class 로 전환 2
---------------------------------------------------------------------
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

//struct AAC
class AAC
{
public: //struct와 같은 접근을 위해
 //멤버 변수
 int accid;  //계좌번호
 char pw[5];  // 비밀번호
 char name[20]; // 이름
 int bal;  // 잔액
 
 //멤버 함수
 void showdata();
 void putcash();
 void getcash();
};

// 멤버 지정 연산자  ::
//외부함수로 정의할때에는 함수명 앞에 class::멤버함수 형식으로 한다.
void AAC::showdata()
{
 
 cout<<"\n\n\n계좌번호 : "<<accid<<endl;
 cout<<"잔액     : "<<bal<<endl;
}

void AAC::putcash()
{
 int temp;
 cout<<"\n\n입금금액 : ";
 cin>>temp;
 bal+=temp;
 cout<<temp<<" 원 입금 완료"<<endl;
}
void AAC::getcash()
{
 int temp;
 cout<<"\n\n출금 금액 : ";
 cin>>temp;
 bal-=temp;
 cout<<temp<<" 원 출금 완료"<<endl;
}
/*
void showdata(AAC &a);
void putcash(AAC &a);
void getcash(AAC &a);// &a    레퍼런스 - 메모리 공간의 다른이름을 붙여서 같이 공유함
*/
int main()
{
 AAC ac={1111, "1234","abc", 50000};

 ac.showdata();
 
 ac.putcash();
 ac.showdata();
 
 ac.getcash();
 ac.showdata();
 
    return 0;
}
/*
void showdata(AAC &a)
{
 
 cout<<"\n\n\n계좌번호 : "<<a.accid<<endl;
 cout<<"잔액     : "<<a.bal<<endl;
}

void putcash(AAC &a)
{
 int temp;
 cout<<"\n\n입금금액 : ";
 cin>>temp;
 a.bal+=temp;
 cout<<temp<<" 원 입금 완료"<<endl;
}
void getcash(AAC &a)
{
 int temp;
 cout<<"\n\n출금 금액 : ";
 cin>>temp;
 a.bal-=temp;
 cout<<temp<<" 원 출금 완료"<<endl;
}*/

---------------------------------------------------------------------
class 로 전환 lab
---------------------------------------------------------------------


#include <iostream>
using std::cout;
using std::cin;
using std::endl;
 
/*
    아래와 같은 main함수가 수행될 수 있는 Triangle 클래스를 디자인해보자.
    
    1. Triangle클래스 디자인  
      
       ▶ 멤버 변수
          밑변, 높이
       ▶ 멤버 함수
          SetArea - 밑변, 높이 초기화 수행
          GetArea - 삼각형의 넓이 리턴
          
    2. 클래스 멤버함수는 외부정의한다.
*/
class Triangle
{
public:
 //멤버 변수
int ba,he;
 //멤버 함수
//class 내의 멤버 변수와 멤버함수내의 변수명은 중복 되면 안된다.
void SetArea(int a, int b);
double GetArea();

};

void Triangle::SetArea(int a, int b)
{
 ba = a; // 밑변
 he = b; // 높이

}
double Triangle::GetArea()
{
 double area;
 area = ba* he/2.0;
 return area;
}

int main()
{
    int base, height;
    cout << "\n *** 삼각형 넓이 구하기 ***\n\n";
    cout << "밑변 : ";
    cin >> base;
    cout << "높이 : ";
    cin >> height;
 
    Triangle tri; //클래스 변수 선언
    tri.SetArea(base, height); //밑변, 높이 초기화
                                 //삼각형 넓이 리턴
    cout << "삼각형의 넓이는 " << tri.GetArea() << "입니다.\n";
    return 0;
}

2008. 8. 18. 14:39

c++

int *p1
p1 = &b[1];


int a ={10,20,30}
int *p[3];    int 형 주소 3개를 담는 배열~?
p[0]= &a[0];

  a[0] a[1]    a[2]
    |   |      |
  p[0]   |   p[1] | p[2]


배열 이름 == 시작 주소

■ 2차원 배열의 특징
배열 이름 == 시작 주소
배열이름[행 ]  -> 행의 시작 주소

// 이차원 배열을 이용한 메모 입력과 출력
// 2008_8_14
#include<iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
 char memo[5][1024];
 // 5 * 1024
 int i=0;

 for(i=0;i<5;i++)
 {
  cout<<"put memo : ";
  // char pointer  = 주소부터 입력한수 널문자까지 ('\0')입력 된다
  // cin >> memo ; // 널(공백) 이전까지
  cin.getline(memo[i],1024);
 }

 cout<<"\n\n\t\t________memo";
 for(i=0;i<5;i++)
 {
  // char 포인터 = 주소를 출력 하는게 아니라 주소부터 시작해서 널까지 !
  cout<<memo[i];

 }

}
동적메모리 할당을 이용한 메모체크

// 동적 메모리 할당 - 이차원 배열을 이용한 메모 입력과 출력
#include<iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
 //char memo[5][1024];
 // 5 * 1024
 char buf[1024];
 char *p[5];
 int i=0;
//int *p = new int;
 for(i=0;i<5;i++)
 {
  cout<<"put memo : ";
  // char pointer  = 주소부터 입력한수 널문자까지 ('\0')입력 된다
  // cin >> memo ; // 널(공백) 이전까지
  //cin.getline(memo[i],1024);
  cin.getline(buf,1024);

  p[i] = new char[strlen(buf)+1];
  strcpy(p[i],buf);// ?????????????????????
 }

 cout<<"\n\n\t\t________memo";
 for(i=0;i<5;i++)
 {
  // char 포인터 = 주소를 출력 하는게 아니라 주소부터 시작해서 널까지 !
  //cout<<memo[i];
  cout<<p[i]<<endl;
 }

 cout<<"\n\n\t\t________buf";
 for(i=0;i<5;i++)
 {
  delete []p[i];  //    +형식 delete []pointer
  cout<<"동적 메모리 해제\n";
 }
 return 0;
}

// 동적 메모리 할당 - 이차원 배열을 이용한 메모 입력과 출력
#include<iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
 //char memo[5][1024];
 // 5 * 1024
 char buf[1024];
 char *p[5];
 int i=0;
 int llen[5];
 int b=0;

//int *p = new int;
 for(i=0;i<5;i++)
 {
  cout<<"put memo : ";
  // char pointer  = 주소부터 입력한수 널문자까지 ('\0')입력 된다
  // cin >> memo ; // 널(공백) 이전까지
  //cin.getline(memo[i],1024);
  cin.getline(buf,1024);

  p[i] = new char[strlen(buf)+1];
  strcpy(p[i],buf);// ?????????????????????
  llen[i] = strlen(buf);
 }
 
 for(i=0;i<4;i++)
 {
  if( llen[i] < llen[i+1])
  {
   llen[0]= llen[i+1] ;
  }
  else
  {
   llen[0]= llen[i];
  }

 }
 cout<<"\n\n\t\t________memo";
 for(i=0;i<5;i++)
 {
  // char 포인터 = 주소를 출력 하는게 아니라 주소부터 시작해서 널까지 !
  //cout<<memo[i];
  cout<<llen[0]<<endl;
 }
 cout<<"\n\n\t\t________buf";
 cout<<"가장긴놈"<<p[b-1]<<endl;

 cout<<"\n\n\t\t________buf";
 for(i=0;i<5;i++)
 {
  delete []p[i];  //    +형식 delete []pointer
  cout<<"동적 메모리 해제\n";
 }
 return 0;
}

int *p = new int;
문자열 동적 할당
 - 포인터가 동적 메모리를 가리켜야 한다.
 - 성능 부담, 잘못된 메모리를 할당할 수 도 있다.
 - 단지 메모리 효울을 위해 쓰인다.
 
 - 길이가 일정한 경우 배열이용
 - 데이터가 적을경우 배열이용

#include <iostream>


using std::cout;
using std::cin;
using std::endl;
 
int main()
{
   
}

2008. 8. 16. 10:32

gdb

maniacs
psyoblade.egloos.com
Valley | Log-in
gdb 를 통한 디버깅 따라하기 

참고서적 : 유닉스 리눅스 프로그래밍 필수 유틸리티 : vi, make, gcc, gdb, cvs, rpm


1. 우선 컴파일 시에 디버깅 정보를 담아야 한다.
 gcc -g -o [프로그램명] [소스파일명]
 디버깅 옵션인 -g 으로 컴파일하며, 최적화 옵션인 -O 은 주지 않도록 한다.

2. 실행방법
 gdb [프로그램명]
 gdb [프로그램명] [core파일명]
 gdb [프로그램명] [실행중인프로세스pid]

3. 종료방법
 q
 Ctrl + d

4. 소스 찾아가기 (list)
 l   : main 함수를 기점으로 소스의 내용이 출력된다
 l 10  : 10 행 주변의 소스가 출력되는데 10 - 5 행부터 10 + 5행까지 총 10행이 출려된다.
 l func  : func 함수의 소스를 출력
 l -5  : 기본값으로 10줄이 출력된다고 가정하고, 다음에 출력될 라인이 11라인이라면, 10(마지막라인) - 5 라인을 중심으로 출력된다. 즉, 그대로 1~10라인이 출력된다.
 l a.c:func : a.c 파일의 func 함수부분을 출력
 l a.c:10 : a.c 파일의 10행을 기준으로 출력

5. 옵션
 set listsize 20 : 한번에 출력하는 행의 갯수를 20개로 늘린다.
 Enter  : 마지막으로 수행한 명령어를 다시 수행한다

6. 프로그램 실행, 종료 (run, kill)
 r   : 프로그램 수행 (재시작)
 r arg1 arg2 : arg1과 arg2를 인자로 프로그램 수행
 k   : 프로그램 수행종료

7. 역추적하기 (backtrace)
 bt   : 오류가 발생한 함수를 역으로 찾아간다.

8. 중단점 사용하기 (breakpoint, temporary breakpoint)
 b func  : func 함수에 브레이크 포인트 설정
 b 10  : 10행에 브레이크 포인트 설정
 b a.c:func : a.c파일의 func함수에 브레이크 포인트 설정
 b a.c:10 : a.c파일의 10행에 브레이크 포인트 설정
 b +2  : 현재 행에서 2개 행 이후 지점에 브레이크 포인트 설정
 b -2  : 현재 행에서 2개 행 이전 지점에 브레이크 포인트 설정
 b *0x8049000 : 0x8049000 주소에 브레이크 포인트 설정 (어셈블리로 디버깅 시 사용)
 b 10 if var == 0 : 10행에 브레이크 포인트를 설정해되, var 변수 값이 0일 때 작동
 tb   : 임시 중단점을 사용하는 것으로 한번만 설정되며, 그 이후에는 삭제된다.

9. 중단점 설정하기 (condition)
 condition 2 var == 0 : 고유번호가 2번인 브레이크포인트에 var변수가 0일 때 동작하라고 설정

10. 중단점 삭제하기 (clear, delete)
 cl func  : func 함수의 시작 부분에 브레이크 포인트 지움
 cl 10  : 10행의 브레이크 포인트 지움
 delete 1 : 고유번호 1번의 브레이크 포인트를 지운
 cl a.c:func : a.c 파일의 func함수의 브레이크 포인트 지움
 cl a.c:10 : a.c 파일의 10행의 브레이크 포인트 지움
 cl   : 모든 브레이크 포인트 지움

11. 중단점 정보보기 (information)
 info b  : 현재 설정된 브레이크 포인트의 정보를 보여준다
 방향키Up/Down : 방향키 Up/Down을 누르면 히스토리 기능을 제공한다
 info br + TAB : info br 로 시작하는 키워드가 히스토리에 있다면 뿌려준다
 info TAB + TAB : info 뒤에 올 수 있는 인자 리스트를 보여준다
 TAB + TAB  : 현재 사용가능한 모든 명령어 리스트를 보여준다

12. 중단점 비활성화, 활성화 하기 (enable, disable)
 disable 2 : 고유번호 2번인 브레이크 포인트 비활성화
 enable 2 : 고유번호 2번인 브레이크 포인트 활성화

13. 디버깅 하기 (step, next, continue, until, finish, return, step instruction, next instruction)
 s  : 현재 출력된 행을 수행하고 멈추지만, 함수의 경우 함수의 내부로 들어가서 수행된다
 s 5  : s를 5번 입력한 것과 동일
 n  : 현재 행을 수행하고 멈추지만, 함수의 경우 함수를 수행하고 넘어간다
 n 5  : n을 5번 입력한 것과 동일
 c  : 다음 브레이크 포인트를 만날때 까지 계속 수행한다
 u  : for 문에서 빠져나와서 다음 브레이크 포인트까지 수행한다.
 finish : 현재 함수를 수행하고 빠져나감
 return : 현재 함수를 수행하지 않고 빠져나감
 return 123 : 현재 함수를 수행하지 않고 빠져나감, 단, 리턴값은 123
 si  : 현재의 인스트럭션을 수행, 함수 호출 시 내부로 들어간다.
 ni  : 현재의 인스트럭션을 수행, 함수 호출 시 내부로 들어가지 않는다.

14. 감시점 설정 (watch)
 watch i : i변수에 와치포인트를 설정하고 i변수가 바뀔 때마다 브레이크가 걸리면서 이전값과 현재값을 출력한다.

15. 변수 정보보기 (info, print)
 info locals : 현재 상태에서 어떤 지역변수들이 있으며, 값은 어떠한지를 알 수 있다.
 info variables : 현재 상태에서의 전역변수 리스트를 확인할 수 있다.
 p lval  : lval 값을 확인한다.
 p func  : func 함수의 주소값을 확인한다.
 p pt  : pt가 구조체라면 구조체의 주소를 확인한다
 p *pt  : pt가 구조체라면 구조체의 값을 확인한다.
 p **pt  : *pt가 구조체라면 구조체의 값을 확인한다.
 info registers : 레지스트 값 전체를 한번에 확인한다.

16. 레지스트 값 및 포인터가 가리키는 구조체의 배열을 출력 (info, print)
 info all-registers : MMX 레지스트를포함하여 거의 대부분의 레지스트 값을 확인한다.
 p $eax  : eax 레지스트의 값을 확인한다. ( ex_ eax, ebx, ecx, edx, eip )
 p *pt@4  : 4크기의 배열로 gdb가 알 수 있으므로 4개의 크기만큼 가져와서 확인할 수 있다.

17. 중복된 변수명이 있는 경우 특정 변수를 지정해서 출력 (print)
 p 'main.c'::var : main.c 파일에 있는 전역변수인 var 변수의 값을 출력
 p hello::var : hello 함수에 포함된 static 변수인 var 변수의 값을 출력

18. 출력 형식의 지정
 p/t var : var 변수를 2진수로 출력
 p/o var : var 변수를 8진수로 출력
 p/d var : var 변수를 부호가 있는 10진수로 출력 (int)
 p/u var : var 변수를 부호가 없는 10진수로 출력 (unsigned int)
 p/x var : var 변수를 16진수로 출력
 p/c var : var 변수를 최초 1바이트 값을 문자형으로 출력
 p/f var : var 변수를 부동 소수점 값 형식으로 출력
 p/a addr : addr주소와 가장 가까운 심볼의 오프셋을 출력 ( ex_ main + 15 )

19. 타입이 틀릴 경우 타입을 변환하여 출력
 p (char*)vstr : 실제 컴파일 시에 (void *)형으로 되어있었다고 하더라도 (char *)로 캐스팅 하여 보여줌

20. 특정한 위치 지정
 p lstr + 4 : 예를 들어 lstr = "I like you." 라는 문자열은 "ke you."가 출력된다.

21. 변수 값 설정
 p lval = 1000 : 변수값 확인 이외에는 설정도 가능하다.

22. 출력명령 요약 (print)
 p [변수명]    : 변수 값을 출력
 p [함수명]    : 함수의 주소를 출력
 p/[출력형식] [변수명] : 변수 값을 출력 형식으로 출력
 p '[파일명]'::[변수명] : 파일명에 있는 전역변수 값을 출력
 p [함수명]::[변수명] : 함수에 있는 변수 값을 출력
 p [변수명]@[배열크기] : 변수의 내용을 변수 배열의 크기 형태로 출력

23. 디스플레이 명령 (display, undisplay)
 display [변수명]  : 변수 값을 매번 화면에 디스플레이
 display/[출력형식] [변수명] : 변수 값을 출력 형식으로 디스플레이
 undisplay [디스플레이번호] : 디스플레이 설정을 없앤다
 disable display [디스플레이번호] : 디스플레이를 일시 중단한다.
 enable display [디스플레이번호] : 디스플레이를 다시 활성화한다.

24. 스택이란
 스택의 경우는 상위 1기가는 커널에서 사용하며, 그 바로 아래 공간인 상위 0xBFFFFFFF 부터 하위로 늘어나게된다.
 상세한 디버깅을 위해서는 -g 옵션으로 디버깅 정보와 --save-temps 옵션을 통해 어셈블리 코드를 얻어낼 수 있다.
 상위 프레임으로 갈 수록 메인 함수에 가까워 지는 것이다.

25. 스택 프레임 관련 명령 (frame, up, down, info)
 frame [N] : n번 스택 프레임으로 변경
 up   : 상위 프레임으로 이동
 up [N]  : n번 상위 스택 프레임으로 이동
 down  : 하위 프레임으로 이동
 down [N] : n번 하위 스택 프레임으로 이동
 info frame : 현재 스택 프레임 정보를 출력
 info args : 현재 스택 프레임의 함수가 호출될 때 인자를 출력
 info locals : 현재 스택 프레임의 함수내의 지역변수를 출력
 info catch : 현재 스택 프레임의 함수내의 예외 핸들러를 출력

26. 스택 트레이스 하는법
 b main 또는 원하는 곳에 브레이크 포인트를 잡고
 오류가 발생할 때 까지 c를 통해 진행하면, 세그먼트 폴트 등의 오류가 발생하고 디버그가 멈추는데
 여기서 bt 를 통해서 전체 스택 프레임을 확인하고 어떤 함수에서 호출시에 문제가 발생하였는지 확인
 단, 일반적인 라이브러리에서는 오류발생 확률이 없다고 보고, 그 함수를 호출시에 문제를 의심한다.
 다시 프레임을 이동하면서, 로컬변수와 전역변수 등을 확인하면서 디버깅이 가능하다.

27. 메모리 상태 검사 (x)
 x/[범위][출력 형식][범위의 단위] : 메모리의 특정 범위의 값들을 확인할 수 있다.
 이렇게 메모리를 직접 읽어보는 일은 -g 옵션을 가지고 컴파일 되지 않은 실행파일을 디버깅 할때에 자주 사용된다.
 즉, x/10i main 과 같이 역 어셈블하여 해당 코드를 추측하는 것이다.

28. 출력형식
 x/10 main : main 함수 시작부터 40바이트를 출력한다. 출력형식은 다음과 같다.
 x/10t main : main 함수 시작부터 40바이트를 2진수로 출력
 x/10o main : main 함수 시작부터 40바이트를 8진수로 출력
 x/10d main : main 함수 시작부터 40바이트를 부호가 있는 10진수로 출력 (int)
 x/10u main : main 함수 시작부터 40바이트를 부호가 없는 10진수로 출력 (unsigned int)
 x/10x main : main 함수 시작부터 40바이트를 16진수로 출력
 x/10c main : main 함수 시작부터 40바이트를 최초 1바이트 값을 문자형으로 출력
 x/10f main : main 함수 시작부터 40바이트를 부동 소수점 값 형식으로 출력
 x/10a main : 가장 가까운 심볼의 오프셋을 출력
 x/10s main : 문자열로 출력
 x/10i main : 어셈블리 형식으로 출력

29. 범위의 단위 (기본 word - 4바이트)
 x/10b main : byte - 1바이트 단위 - 10바이트 출력
 x/10h main : halfword - 2바이트 단위 - 20바이트 출력
 x/10w main : word - 4바이트 단위 - 40바이트 출력
 x/10g main : giant word - 8바이트 단위 - 80바이트 출력

30. 디스어셈블링 (disas)
 disas func : 어셈블리 코드를 좀 보편적으로 보기 위한 명령어
 disas 0x8048300 0x8048400 : 특정 주소 범위사이의 어셈블리 코드를 보기

31. 함수호출 (call)
 call func(arg1, arg2) : 특정함수 func를 arg1, arg2 파라메터를 포함하여 호출하고, 반환값은 출력

32. 점프 (jump)
 jump *0x08048321 : 해당 주소로 무조건 분기하여 인스트럭션을 계속 수행한다.
 jump 10  : 무조건 10행으로 분기하여 수행한다.
 jump func : func 함수로 무조건 분기하여 수행한다.

33. 시그널 전송 (signal)
 info signals : 보낼 수 있는 시그널의 종류를 확인할 수 있다.
 signal SIGKILL : 디버깅 대상의 프로세스에게 KILL 시그널을 보낼 수 있다.

34. 메모리의 특정 영역에 값을 설정 ( set )
 set {타입}[주소] = [값] : p 명령 대신에 set 을 통해서 메모리의 특정 주소에 저장하는 것이 더 일반적이다
 set {int}0x8048300 = 100 : 해당 주소에 100의 값을 입력한다.

35. gdb 환경설정 (set)
 info set : 변경 가능한 환경설정 정보를 출력한다.
 info functions : 함수들의 리스트를 출력
 info types  : 선언된 타입에 대한 리스트를 출력
 set prompt psyoblade: : 프롬프트를 psyoblade: 로 변경할 수 있다.
 set print array on : 배열을 출력할 때 한 행에 출력하는 것이 아니라 여러 행에 출력한다.

36. 기타 info 를 통해 알 수 있는 정보들
 address         catch           extensions      handle          objects         set             stack           tracepoints
 all-registers   common          files           heap            program         sharedlibrary   symbol          types
 architecture    copying         float           leaks           registers       signals         target          variables
 args            dcache          frame           line            remote-process  source          terminal        warranty
 breakpoints     display         functions       locals          scope           sources         threads         watchpoints
 

2008. 8. 11. 09:23

국회의원을 꿈꾸는 정직한청년입니다.나라당 공천가능할까요?

국회의원을 꿈꾸는 정직한청년입니다.나라당 공천가능할까요?


한나라당 국회의원을 꿈꾸는 엄친아입니다..

현재 국적은 이중국적이고 재산은 부동산 투기와 주가조작으로 300억정도 물려받았습니다™

물론 친일파 후손이구요^^; 외제차도 3대 굴리고 있고 배기량 5000cc 이하는 안탑니다..

집은 버블세븐지역에 각각⑦채 보유하고 있는데 모두 타인명의로 위장전입되어 있습니다..

집안가훈은 정직이고 현재 뉴라이트 교과서에 관여해 일하고 있습니다..

얼마전 부산에 있는 호텔인수했구요. 친동생이 성매매업소 운영중입니다..

부업으론 입당필수 교양과목인 네이버 MB알바로 인턴교육 받는 중인데 알바선배님들이

세뇌교육과 공감조작에 대해 친절하게 가르쳐 주십니다 (우∇익)

어젠 협력업체 노노데모에 견학가서 좌빨과 빨갱이에 대해 특강받고 왔습니다

가장 존경하는 국회의원은 얼짱 전여옥 의원이며 소설가 이문열씨 책을 즐겨 읽습니다..

교회는 주말마다 열심히 다니고 신문은 대대로 조중동만 구독하고 있습니다..

국회의원이 되면 인터뷰할때 여기자 슴가꼭꼭 만저줄꺼구요..

야동싸이트 100곳이상 회원가입되있구요.국회등원하게되면 야동은 책임지겠습니다..

아.. 물론 떡값봉투도 현재 100개가량 만들어 논 상태입니다..

그리고 시간날때마다 대구가서 밤문화 견학하는중이고 종업원한테 재털이 던지기도 잘합니다..

돌아오는길에는 꼭 운주운전하구요..걸리면 도주도 잘합니다..

근데 한가지 걸리는게 집안도 빵빵한데 굳이 현역으로 군복무 한게 좀 걸리네요∴

어떻게 공익이나 면제로 서류위조가 가능한지...

더 치명적인 핸디캡은 제가 아직 전과가 없습니다.ㅠ. 우선 전과기록이 있어야 입당이

더 수월하다는데 병역필에 전과기록까지 없어 엎친데 덮친격입니다>.<

그냥 당당하게 지인들한테 사기치고 다니면서 전과 내공을 쌓아야 할지 막막하네요ㆀ

한나라당만 들어가면 설치류를 내세워도 당선된다길래 꼭 입당하고 싶습니다乃



--------------------------------------------------------------------------

★낭만늑대★님 의 글입니다

 

다음 홈에 그루지야와 러시아 전쟁기사에 올라온 글인데 좀 짱이네요...   [펌]

2008. 8. 11. 09:17

꼴깝떤다

이 대통령 ‘거꾸로 된 태극기 응원’ 누리꾼 비난 봇물

한겨레 | 기사입력 2008.08.10 02:01 | 최종수정 2008.08.10 14:41

50대 여성, 광주지역 인기기사 자세히보기


[한겨레] 여자핸드볼 응원 모습 일파만파…포털에서는 이미 삭제
누리꾼 "국제망신" "국가에 대한 모욕" "어이없다" 반응

이명박 대통령이 베이징 올림픽 한국 여자핸드볼 경기 관람중 태극문양이 거꾸로 뒤집힌 태극기를 흔드는 사진이 인터넷에 퍼날라지면서 누리꾼들의 비난이 확산되고 있다.

 이 사진의 출처는 저녁 7시32분 베이징발 연합뉴스 사진으로, 9일 오후 4시45분 베이징 국가올림픽체육센터에서 열린 한국 여자핸드볼 B조 예선 첫 경기 러시아전을 관람한 이 대통령 내외가 우리팀이 29 대 29, 극적인 무승부를 일궈내자 태극기를 흔들며 기뻐하는 장면이다. 관련 사진 여러컷에서 확인되는 이 대통령 태극기의 문양은 모두 빨간색이 아래쪽으로 파란색이 위로 가 있으며, 4괘 역시 뒤집어져 있다. 그러나 옆에서 함께 흔들고 있던 대통령 부인 김윤옥씨나 유인촌 문화관광체육부 장관의 태극기는 파란색 문양이 아래로 제대로 나와 '대통령의 실수'를 한눈에 확인할 수 있다. 

 핸드볼 경기 결과와 함께 인터넷 포털에 이 사진이 뜨자마자, 누리꾼들은 이 대통령의 태극기가 잘못됐다는 사실을 확인하고 블로그에 올리기 시작했고 사진기사 하단에는 "국제망신"이라는 의견의 댓글이 줄을 이었다.

 한 누리꾼은 "한나라의 국기를 거꾸로 하는 것은 그 국가에 대한 모욕이나 굴욕의 표현이며 전쟁이나 전투에서 국가나 요새가 점령당한 걸 의미한다"며 '제 2의 우생순'을 재현하려는 여자핸드볼팀의 첫 경기 응원에서의 대통령의 '실수'를 씁쓸해 했다. 또 누리꾼들은 "나라가 거꾸로 가고 있으니, 거꾸로 된 태극기 휘날리나", "중국에서 짝퉁을 사서 흔드는건가요", "아무래도 이명박 대통령 측근 중에 엑스맨이 있음에 틀림 없다"는 등의 어이없다는 반응이 주를 이뤘다.

 논란이 확산되자 밤 10시께부터 관련사진이 연합뉴스 포토뉴스에서뿐 아니라 네이버 등 주요 포털에서 삭제됐다. 네이버에서 처음 올라왔던 사진기사 주소로 다시 들어가면 "웹페이지 주소가 변경되었거나 언론사 요청에 의해 삭제했습니다"라는 메시지가 뜬다.

 몇시간 만에 사진이 사라진 것을 확인한 누리꾼 김영희씨는 "언론사가 요청했든 청와대에서 요청했든 인위적 왜곡과는 차원이 다른 엄연한 현장기록물을 임의로 삭제하는 것은 문제"라고 지적했다. 그러나 그는 "이미 블로그에 워터마킹된 연합뉴스 사진이 다 퍼진 상태라 사실을 가릴 순 없다"고 말했다.

 한편, 지난해 2월에는 노무현 전 대통령의 남미 순방 전용기의 태극기가 거꾸로 달려 "기본도 없는 지도자", "나라망신 그만시켜라", "대한민국 국민인것이 부끄럽다"는 등 누리꾼들의 항의가 일파만파로 퍼진 바 있다.

권귀순 기자 gskwon@hani.co.kr
세상을 보는 정직한 눈 < 한겨레 > [ 한겨레신문 구독 | 한겨레21 구독 ]
ⓒ 한겨레신문사, 무단전재 및 재배포 금지
< 한겨레는 한국온라인신문협회(www.kona.or.kr)의 디지털뉴스이용규칙에 따른 저작권을 행사합니다. >
죄송합니다 펌프질했습니다..
2008. 8. 11. 00:35

Chapter 9. 원격 접속과 파일전송

                  Remote Connection & File Transfer

 

 

 

 

INDEX

______________________________________________________

 

1. Introducing an Example Network

2. Remote Connection History

3. Remote Connection & File Transmission for System V

4. Remote Connection & File Transmission for BSD

5. Remote Connection & File Transmission for Securiy

______________________________________________________

 

 

 

 

1. 네트워크 관련 용어

 

LAN(Local Area Network)

A network that covers a small area, usually less than a few thousand feet or meters.

 

WAN(Wide Area Network)

A network that can span thousands of miles or kilometers.

 

[참고] LAN(근거리 통신망, Local Area Network)

LAN[]이란 300m 이하의 통신회선으로 연결된 PC, 메인프레임, 워크스테이션 들의 집합을

말한다. LAN은 컴퓨터 사이의 전류나 전파신호가 정확히 전달될 수 있는 거리, 즉 한 기관

의 빌딩 내에 설치된 컴퓨터 장비들을 직원들이 가장 효과적으로 공동 사용할 수 있도록

연결된 고속의 통신망이다.

 

1970년대 말에서 1980년초 제록스사의 한 연구소에서 LAN에 관한 중요한 업적이 이루어졌

. 이 연구소에서 이더넷(Ethernet ; 공기가 없는 진공상태의 공간에 전파가 흘러갈 수

있는 물질이 존재한다고 가정하여 지은 독일어 단어 "에테르"에서 따온 말)이라고 이름을

붙인 컴퓨터 연결방법이 처음으로 실용화되었다.

 

[참고] WAN(광역 통신망, Wild Area Network)

WAN[]이란 지리적으로 흩어져 있는 통신망을 의미하는 것으로서 근거리통신망, LAN

구별하여 보다 넓은 지역을 커버하는 통신구조를 나타내는 용어로 사용된다. 보통 LAN

범위는 1개의 빌딩이나 학교, 연구소 및 생산공장 등의 일정 구역내인 것에 반해, WAN

넓은 지역을 연결하는 네트웍를 지칭하는 것으로 지방과 지방, 국가와 국가, 또는 대륙과

대륙 등과 같이 지리적으로 완전하게 떨어져 있는 장거리 지역 사이를 연결하고 있는 통신

망이다.

 

광역통신망은 사설망일 수도 있고 임차한 망도 될 수 있지만, 이 용어는 보통 공공망까지

를 포함하는 개념을 내포하고 있다. 지역적으로 LAN WAN 사이에 위치하는 중간정도 크기

의 네트웍을 특히 MAN이라고 부른다.

 

 

 

 

 


 

2. 원격접속과 파일전송

 

Remote Connection & File Transmission History

 

-----------+----------+--------------+--------------

           | System V |      BSD     |   Linux

-----------+----------+--------------+--------------

Remote     | telnet   |  rlogin, rsh |    ssh

Connection |          |              |

           |          |              |

File       | ftp      |  rcp         |    scp, sftp

Transfer   |          |              |

-----------+----------+--------------+--------------

 

 

[참고] 패킷 암호화에 대해서

위의 표에 있는 System V / BSD 계열의 모든 명령어는 패킷을 암호화 시키지 않는 단점을

가지고 있다. 그래서 원격 접속과 파일 전송을 할 때 패킷의 내용을 노출 시킬수 있게 된

. 그래서 최근에는 ssh, scp, sftp 프로그램과 같이 패킷을 암호화 할수 있는 프로그램

을 권장하고 있다.

 

 

[EX] 패킷 암호화 실습

[TERM1] # snoop HOSTA HOSTB

[TERM2] # telnet HOSTB

 

 

 

 

 

3. 원격접속 & 파일전송 명령어(System V 계열)

 

Remote Connection & File Transmission for System V

telnet 명령어

ftp 명령어

 

 

 

(1). telnet CMD

____________________

 

     telnet - user interface to a remote system using the  TELNET

     protocol

 

     The telnet utility communicates with another host using  the

     TELNET  protocol. If telnet is invoked without arguments, it

     enters command mode, indicated by its  prompt,  telnet>.  In

     this  mode, it accepts and executes its associated commands.

     See USAGE, telnet Commands, below. If  it  is  invoked  with

     arguments, it performs an open command with those arguments.

 

     If, for example, a host is specified as @hop1@hop2@host, the

     connection  goes  through  hosts  hop1 and hop2, using loose

     source routing to end at host. If a leading ! is  used,  the

     connection  follows  strict  source  routing. Note that when

     telnet uses IPv6, it can only use loose source routing,  and

     the connection ignores the !.

 

     Once a connection has been opened, telnet enters input mode.

     In  this  mode,  text  typed is sent to the remote host. The

     input mode entered will be either "line mode", "character at

     a  time",  or  "old  line  by line", depending upon what the

     remote system supports.

 

     In "line mode", character processing is done  on  the  local

     system,  under  the control of the remote system. When input

     editing or character echoing is to be disabled,  the  remote

     system  will relay that information.  The remote system will

     also relay changes to any special characters that happen  on

     the remote system, so that they can take effect on the local

     system.

 

     In "character at a time" mode, most text  typed  is  immedi-

     ately sent to the remote host for processing.

 

     In "old line by line" mode, all text is echoed locally,  and

     (normally) only completed lines are sent to the remote host.

     The "local echo character" (initially  ^E) may  be  used  to

     turn  off  and  on the local echo. (Use this mostly to enter

     passwords without the password being echoed.).

 

     If the "line mode" option is enabled, or if  the  localchars

     toggle is TRUE (the default in "old line by line" mode), the

     user's quit, intr, and flush characters are trapped locally,

     and sent as TELNET protocol sequences to the remote side. If

     "line mode" has ever been enabled, then the user's susp  and

     eof are also sent as TELNET protocol sequences. quit is then

 

     sent as a TELNET ABORT instead of BREAK. The options  toggle

     autoflush  and  toggle  autosynch cause this action to flush

     subsequent output to the terminal  (until  the  remote  host

     acknowledges  the  TELNET  sequence);  and to flush previous

     terminal input, in the case of quit and intr.

 

     While connected to a remote host, the user can enter  telnet

     command  mode  by  typing  the telnet escape character (ini-

     tially ^]). When in command mode, the normal terminal  edit-

     ing  conventions  are  available.  Pressing  <RETURN> at the

     telnet command prompt causes  telnet to exit command mode.

 

 


 

(1-1). telnet 명령어 실행 모드

 

telnet Remote Connection Excution Mode

- 대화형 모드(Interractive Mode)

- 비대화형 모드(Noninterractive Mode)

 

telnet 명령어 실행 모드

(비대화형 모드)  # telnet 172.16.8.254

 

(대화형 모드)    # telnet

                 telnet> open 172.16.8.254

 

 

(1-2). 기본사용법

 

# telnet  [호스트이름/아이피] [포트]

 

(telnet 명령어 사용법)

# telnet 172.16.8.254 

# telnet 172.16.8.254 23 (/etc/services 정의)

# telnet solaris254      (/etc/hosts 정의)

 

 

[참고] 잘 알려진 서비스 포트(Well-kown Port Number, 0 ~ 1023, 0 ~ 65535)

------------------

포트    서비스명

------------------

20,21   FTP

22      SSH

23      TELNET

25      SMTP

53      DNS

67,68   DHCP(Bootp)

80      WEB

110     POP3

111     sunrpc

123     NTP

143     IMAP

------------------

 

[참고] telnet 명령어 수행시 암호를 잘못 입력한 경우

# telnet localhost

Trying 127.0.0.1...

Connected to localhost.

Escape character is '^]'.

 

SunOS 5.9

 

login: root

Password:          <----- 암호 잘못 입력(암호: k)

Login incorrect

 

login: <Ctrl + ]>  <----- Escape Charater 입력

telnet>  quit       <----- 'quit' 입력

[참고] telnet 연결 화면시 에러 메세지

 

■ 상대편 서버의 이름을 잘못 지정한 경우

■ 상대편 서버가 정상적으로 동작하지 않는 경우

■ 상대편 서버로 로그인시 암호가 틀린 경우

root 사용자로 로그인시 CONSOLE 변수가 지정이 잘못된 경우

■ 상대편 서버에서 TCP_Wrapper로 막고 있는 경우

 

 

■ 상대편 서버의 이름을 잘못 지정한 경우

서버의 도메인을 알수 없을 경우

- /etc/hosts 파일의 정의가 되지 않은 경우

- DNS 서버에 도메인 등록이 되어 있지 않은 경우

 

----------------------메세지----------------------

# telnet solaris250       <----- /etc/hosts 파일에 solaris250 없음

solaris254: Unknown host  <----- 메세지 확인

--------------------------------------------------

 

 

■ 서버가 정상적으로 동작하지 않는 경우

- 서버의 아이피를 잘못 지정한 경우

- 서버가 Down 되어져 있는 경우

 

----------------------메세지----------------------

# telnet 172.16.8.250     <----- 172.16.8.250 아이피가 없음

Trying 172.16.8.250...

telnet: Unable to connect to remote host: Connection refused <----- 메세지 확인

--------------------------------------------------

(주의) 메세지를 받기 위해서는 약 10~20초 정도를 기다려야 한다.

 

 

■ 암호가 틀린 경우

- 로그인시 사용자의 암호를 잘못 입력한 경우

 

----------------------메세지----------------------

# telnet solaris254

Trying 172.16.8.254...

Connected to solaris254

Escape charater is '^]'

 

SunOS 5.9

 

login: user01

Password:       <----- 틀린 암호 입력(암호: 12345)

Login incorrect <----- 메세지 확인

--------------------------------------------------

 

 


 

root 사용자로 로그인시 CONSOLE 변수가 잘못 지정된 경우

 

----------------------메세지----------------------

# telnet 172.16.8.254

Trying 172.16.8.254...

Connected to 172.16.8.254.

Escape character is '^]'.

 

SunOS 5.9

 

login: root

Password:              <----- 정상 암호 입력(암호: knit)

Not on system console  <----- 메세지 확인

Connection to 172.16.8.254 closed by foreign host.

--------------------------------------------------

 

# vi /etc/default/login

......

[수정전]

#CONSOLE=/dev/console

[수정후]

CONSOLE=/dev/console

 

# telnet localhost

root 사용자로 로그인

 

(복구 작업)

# vi /etc/default/login

(이전 상태로 복원)

 

 

 

TCP_Wrapper에 의해 막힌 경우

 

# vi /etc/default/inetd

.....

[수정전]

ENABLE_TCPWRAPPERS=NO

[수정후]

ENABLE_TCPWRAPPERS=YES

 

# pkill -1 inetd

# echo "ALL: ALL" > /etc/hosts.deny

 

----------------------메세지----------------------

# telnet 172.16.8.254

Trying 172.16.8.254...

Connected to solaris254

Escape charater is '^]'

Connection to solaris254 closed by foreign host. <----- 메세지 확인

--------------------------------------------------

 


 

(복구 작업)

# vi /etc/default/inetd

-> 이전 상태로 복원

 

# rm /etc/hosts.deny

# pkill -1 inetd

 

 

 

 

 

(2). ftp CMD

____________________

 

     The ftp command is the user interface to the Internet  stan-

     dard  File  Transfer  Protocol (FTP). ftp transfers files to

     and from a remote network site.

 

     The host and optional port with which ftp is to  communicate

     may  be  specified on the command line. If this is done, ftp

     immediately attempts to establish a  connection  to  an  FTP

     server  on  that  host.  Otherwise,  ftp  enters its command

     interpreter and awaits instructions from the user. When  ftp

     is  awaiting  commands from the user, it displays the prompt

     ftp>.

 

     -i    Turns off interactive prompting during  multiple  file

           transfers.

 

 

 

(2-1). ftp 명령어 사용법

 

# ftp [옵션] [호스트이름/아이피] [포트]

 

ftp> help

ftp> bin  (solaris9 default)

ftp> ascii(solaris8 default)

ftp> hash

ftp> prompt

ftp> get filename

ftp> put filename

ftp> mget filename

ftp> mput filename

ftp> quit

ftp> bye

 

 

[참고] FTP Client Tools(GUI) - gftp

http://www.sunfreeware.com 다운 받아서 설치하면 된다.

 

 

 


 

(2-2). ftp 명령어 실습 1

 

=====HOSTA=====            ======HOSTB======

/tmp/uploadfile   =====>  /tmp

/root             <=====  /tmp/uploadfile

===============            =================

 

     [그림] 파일 업로드 / 다운로드

 

 

# mkfile 10m /tmp/test.solarisXXX

# mkdir /root

# ftp 172.16.8.254

root 사용자로 로그인

ftp> help

 

■ 업로드/다운로드 포인터 맞추기

■ 편리한 기능 설정

■ 업로드/다운로드

■ 확인 접속 해제

 

 

(a). 업로드/다운로드 포인터 맞추기(upload/download pointer)

ftp> lcd /tmp

ftp> cd  /tmp

ftp> ls

 

[참고] 업로드/다운로드 포인터

 

===== HOSTA =====            ===== HOSTB =====

 

 현재 디렉토리 ----------------> 홈디렉토리

 () /test                           /

 

 

 

(b). 편리한 기능 설정(FTP function)

ftp> bin               // unix 에서는 보통 bin mode로 동작하기 때문 맞추지 않으면 에러발생

ftp> ascii     // text 형태로~

ftp> hash      // 8k 단위로 # 표시

ftp> prompt    // 대화형 모드

 

[참고] 파일 전송모드 설정(ascii/bin)

 

===== HOSTA =====            ===== HOSTB =====

                   전송모드

File(s) ------------------------>

- ASCII             ASCII

- BINARY            BINARY

     * Binary Files

     * Compress Files

     * Archive Files

     * Encyption Files

 

 

[참고] 해쉬 설정(hash)

 

===== HOSTA =====            ===== HOSTB =====

 

File(s)

500Mbytes ----------------------->

                8k단위 #(Pound) 표시

 

 

[참고] 대화형 모드 ON/OFF(prompt)

 

===== HOSTA =====            ===== HOSTB =====

 

File(s)

file1, file2 ... ----------------->

                업로드/다운로드(y/n)?

 

 

 

(c). 업로드/다운로드(upload/download)

ftp> put test.solarisXXX

ftp> get test.solarisXXX

ftp> mput test.*

ftp> mget test.*

 

ftp> ls  [-al]

ftp> dir [-al]

 

ftp> bye

ftp> quit

 

 

 


 

[참고] 자동 파일 업/다운로드 스크립트

/root/shell/auto_ftp.sh

# rcp 172.16.8.254:/root/shell/auto_ftp.sh /test

 

-------------- auto_ftp.sh 설명 -------------------

#!/bin/ksh

 

#IP=172.16.8.254

IP=172.16.8.1

USERNAME=user01

PASSWD=user01

PORT=2121

#B_FILE=file_`date +'%m%d'`.tar.gz    # Backup File

B_FILE=backup.`date +'%m%d'`          # Backup File

 

ftp -n $IP $PORT << EOF                      // < redirect stdin , << here documentation

user $USERNAME $PASSWD

bin

hash

prompt

cd c:\a

lcd /root/test

put $B_FILE

EOF

----------------------------------------------------

 

(2-3). ftp 명령어 실습 2

 

===== Solaris Server =====            ===== Window Server =====

      /source (소스)

          |

          V

      /root/test/backup.0723 =========>   c:\a

 

==========================            =========================

 

  [그림] Solaris Server에서 Window Server로 자동 백업 설정

 

 

         Backup File : /root/test/backup.0723

         Windows     : 172.16.8.1

         Solaris     : 172.16.8.254

         Windows Backup Directory : C:\a

 

Function 1) Solaris Backup (/source => /root/test/backup.0723)

Function 2) Solaris->Windows Backup(/root/test/backup.0723->C\a)

 

 

 

(Function1)

# tar cvf /root/test/backup.0723 /source

# crontab -e

0 5 * * 0 tar cvf /root/test/backup.`date +'%m%d'` /source

 

[EX1] 실습

# mkdir /source

# cp /etc/passwd /source

# cp /etc/hosts /source

 

# cd /test

# tar cvf backup.0121 /source

 

 

 

(Function2)

# crontab -e

0 6 * * 0 /root/shell/auto_ftp.sh

 

 

 

[EX2] 실습

 

UNIX Server --------> Window Server

# ftp IP              ftp

   |

   +--> auto_ftp.sh

 

Windows) ftp 프로그램 실행 > "서버" > 적당한 정보 입력

        * 서버 IP    : 121.160.70.XXX

        * 홈디렉토리 : c:\a

        * [ ] ID 없이 접속 허용

        * [ ] 읽기만 허용

        * 아이디 / 비밀번호 : user01 / user01

        * 포트 : 21

        * 허용인원 : 5

       

UNIX   )# vi /test/auto_ftp.sh

        IP=121.160.70.148  --> 적당한 IP로 수정

        .....

        lcd /test    # 정보 수정(/root/test -> /test)

        cd c:\a      # Delete a Line  --> 라인 삭제

        .....

        # chmod 755 auto_ftp.sh

        # ./auto_ftp.sh

 

 

[참고] UNIX <--> Window 서버 동기화

- auto_ftp.sh 스크립트 사용

- SAMBA 서버 이용

- rsync 서버 이용

 

 

 


 

(2-4). ftp 관련 파일

 

/etc/ftpd/ftpusers

/etc/shells

 

 

 

(a). /etc/ftpd/ftpusers

 

/etc/ftpd/ftpusers 파일안에는 한개의 라인당 한명의 사용자가 등록 될수 있으면 이 파

일에 등록된 사용자는 FTP로 접속할 수 없다. Solaris 9 버전부터 ftpusers 파일은

/etc/ftpd 디렉토리에 존재하지만 이전버전에서는(Solaris 8 버전 이하) /etc 디렉토리

하위에 존재했었다. 기본 설정 파일을 그대로 사용한다면 시스템 사용자(System Account)

FTP로 로그인 할 수 없다. 하지만 일반사용자(: user01, user02...) FTP로 로그인

이 가능하다.

 

(FTP 서버 사용자 기본 정책)

- root 사용자는 FTP 서버에 접속 불가능

- 일반 사용자는 접속 가능(: user01, user02....)

 

# cat /etc/ftpd/ftpusers

root

daemon

bin

sys

adm

lp

uucp

nuucp

.....

 

[EX] /etc/ftpd/ftpusers 파일 예

# vi /etc/ftpd/ftpusers

root     <---- ENV_main.sh에 의해 삭제된 라인 등록

daemon

bin

sys

......

# ftp localhost

220 sun99 FTP server ready.

Name (localhost:root): root      <----- root 사용자로 로그인

331 Password required for root.

Password:                        <----- root 사용자 암호 입력

530 Login incorrect.             <----- 메세지 확인

Login failed.

 

# vi /etc/ftpd/ftpusers

daemon   <----- root 사용자 라인 삭제

bin

sys

......

# ftp localhost

root 사용자로 로그인 --> 정상적인 접속이 됨

 

 

 

[참고] /etc/ftpd/ftpusers 파일을 사용한 보안 강화

 

/etc/ftpd/ftpusers 파일 활용 예

# awk -F: '{print $1}' /etc/passwd > /etc/ftpd/ftpusers

 

# vi /etc/ftpd/ftpusers

root

....

user01

...

user02

....

#ftpuser     # FTP Upload User

....

 

[참고] /root/shell/ftpusers_limit.sh

 

 

 

(b). /etc/shells

 

/etc/shells 파일은 FTP 서버에 접속하여 명령어를 실행할때 사용할 수 있는 쉘을 정의 할

수 있다. 한개의 라인에 하나의 쉘을 정의한다. 이 파일은 솔라리스 기본 설치시 존재하지

않는다. 따라서 모든 사용자는 /etc/passwd 파일의 마지막 필드에 존재하는 쉘을 사용하여

FTP 작업을 할수 있다.

 

====== FTP Client ======           ======== FTP Server ========

 

# ftp Sever ----------------------> ID/PASS(인증)

                          user01     * /etc/passwd

                                       user01:--------:/bin/ksh

                                     * /etc/shells

                                        /bin/ksh     // FTP 로 접속시 할당 받을 쉘

                                        ....                  // 다른 서비스도 정의한다.

========================           ============================

 

/etc/shell 파일의 정의 방식

 

# cat /etc/shells          // 한라인에 한 개의 쉘

/bin/ksh

/bin/csh

/bin/sh

/usr/bin/ksh

.....

 

 

[EX] /etc/shells 파일 실습

 

# touch  /etc/shells

# ftp localhost

Connected to localhost.

220 solaris254 FTP server ready.

Name (localhost:root): user01      <----- user01 사용자로 로그인

331 Password required for user01.

Password:                          <----- user01 사용자 암호 입력

530 Login incorrect.               <----- 메세지 확인

Login failed.

ftp> quit                          <----- 'quit' 입력

 

# vi /etc/shells

/bin/ksh

 

# ftp localhost

user01 사용자 로그인

===> user01 사용자 로그인 가능

 

(시스템 복원)

# rm /etc/shells

 

 

 

 

 

4. 원격접속 & 파일전송 명령어(BSD 계열)

 

Remote Connection & File Transmission for BSD

rlogin 명령어

rsh 명령어

rcp 명령어

 

 

 

(1). r 명령어 동작원리

 

HOSTA    ---->     HOSTB

# telnet B          Auth(ID/PASS)

# rlogin B          Auth(/etc/hosts.equiv, ~/.rhosts)         // 인증과 관련된 파일

 

/etc/hosts.equiv   System wild Conf.                 // 전체 사용자

~/.rhosts            System specific Conf.   // 개인적인~

____________________                                 // 하지만 root는 둘다 제외된다.

 

HOSTA

HOSTA  user01

+

 

/etc/hosts.equiv

~/.rhosts

---------------------

HOSTA

HOSTA  +

HOSTA  user01

+      user01

+      +

 

 

HOSTA    ---->     HOSTB

# rlogin B          Auth(~root/.rhosts)

                         HOSTA

                         HOSTA  user01

                         +   +

 

 

[EX] .rhosts 파일 생성

# cat >  /.rhosts

+ +

<CRTL + D>

# cat /.rhosts

 

 

 

(2). rlogin CMD

____________________

 

     rlogin establishes a remote login session from your terminal

     to the remote machine named hostname.

 

     Hostnames are listed in the hosts  database,  which  may  be

     contained in the /etc/hosts and /etc/inet/ipnodes files, the

     Network Information Service (NIS) hosts  map,  the  Internet

     domain name server, or a combination of these. Each host has

     one official name (the first name in  the  database  entry),

     and  optionally one or more nicknames. Either official host-

     names or nicknames may be specified in hostname.

 

     Each remote machine may have a file  named  /etc/hosts.equiv

     containing  a list of trusted hostnames with which it shares

     usernames. Users with the same username on  both  the  local

     and  remote  machine  may rlogin from the machines listed in

     the remote machine's /etc/hosts.equiv file without supplying

     a  password.  Individual  users may set up a similar private

     equivalence list with the file .rhosts in their home  direc-

     tories.  Each  line in this file contains two names: a host-

     name and a username separated by a  space.  An  entry  in  a

     remote  user's  .rhosts file permits the user named username

     who is logged into hostname to log in to the remote  machine

     as the remote user without supplying a password. If the name

     of the local host is not found in the /etc/hosts.equiv  file

     on  the  remote machine, and the local username and hostname

     are not found in the remote user's .rhosts  file,  then  the

     remote  machine will prompt for a password. Hostnames listed

     in /etc/hosts.equiv and .rhosts files must be  the  official

     hostnames listed in the hosts database; nicknames may not be

     used in either of these files.

 

     For security reasons, the .rhosts  file  must  be  owned  by

     either the remote user or by root.

 

     The remote terminal type is the same as your local  terminal

     type (as given in your environment TERM variable).  The ter-

     minal or window size is also copied to the remote system  if

     the  server  supports  the  option,  and changes in size are

     reflected as well. All echoing takes  place  at  the  remote

     site,  so that (except for delays) the remote login is tran-

     sparent.  Flow  control  using  <CTRL-S>  and  <CTRL-Q>  and

     flushing of input and output on interrupts are handled prop-

     erly.

 

 

(2.1) 명령어 사용법

                                   // # rcp source destination

# rlogin hostname

# rlogin -l username hostname (-l : login name)

# rlogin username@hostname

 

[EX] rlogin 실습

# rlogin localhost

# rlogin 172.16.8.254

# exit

# rlogin -l user01 172.16.8.254

user01 사용자의 인증이 되어 있지 않기 때문에 로그인 시에 인증이 되어야 한다.

$ exit

 

rlogin   : 미리 인증(:~/.rhosts)이 되어 있지 않으면 접속할 당시에 패스워드를 통해

           인증하게 된다.

rsh, rcp : 미리 인증이 되어 있지 않으면 명령어 수행이 되지 않는다.

 

 

 

(3). rsh CMD

____________________

 

     rsh connects to the  specified  hostname  and  executes  the

     specified  command.  rsh  copies  its  standard input to the

     remote command, the standard output of the remote command to

     its  standard  output,  and the standard error of the remote

     command to its standard error.  Interrupt,  quit,  and  ter-

     minate  signals  are  propagated  to the remote command. rsh

     normally terminates when the remote command does.

 

     If you omit command, instead of executing a single  command,

     rsh logs you in on the remote host using rlogin(1).

 

     rsh will not return the exit status code of command.

 

     Shell metacharacters which are not quoted are interpreted on

     the  local  machine,  while quoted metacharacters are inter-

     preted on the remote machine. See EXAMPLES.

 

     If there is no locale setting in the initialization file  of

     the  login  shell (.cshrc, . . .) for a particular user, rsh

     always executes the command in the  "C"  locale  instead  of

     using the default locale of the remote machine.

 

 

(3-1). 명령어 사용법

 

# rsh hostname CMD

 

# rsh 172.16.8.254 hostname

# rsh 172.16.8.254 ls -l /tmp

# rsh 172.16.8.254 ls -l /root/docs

 

 

 

(4). rcp CMD

____________________

 

     The rcp command copies files between machines. Each filename

     or  directory  argument  is either a remote file name of the

     form:

 

     hostname:path

 

     or a local file name (containing no ":" (colon)  characters,

     or "/" (backslash) before any ":" (colon) characters).

 

     The hostname can be an IPv4  or  IPv6  address  string.  See

     inet(7P) and inet6(7P). Since IPv6 addresses already contain

     colons, the hostname should be enclosed in a pair of  square

     brackets  when an IPv6 address is used. Otherwise, the first

     occurrence of a colon can be interpreted  as  the  separator

     between hostname and path. For example,

 

     [1080::8:800:200C:417A]:tmp/file

 

     If a filename is not a full path  name,  it  is  interpreted

     relative  to  your  home  directory on hostname. A path on a

     remote host may be quoted using \, ",  or  ',  so  that  the

     metacharacters are interpreted remotely.

 

     rcp does not prompt for passwords; your current  local  user

     name  must exist on hostname and allow remote command execu-

     tion by rsh(1).

 

     rcp handles third party copies,  where  neither  source  nor

     target  files are on the current machine. Hostnames may also

     take the form

 

     username@hostname:filename

 

     to use username rather than your current local user name  as

     the user name on the remote host. rcp also supports Internet

     domain addressing of the remote host, so that:

 

     username@host.domain:filename

 

     specifies the username to be used,  the  hostname,  and  the

     domain  in  which that host resides. File names that are not

     full path names will be interpreted  relative  to  the  home

 

 

(4-1). 명령어 사용법

 

# rcp file1 172.16.8.254:/tmp

# rcp 172.16.8.254:/tmp/file1 /tmp

# rcp -r dir1 172.16.8.254:/tmp

# rcp -r 172.16.8.254:/root/shell /root

# rcp 172.16.8.254:/root/* .

# rcp file1 user01@172.16.8.254:/tmp

 

 

[EX] rcp 실습

# rcp -r 172.16.8.254:/root/shell /root

 

# touch  /root/test.solarisXXX

# rcp /root/test.solarisXXX 172.16.8.254:/tmp

# rsh 172.16.8.254 ls -l /tmp

 

 

[참고] .rhosts 파일 정책(Policy)

 

(a). 사용자 홈디렉토리에 .rhosts 파일을 정기적으로 지우는 정책

 

# find /export/home -name .rhosts -type f -exec rm {} \;

 

# crontab -e

0 6 * * * find /export/home -name .rhosts -type f -exec rm {} \;

 

 

(b). 사용자 홈디렉토리에 .rhosts 파일을 못 만들도록 하는 정책

user01 Home Directory : /export/home/user01

 

# cd /export/home/user01

# mkdir .rhosts (rwxr-xr-x root        other)

# touch .rhosts/.notperm (rw-r--r-- root other)

 

# chmod 000 .rhosts

# chmod 000 .rhosts/.notperm

 

--------- /export/home/user01 ---------- (user01:other rwxr-xr-x)

 

      .rhosts 디렉토리 생성(관리자) (root:other rwxr-xr-x)

                  |

                  +----------------> 디렉토리 삭제(사용자)

                  |                  # rmdir .rhosts

                  |

      .rhosts/.notperm 파일생성(관리자) .rhosts (root:other rwxr-xr-x)

                  |                          +-- .notperm(root:other rw-r--r--)

                  |

                  +----------------> 디렉토리 삭제(사용자)

                                     # rm -r .rhosts

 

(사용자 테스트)

# telnet localhost

user01 사용자로 로그인

$ touch .rhosts

touch: cannot change times on .rhosts

 

$ rmdir .rhosts

rmdir: directory ".rhosts": Directory not empty

 

$ rm -r .rhosts

rm: cannot read directory .rhosts: Permission denied

 

$ ls .rhosts

.rhosts: Permission denied

 

$ cd .rhosts

ksh: .rhosts: permission denied

 

 

 

[참고] 사용자의 환경파일의 내용을 수정하지 못하도록 관리자가 설정

 

사용자의 홈 : /export/home/user02

 

/export/home/user02 (root other rwxr-xr-x)

               |

               +--- .profile (root other rw-r--r--)

               |

               +--- work (user02 staff rwxr-xr-x)

 

# cd /export/home

# mv user02 user02.old

# mkdir /export/home/user02

# cd ~user02

# vi .profile

PATH=/bin:/sbin:/usr/bin:/usr/dt/bin:/usr/sbin

export PATH

 

cd work

# mkdir work

# chown user02:staff work

 

# telnet localhost

user02/user02

 

$ pwd

$ id

$ echo $PATH

$ vi ~/.profile

수정가능(X)

:wq!

 

 

5. 원격접속 & 파일전송 명령어 (암호화 방식)

 

Remote Connection & File Transmission for Securiy

ssh 명령어

scp 명령어

sftp 명령어

 

 

[SSH 에 대해서]

전형적인 TCP/IP Transport Layer 암호화 메커니즘을 사용하며, 이것은 암호화 엔진을 위

하여 대중적인 Blowfish 또는 정부 지원의 tripe-DES(Data Encryption Standard) 알고리

즘을 사용한다. 암호화 기술의 사용은 상호 작용 세션의 내용이 클라이언트 및 서버 이외

에는 누구에게도 알려지지 않게 한다. 세션 데이터 암호화뿐만 아니라, 식별 및 인증 과

정이 RSA 암호화 기술을 사용하여 암호화 된다. 이것은 사용자이름과 패스워드의 조합이

3자에 의해 sniff 될수 없음을 의미 한다.

 

[SSH 클라이언트 연결 수립과정]

(a). 클라이언트 연결을 요청하기 위해 서버 포트로 연결한다.(default port 22)

(b). 서버는 표준 public RSA 호스트 키(1024 bits)와 매시간 변경되는 다른 RSA 서버키

     (768 bits)를 가지고 응답한다. 서버 키가 시간마다 변경되기 때문에, 한 세션의 트

     래픽에 대한 키가 crack 되어도, historic 데이터는 여전히 암호화되어 이러한 공격

     툴를 제한한다.

(c). 서버는 알지 못하는 호스트로부터 연결을 거부하도록 설정될 수 있지만 기본적으로

     모든 클라이언트로 부터 연결을 허용한다.

(d). 만약 연결이 수용되면, 클라이언트는 256비트의 임의 번호로 구성되는 세션 키를 생

     성하고 서버가 지원하는 암호화 알고리즘(tripe-DES or Blowfish)을 선택한다.

(e). 클라이언트 RSA를 사용하는 세션키를, 호스트 및 서버 키 모두를 사용하여 암호화하

     고 암호화된 키를 서버로 돌려보낸다.

(f). 서버는 세션 키를 해독하여 클라이언트와 서버 사이의 암호화가 사용가능하게 된다.

(g). 만약 기본 인증메커니즘이 선택된다면, 클라이언트는 secure channel을 통해 서버에

     대한 사용자 이름과 패스워드를 전달한다.

 

# ssh -l user01 172.16.8.254                                              sshd(22)

 [client]       --------- request connection (port 22)       -----------> [server]

generate 256bit <-------- send 1024bit host key & server key -----------

client key                (public RSA Key)        (Time Based)

                --------- send new key                       ----------->

                <-------- request username/password          ------------ secure channel

                                                                          established

                --------- send username/password             ----------->

                <-------- accept or reject connection        ------------

 

                         [그림] ssh 클라이언트/서버 연결과정

 

다음 그림은 일반적인 암호화 방식을 나타낸다.

---------- HOSTA -----------                   ---------- HOSTB -----------

                                   전송

A ---> 암호화알고리즘 ---> " ----------------> " ---> 복호화알고리즘 ---> A

         +3   /2                                         * 2  -3

                   A                                              A

                     |                                              |

                    Key                                            Key

 

                        [그림] 일반적인 암호화 방식

(1). ssh CMD

____________________

 

     ssh (Secure Shell) is a program for logging  into  a  remote

     machine  and  for executing commands on a remote machine. It

     is intended to replace rlogin and rsh, and to provide secure

     encrypted communications between two untrusted hosts over an

     insecure network. X11 connections and arbitrary TCP/IP ports

     can also be forwarded over the secure channel.

 

     ssh connects and logs into the specified hostname. The  user

     must  prove  his or her identity to the remote machine using

     one of several methods depending  on  the  protocol  version

     used:

 

  SSH protocol version 1

     First, if the machine the user logs in  from  is  listed  in

     /etc/hosts.equiv or /etc/shosts.equiv on the remote machine,

     and the user names are the same on both sides, the  user  is

     immediately  permitted  to  log  in.  Second, if .rhosts  or

     .shosts exists in the user's home directory  on  the  remote

     machine  and  contains  a  line  containing  the name of the

     client machine and the name of the user on that machine, the

     user  is  permitted  to  log in. This form of authentication

     alone is normally not allowed by the server  because  it  is

     not secure.

 

     The second (and primary) authentication method is the rhosts

     or hosts.equiv method combined with RSA-based host authenti-

     cation. It means that if the login  would  be  permitted  by

     $HOME/.rhosts,     $HOME/.shosts,    /etc/hosts.equiv,    or

     /etc/shosts.equiv, and if additionally the server can verify

     the client's host key (see /etc/ssh_known_hosts in the FILES

     section), only then is login permitted. This  authentication

     method  closes security holes due to IP spoofing, DNS spoof-

     ing, and routing spoofing.

 

     Note to the administrator: /etc/hosts.equiv,  $HOME/.rhosts,

     and  the  rlogin/rsh  protocol  in  general,  are inherently

     insecure and should be disabled if security is desired.

 

     As a third authentication  method,  ssh  supports  RSA-based

     authentication. The scheme is based on public-key cryptogra-

     phy. There are cryptosystems where encryption and decryption

     are  done  using  separate  keys,  and it is not possible to

     derive the decryption key from the encryption  key.  RSA  is

     one  such  system.  The  idea  is  that  each user creates a

     public/private key pair  for  authentication  purposes.  The

     server  knows  the  public  key, and only the user knows the

     private key. The file $HOME/.ssh/authorized_keys  lists  the

     public keys that are permitted for logging in. When the user

     logs in, the ssh program tells the server which key pair  it

     would  like  to use for authentication. The server checks if

     this key is permitted, and if so, sends the  user  (actually

     the  ssh  program running on behalf of the user) a challenge

     in the form of a random number, encrypted by the user's pub-

     lic  key.  The  challenge  can  only  be decrypted using the

     proper private key. The  user's  client  then  decrypts  the

     challenge  using  the  private  key,  proving that he or she

     knows the private key  but  without  disclosing  it  to  the

     server.

 

     ssh implements the  RSA  authentication  protocol  automati-

     cally.  The  user creates his or her RSA key pair by running

     ssh-keygen(1).    This   stores   the   private    key    in

     $HOME/.ssh/identity     and     the     public     key    in

     $HOME/.ssh/identity.pub in the user's  home  directory.  The

     user     should    then    copy    the    identity.pub    to

     $HOME/.ssh/authorized_keys in his or her home  directory  on

     the  remote machine (the authorized_keys file corresponds to

     the conventional $HOME/.rhosts file, and  has  one  key  per

     line,  though  the  lines can be very long). After this, the

     user can log in without giving the password. RSA authentica-

     tion is much more secure than rhosts authentication.

 

     The most convenient way to use  RSA  authentication  may  be

     with  an  authentication  agent.  See  ssh-agent(1) for more

     information.

 

     If other authentication methods fail, ssh prompts  the  user

     for  a password. The password is sent to the remote host for

     checking. However, since all communications  are  encrypted,

     the password cannot be seen by someone listening on the net-

     work.

 

  SSH protocol version 2

     When a user connects using the protocol version 2, different

     authentication  methods  are available. At first, the client

     attempts to authenticate using the  public  key  method.  If

     this method fails, password authentication is tried.

 

     The public key  method  is  similar  to  RSA  authentication

     described  in  the  previous  section  except  that  the DSA

     algorithm is used instead of the patented RSA algorithm. The

     client  uses  his  private DSA key $HOME/.ssh/id_dsa to sign

     the session identifier and sends the result to  the  server.

     The  server checks whether the matching public key is listed

     in $HOME/.ssh/authorized_keys and grants access if both  the

     key is found and the signature is correct. The session iden-

     tifier is derived from a shared Diffie-Hellman value and  is

     known only to the client and the server.

 

     If public key authentication fails or is  not  available,  a

     password  can be sent encrypted to the remote host for prov-

     ing the user's identity. This protocol 2 implementation does

     not yet support Kerberos or S/Key authentication.

 

     Protocol 2 provides additional mechanisms for  confidential-

     ity  (the traffic is encrypted using 3DES, Blowfish, CAST128

     or Arcfour) and integrity (hmac-sha1, hmac-md5). Notice that

     protocol  1  lacks  a  strong  mechanism  for  ensuring  the

     integrity of the connection.

 

  Login session and remote execution

     When the user's identity has been accepted  by  the  server,

     the  server  either executes the given command, or logs into

     the machine and gives the user a normal shell on the  remote

     machine.  All communication with the remote command or shell

     will be automatically encrypted.

 

     If a pseudo-terminal has been allocated (normal  login  ses-

     sion), the user can disconnect with ~., and suspend ssh with

     ~^Z. All forwarded connections can be listed with ~#. If the

     session  blocks  waiting for forwarded X11 or TCP/IP connec-

     tions  to  terminate,  ssh  can  be  backgrounded  with  ~&,

     although  this  should  not  be used while the user shell is

     active, as it can cause the shell  to  hang.  All  available

     escapes can be listed with ~?.

 

     A single tilde character can be sent as ~~ (or by  following

     the  tilde by a character other than those described above).

     The escape character must always  follow  a  newline  to  be

     interpreted  as special. The escape character can be changed

     in configuration files or on the command line.

 

     If no pseudo tty has been allocated, the  session  is  tran-

     sparent and can be used to reliably transfer binary data. On

     most systems, setting the escape character  to  "none"  will

     also make the session transparent even if a tty is used.

 

     The session terminates when the  command  or  shell  in  the

     remote machine exits and all X11 and TCP/IP connections have

     been closed. The  exit  status  of  the  remote  program  is

     returned as the exit status of ssh.

 

  X11 and TCP forwarding

     If the user is using X11 (the DISPLAY  environment  variable

     is  set), the connection to the X11 display is automatically

     forwarded to the remote side in such a way that any X11 pro-

     grams  started  from  the shell (or command) will go through

     the encrypted channel, and the  connection  to  the  real  X

     server  will be made from the local machine. The user should

     not manually set DISPLAY. Forwarding of X11 connections  can

     be configured on the command line or in configuration files.

 

     The DISPLAY value set  by  ssh  will  point  to  the  server

     machine,  but  with a display number greater than zero. This

     is normal behavior, because ssh creates a "proxy"  X  server

     on  the  server  machine for forwarding the connections over

     the encrypted channel.

 

     ssh will also automatically set up Xauthority  data  on  the

     server  machine. For this purpose, it will generate a random

     authorization cookie, store it in Xauthority on the  server,

     and  verify that any forwarded connections carry this cookie

     and replace it by the real cookie  when  the  connection  is

     opened.  The real authentication cookie is never sent to the

     server machine (and no cookies are sent in the plain).

 

     If the user is using an authentication agent, the connection

     to  the  agent is automatically forwarded to the remote side

     unless disabled on the command line or  in  a  configuration

     file.

 

     Forwarding of arbitrary TCP/IP connections over  the  secure

     channel  can be specified either on the command line or in a

     configuration file. One possible application of TCP/IP  for-

     warding  is  a  secure  connection  to  an electronic purse.

     Another possible application is going through firewalls.

 

  Server authentication

     ssh automatically maintains and checks a database containing

     identifications  for  all  hosts it has ever been used with.

     RSA host keys are stored in  $HOME/.ssh/known_hosts  in  the

     user's    home    directory.    Additionally,    the    file

     /etc/ssh_known_hosts  is  automatically  checked  for  known

     hosts.  Any  new hosts are automatically added to the user's

     file. If a host's identification  ever  changes,  ssh  warns

     about this and disables password authentication to prevent a

     trojan horse from getting the user's password. Another  pur-

     pose  of  this  mechanism  is  to  prevent man-in-the-middle

     attacks which could otherwise  be  used  to  circumvent  the

     encryption. The StrictHostKeyChecking option (see below) can

     be used to prevent logins to machines whose host key is  not

     known or has changed.

 

 

(1-1). ssh 명령어 사용법

 

# ssh hostname

# ssh -l username hostname

# ssh username@hostname

 

 

 

(2). sftp CMD

_____________________

 

     The sftp utility is an  interactive  file  transfer  program

     with a user interface similar to ftp(1) that uses the ssh(1)

     command to create a secure connection to the server.

 

     sftp implements the SSH File Transfer Protocol as defined in

     IETF  draft-ietf-secsh-filexfer.  There  is  no relationship

     between the protocol used  by  sftp  and  the  FTP  protocol

     (RFC959) provided by ftp(1).

 

(2-1). sftp 명령어 사용법

 

sftp 명령어는 ftp 명령어를 기반으로 만들어 졌기 때문에 명령어 형식이 거의 흡사하다.

 

# sftp 172.16.8.254

# sftp user01@solaris254

 

[EX] sftp 명령어 실습

 

# sftp 172.16.8.254

Connecting to 172.16.8.254...

The authenticity of host '192.168.1.200' can't be established.

RSA key fingerprint in md5 is: 66:2c:f0:80:41:26:f7:1f:5d:a3:be:8c:0d:9a:e5:e1

Are you sure you want to continue connecting(yes/no)? yes <----- 'yes' 입력

Warning: Permanently added '192.168.1.200' (RSA) to the list of known hosts.

root@192.168.1.200's password:  <----- 암호 입력(암호: knit)

sftp > help                     <----- 'help' 입력

Available commands:

cd path                       Change remote directory to 'path'

lcd path                      Change local directory to 'path'

chgrp grp path                Change group of file 'path' to 'grp'

chmod mode path               Change permissions of file 'path' to 'mode'

chown own path                Change owner of file 'path' to 'own'

help                          Display this help text

get remote-path [local-path]  Download file

lls [ls-options [path]]       Display local directory listing

lmkdir path                   Create local directory

lpwd                          Print local working directory

ls [path]                     Display remote directory listing

lumask umask                  Set local umask to 'umask'

mkdir path                    Create remote directory

put local-path [remote-path]  Upload file

pwd                           Display remote working directory

exit                          Quit sftp

quit                          Quit sftp

rename oldpath newpath        Rename remote file

rmdir path                    Remove remote directory

rm path                       Delete remote file

!command                      Execute 'command' in local shell

!                             Escape to local shell

?                             Synonym for help

sftp > quit   <----- 'quit' 입력

 

 

 


 

(3). scp CMD

_____________________

 

     The scp utility copies files between hosts on a network.  It

     uses ssh(1) for data transfer, and uses the same authentica-

     tion and  provides  the  same  security  as  ssh(1).  Unlike

     rcp(1),  scp  will  ask for passwords or passphrases if they

     are needed for authentication.

 

     Any file name may contain a host and user  specification  to

     indicate  that  the  file is to be copied to/from that host.

     Copies between two remote hosts are permitted.

 

(3-1). scp 명령어 사용법

 

scp 명령어는 rcp 명령어를 기반으로 만들어 졌기 때문에 명령어의 형식이 거의 흡사하다.

 

# scp /tmp/file1 172.16.8.254:/tmp

# scp -r /root/test 172.16.8.254:/tmp

# scp -r 172.16.8.254:/tmp /test

# scp -r file1 user01@172.16.8.254:/tmp

 

 

 

(4). ssh 관련 파일들

 

- $HOME/.ssh/known_hosts

- $HOME/.ssh/identity

- $HOME/.ssh/identity.pub

- $HOME/.ssh/id_dsa.pub

- $HOME/.ssh/config

- $HOME/.ssh/authorized_keys

- /etc/ssh/ssh_known_hosts

- /etc/ssh/ssh_config

- $HOME/.rhosts

- /etc/hosts.equiv

- /etc/ssh/shosts.equiv

- /etc/ssh/sshrc

- $HOME/.ssh/rc

- $HOME/.ssh/environment

 

 

 

     $HOME/.ssh/known_hosts

           Records host keys for all hosts the  user  has  logged

           into   that   are  not  in  /etc/ssh_known_hosts.  See

           sshd(1M).

 

     $HOME/.ssh/identity

 

     $HOME/.ssh/id_dsa

           Contains the RSA and the DSA  authentication  identity

           of  the  user.  These files contain sensitive data and

           should be readable by the user but not  accessible  by

           others (read/write/execute). Notice that ssh ignores a

           private key file if it is accessible by others. It  is

           possible  to  specify a passphrase when generating the

           key. The passphrase will be used to encrypt the sensi-

           tive part of this file using 3DES.

 

     $HOME/.ssh/identity.pub

 

     $HOME/.ssh/id_dsa.pub

           Contains the public key for authentication,  that  is,

           the public part of the identity file in human-readable

           form. The contents of the $HOME/.ssh/identity.pub file

           should  be  added to $HOME/.ssh/authorized_keys on all

           machines where you wish to log in using RSA  authenti-

           cation. The contents of the $HOME/.ssh/id_dsa.pub file

           should be added to $HOME/.ssh/authorized_keys  on  all

           machines  where you wish to log in using DSA authenti-

           cation. These files are not  sensitive  and  can,  but

           need not, be readable by anyone. These files are never

           used automatically and are  not  necessary.  They  are

           provided only for the convenience of the user.

 

     $HOME/.ssh/config

           This is the per-user configuration file. The format of

           this file is described above. This file is used by the

           ssh client. This file does  not  usually  contain  any

           sensitive information, but the recommended permissions

           are read/write for the user and not accessible by oth-

           ers.

 

     $HOME/.ssh/authorized_keys

           Lists the DSA keys that can be used for logging in  as

           this  user. This file is not highly sensitive, but the

           recommended permissions are read/write  for  the  user

           and not accessible by others.

 

     /etc/ssh/ssh_known_hosts

           Systemwide    list     of     known     host     keys.

           /etc/ssh_known_hosts  contains  RSA  keys.  This  file

           should be prepared by the system administrator to con-

           tain  the  public  host  keys  of  all machines in the

           organization and should be  world-readable.  The  file

           contains  public  keys, one per line, in the following

           format, with fields separated by spaces: system  name,

           number  of  bits in modulus, public exponent, modulus,

           and optional comment field. When different  names  are

           used  for  the  same machine, all such names should be

           listed, separated by commas. See sshd(1M).

 

           The  canonical  system  name  (as  returned  by   name

           servers) is used by sshd(1M) to verify the client host

           when logging in. Other names are  needed  because  ssh

           does not convert the user-supplied name to a canonical

           name before checking the key, to prevent someone  with

           access  to  the  name  servers from being able able to

           fool host authentication.

 

     /etc/ssh/ssh_config

           Systemwide  configuration  file.  This  file  provides

           defaults  for  those  values that are not specified in

           the user's configuration file, and for those users who

           do not have a configuration file.

 

           This file must be world-readable.

 

     $HOME/.rhosts

           This file is used in .rhosts  authentication  to  list

           the  host/user  pairs  that  are  permitted to log in.

           (Notice that this file is also used by rlogin and rsh,

           which  makes  using  this file insecure.) Each line of

           the file contains a host name (in the  canonical  form

           returned  by  name  servers),  and then a user name on

           that host, separated by a  space.  On  some  machines,

           this  file may need to be world-readable if the user's

           home  directory  is  on  an  NFS  partition,   because

           sshd(1M)  reads  it  as  root. Additionally, this file

           must be owned by the user and must not have write per-

           missions  for  anyone else. The recommended permission

           for most machines is read/write for the user  and  not

           accessible by others.

 

           Notice that, by default, sshd(1M) will be installed so

           that  it  requires  successful RSA host authentication

           before  permitting  .rhosts  authentication.  If  your

           server  machine does not have the client's host key in

           /etc/ssh_known_hosts,   you   can    store    it    in

           $HOME/.ssh/known_hosts.  The easiest way to do this is

           to connect back to the client from the server  machine

           using ssh. This will automatically add the host key to

           $HOME/.ssh/known_hosts.

 

     $HOME/.shosts

           This file is used exactly the same way as .rhosts. The

           purpose  for  having  this  file  is to be able to use

           rhosts  authentication  with  ssh  without  permitting

           login with rlogin(1) or rsh(1).

 

 

     /etc/hosts.equiv

           This file is used during  .rhosts  authentication.  It

           contains  canonical  hosts  names,  one per line. (See

           sshd(1M) for the full  format  description.).  If  the

           client  host is found in this file, login is automati-

           cally permitted, provided that client and server  user

           names  are  the same. In addition, successful RSA host

           authentication is normally required. This file  should

           only be writable by root.

 

     /etc/ssh/shosts.equiv

           This file is processed  exactly  as  /etc/hosts.equiv.

           This file may be useful to permit logins using ssh but

           not using rsh or rlogin.

 

     /etc/ssh/sshrc

           Commands in this file are executed  by  ssh  when  the

           user  logs  in just before the user's shell or command

           is started. See sshd(1M) for more information.

 

     $HOME/.ssh/rc

           Commands in this file are executed  by  ssh  when  the

           user  logs  in just before the user's shell or command

           is started. See sshd(1M) for more information.

 

     $HOME/.ssh/environment

           Contains additional definitions for environment  vari-

           ables. See ENVIRONMENT VARIABLES.


2008. 8. 8. 18:46

Chapter 8. 프로세스 관리


Process Administration

 

 

INDEX

_______________________________________

 

1. Process Information

2. Default Process Administration

3. Extenston Process Administration

_______________________________________

 

 

 

프로세스(Process) ?

- 실행중인 프로그램그램이다.

 

프로세스는 컴퓨터 내에서 실행중인 프로그램의 인스턴스이다. 이 용어는 몇몇 운영체계에

서 사용되는, "태스크"라는 용어와 의미상으로 가깝다. 유닉스나 몇몇 다른 운영체계에서

, 프로그램이 시작되면 프로세스도 시작된다. 태스크와 마찬가지로, 프로세스는 그 프로

세스가 추적 관리될 수 있게 하기 위한 특정한 데이터 셋이 관련되어 실행 중인 프로그램

이다. 여러 명의 사용자들에 의해 공유되고 있는 응용프로그램은 일반적으로 각 사용자들

의 실행단계에서 하나의 프로세스를 갖는다.

 

프로세스는 자프로세스라고도 불리는 서브프로세스를 시작시킬 수 있다. 자프로세스는 부

프로세스의 복제로서 부프로세스의 자원을 일부 공유하는데, 부프로세스가 종료되면 더

이상 존재할 수 없다. 프로세스들은 몇 가지 IPC 방식을 통하여 정보를 교환하거나 그들의

연산을 동기화할 수 있다.

 

IPC 방식의 대표적인 메쏘드는

      (a)Pipes named pipes

      (b)Message queueing

      (c)Semaphores,

      (d)Shared Memory

      (e)Socket

등이다.

 

 


1. 프로세스 정보(Process Information)

 

ps 명령어를 통해서 프로세스 정보를 확인할 수 있다. 이런 정보는 존재해야만 출력이 될

수 있다. 프로세스의 정보는 /proc 디렉토리에 하위에 프로세스 아이디(PID) 번호와 대응

이 되는 이름을 가진 디렉토리에 존재한다.

 

다음은 기본적인 프로세스 정보에 대한 내용이다.

- PID(Process Identification)

- PPID(Parent Process ID)

- UID/GID

- EUID/EGID

- Control Terminal

 

 

 

(1). 프로세스 정보가 존재하는 디렉토리

프로세스에 대한 정보는 /proc 디렉토리에 해당 프로세스의  PID 번호 디렉토리안에 정보

가 존재하게 된다.   이 디렉토리 안에 존재하는 파일들은 대부분 텍스트 파일로 되어 있지

않기 때문에 프로세스의 정보를 확인 할때 pCMD(: pfiles, pstack, ptree, ....)등의 명령

어를 사용해야 한다.

프로세스 정보 디렉토리 : /proc/PID

 

# admintool &

[1]    479     <----- admintool PID 번호 확인(479)

 

# ps

   PID TTY      TIME CMD

   467 pts/3    0:00 ksh

   479 pts/3    0:00 admintoo   <----- admintool PID 번호 확인(479)

 

# ls -ld /proc/479

 

admintool 종료(adminitool exit)

# ls -ld /proc/479

/proc/479: No such file or directory

 

 

 

[참고] procfs 특징

(a). /proc 디렉토리 하위에 PID 번호의 디렉토리가 생성되고 그안에 프로세스 정보가 쌓

     이게 된다. /proc/PID 디렉토리 하위에는 프로세스의 정보에 관련한 자세한 내용이

     파일과 디렉토리에 존재하게 된다.

(b). /proc/PID 디렉토리의 소유자는 프로세스를 실행시킨 사람의 소유이다.

 

 

 

[참고] 프로세스 정보를 자세하게 보기 위해서는 다음 파일을 참고 한다.

/root/docs/Reference/Process_CMD.txt

- 위의 문서중 pldd, pfiles, pstack, ptree, ptime 명령어는 반드시 알아 두자.

pldd     : 프로세스가 사용하고 있는 동적 라이브러리 확인

pfiles   : 프로세스가 사용하고 있는 파일들 확인

pstack   : 프로세스가 사용하고 있는 stack 공간 확인

ptree    : 프로세스 tree 구조 확인

ptime    : 프로세스가 실행된 시간 확인

 

 

 

(2). PID

 

프로그램을 실행 하면 프로세스가 되며, 각각의 프로세스를 식별하기 위해 할당되는 번호로

PID 번호가 할당 된다.

 

 

 

(3). 부모프로세스(PPID)의 의미 확인

 

- PPID(Parent PID)

 

# ps

   PID TTY      TIME CMD

   467 pts/3    0:00 ksh

 

# ksh

# ps

   PID TTY      TIME CMD

   467 pts/3    0:00 ksh

   490 pts/3    0:00 ksh

 

# ps -l

 F S   UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN TTY      TIME CMD

 8 S     0  467   465  0  40 20 d4f1f138    500 d4f1f1a4 pts/3    0:00 ksh

 8 S     0  490   467  0  50 20 d4f1e338    500 d4f1e3a4 pts/3    0:00 ksh

 

 

PID=467

------------+

            |

            | PID=490, PPID=467

            +----------------------

 

[그림] 자식프로세스, 부모프로세스

 

 

 

(4). UID/GID, EUID/EGID의 의미 확인

 

- UID(User Identification)

- GID(Group Identification)

- EUID(Effective UID)

- EGID(Effective GID)

 

 

 


(5). 제어 터미널의 의미 확인

 

제어 터미널 필드에 올수 있는 정보는 다음과 같다.

 

제어 터미널(Control Terminal)

/dev/pts/5

/dev/term/b

/dev/console

?

 

 

 

 

2. 프로세스 관리 (1)

 

Default Process Administration

- 프로세스 실행(Process Execution)

- 프로세스 확인(Process Verification)

- 프로세스 종료(Process Termination)

 

 

(1). 프로세스 실행

 

하나의 프로그램을 실행하면 하나의 프로세스가 된다. 프로세스는 2가지 방법 형태로 실행

이 가능하며 (a)첫번째 방식은 포그라이운드(fg, foreground)에서의 실행 이고, (b)두번째

방식은 백그라운드(bg, background)에서의 실행이다.

 

프로세스 실행 방법

(fg) # admintool

(bg) # admintool &

 

(Foreground Process)

 

fg  ksh

-----------------+                     +-----------------

                 |                     |

                 |  ksh      admintool |

                 +---------------------+

 

# admintool

# ls

 

 

(Background Process)

 

bg  ksh 

-----------------+---------------------+---------------------

                 |                     |

                 | ksh       admintool |

                 +---------------------+

 

# admintool &

[1] PID

# ls

(2). 프로세스 확인

 

실행된 프로세스를 확인할 때는 ps 명령어를 사용한다.

# ps -ef | grep inetd

 

(명령어 옵션 사용법)

# ps

# ps l         // long info

# ps -a        // user가 실행 시킨 모든 데몬

# ps -U 100 (# ps -U user01, # ps -U user01,user02,user03)

# ps -t pts/5          // TERM 5에서 실행 중인 프로세스

# ps -ef | grep inetd

 

[ps 명령어 출력 화면 해석]

# ps

PID TTY      TIME CMD

467 pts/3    0:00 ksh

 

----------------------------------------------------------------------------

종류    설 명

----------------------------------------------------------------------------

PID     프로세스 아이디(식별 번호)

TTY     제어 터미널

TIME    CPU 사용 누적 시간(Comunitive Time)

CMD     명령어

----------------------------------------------------------------------------

 

[ps -l 명령어 출력 화면 해석]

# ps -l

F S   UID   PID  PPID  C PRI NI   ADDR      SZ    WCHAN    TTY      TIME CMD

8 S   0     467  465   0 40  20  d4f1f138  500   d4f1f1a4 pts/3    0:00 ksh

 

----------------------------------------------------------------------------

종류    설 명

----------------------------------------------------------------------------

F        현재는 의미가 없음

S        프로세스의 상태정보(Process Status)

         - S : Sleeping, process is waiting for an event to complete.

         - O : Occupy, process is running on a processor.

         - R : Runnable, process is on run queue.

         - T : Stopped, either by a job control signal or because it is being traced

         - Z : Zombie, process terminated and parent not waiting

UID      프로세스 실행 사용자

PID      프로세스 아이디(식별 번호)

PPID     부모 프로세스 아이디(식별 번호)

PRI      프로세스 우선 순위(Prioty)

NI       NICE , 프로세스의 우선 순위를 조정하는 값

ADDR    프로세스의 메모리상의 주소

SZ       가상 메모리 크기

WCHAN    프로세스 락(lock) 또는 이벤트시에 사용하는 프로세스 휴식(sleep) 주소

TTY      제어터미널

TIME     CPU 사용 누적 시간

CMD      명령어

----------------------------------------------------------------------------

 

 

 

-----------------------------------------------------------------------------------

필드   

-----------------------------------------------------------------------------------

UID    The effective user ID of the process's owner.

 

PID    The process ID.

 

PPID   The parent process ID.

 

C      The processor utilization for scheduling. This field is not displayed when

       the -c option is used.

 

CLS    The scheduling class to which the process belongs:

      real-time, system, or timesharing. This field is included only with the -c

       option.

 

PRI    The kernel thread's scheduling priority. Higher numbers indicate a higher

      priority.

 

NI     The process's nice number, which contributes to its scheduling priority.

       Making a process nicer means lowering its priority.

 

ADDR   The address of the proc structure.

 

SZ     The virtual address size of the process.

 

WCHAN  The address of an event or lock for which the process is sleeping.

 

STIME  The starting time of the process (in hours, minutes, and seconds).

 

TTY    The terminal from which the process (or its parent) was started. A question

       mark indicates that there is no controlling terminal.

 

TIME   The total amount of CPU time used by the process since it began.

 

CMD    The command that generated the process.

-----------------------------------------------------------------------------------

 

[ps -ef 명령어 출력 화면 해석]

# ps -ef | more

UID     PID  PPID C  STIME     TTY      TIME CMD

root    0    0    0   10:01:51  ?        0:03 sched

----------------------------------------------------------------------------

종류    설 명

----------------------------------------------------------------------------

UID      프로세스 실행 사용자

PID      프로세스 아이디(식별 번호)

PPID     부모 프로세스 아이디(식별 번호)

STIME    프로세스 시작 시간(Start Time)

TTY      제어 터미널

TIME     CPU 실행 누적 시간

CMD      명령어

----------------------------------------------------------------------------

[참고] ps 명령어 옵션

# man ps

.....

     The ps command prints information  about  active  processes.

    Without  options, ps prints information about processes that

     have the same effective user ID  and  the  same  controlling

    terminal  as  the invoker. The output contains only the pro-

     cess ID, terminal identifier, cumulative execution time, and

     the   command  name.  Otherwise,  the  information  that  is

     displayed is controlled by the options.

 

     Some options accept lists as arguments. Items in a list  can

     be either separated by commas or else enclosed in quotes and

     separated by commas  or  spaces.  Values  for  proclist  and

     grplist must be numeric.

 

     -e     Lists information about every process now running.

 

     -f    Generates a full listing. (See below for significance

            of columns in a full listing.)

 

     -l    Generates a long listing. (See below.)

 

     -a     Lists information about all processes most  frequently

            requested: all  those  except  session  leaders  and

            processes not associated with a terminal.

 

     -t  term

            Lists only process data associated with term. Terminal

            identifiers are  specified as a device file name, and

            an identifier. For example, term/a, or pts/0.

 

     -u  uidlist

            Lists only process data whose effective user ID number

            or login name is given in uidlist. In the listing, the

            numerical user ID will be printed unless you give  the

            -f option, which prints the login name.

 

     -U  uidlist

            Lists information for processes  whose  real  user  ID

            numbers  or login  names  are  given  in uidlist. The

            uidlist must be a single argument in  the  form  of a

            blank- or comma-separated list.

......

 

 


[참고] 솔라리스 시스템의 모든 프로세스 구분

모든 프로세스 종류(Process Type)

- 데몬 (Daemon Process)

- 사용자 프로세스(User Process)

 

+-----------+ <-------+  

|           |         |

|  Daemon   |         |

|           |         |

|-----------| <-+     -e

|           |   |     |

| User Proc.|  -a,-t |

|           |   |     |

+-----------+ <-+ <---+

 

User proc

         t : term

        u : user

 

프로세스를 생성하는 것은 2종류가 있다. 사람 즉 유저가 생성하는 프로세스와 데몬이 생성하는 프로세서다.

그중에서 사용자가 생성하는 프로세스의 목록을 알고 싶다면 ps -a 명령어로 확인이 가능하고, 시스템의 모든 프로세스를 확인하고 싶다면 ps -e명령어로 확인이 가능하다.

 

[참고] Daemon 이란?

시스템을 위해 또는 서비스를 위해 백그라운드에서 동작하는 프로세스이다.

 

 

 

(3). 프로세스 종료

 

프로세스 종료 방법

# kill PID   (# kill -15 PID)

# kill -9 PID

 

* 시그널(Signal)

___________________________________________

 

1  SIGHUP   프로세세 재시작(HangUp)

2  SIGINT   인터럽트(Interrupt, <Ctrl + C>)

9  SIGKILL  강제 종료(force exit signal)

15 SIGTERM  정상 종료(exit)

___________________________________________

 

[참고] 시그널(Signal)이란?

프로세스가 생성하거나 또는 프로세스에게 보내는 비동기적 알림 이벤트이다. 대부분의

동작은 프로세스 종료(Exit), Core 파일 생성(Core), 프로세스 정지(Stop)등이다.

 

# man -s 3head signal

 

# kill -l                 // signal list 확인

# kill -l HUP

# kill -l 1

 

 

[참고] kill 명령어 사용법

# kill PID

# kill -15 PID

# kill -TERM PID

# kill -s term PID         // -s : 특별히 보낼 시그널을 지정 시그널 이름이나 번호가 온다.

# kill -s TERM PID

 

 

[EX] kill -9 명령어 실습

[TERM1] 사용자 윈도우

# telnet localhost

user01 사용자로 로그인

$ id

 

[TERM2] 관리자 윈도우

# w

  5:24오후  up  9:01,  4 users,  load average: 0.02, 0.01, 0.01

User    tty           login@  idle  JCPU   PCPU  what

.....

user01  pts/8         5:24오후                      -ksh

.....

 

# ps -U user01

   PID TTY      TIME CMD

  1185 pts/8    0:00 ksh

# kill -9 1185

 

 

[참고] pgrep 명령어

ps + grep

 

# ps -ef | grep   inetd

    root   186    1  0 08:24:03 ?        0:00 /usr/sbin/inetd -s

# pgrep  -l inetd

  186 inetd

# pgrep  -lf inetd

  186 /usr/sbin/inetd -s

 

 

[참고] pkill 명령어

ps + kill

 

# ps -ef | grep   inetd

# kill -1 inetd's PID

or

# pkill  -1 inetd

 

 

 

[참고] nice & renice

프로세스의 우선 순위 조정 명령어

- nice   : 프로세스의 실행 시킬때 우선 순위를 정의할 수 있다.

- renice : 실행중인 프로세스의 우선 순위를 정의할 때 사용한다.

 

 


3. 프로세스 관리 (2)

 

프로그램을 실행하면 한나의 프로세스가 뜨게 되고, 이것을 하나의 잡(Job)이라고 표시한

. 다음은 잡 단위로 관리하는 방법에 대한 소개이다.

 

 

(1). (Job) 실행

 

잡 실행 방법

- 포그라운드 실행 방법

- 백그라운드 실행 방법

 

         +-----bg-----+

         |            |

+-----fg-----+        |

|            |        |

|            |        |

|            |        |

|            |--------+

|            |

+------------+

 

[EX] 프로세스 실행

# sleep  500 &

[1]     576

 

# sleep  600 &

[2]     579

 

[참고]

[1]   : Job ID

576   : Process ID

 

 

 

(2). (Job) 확인 및 작업 이동

 

Process Verification

 

[EX] (Job) 작업 이동

# jobs

[2] +  Running                 sleep 600 &

[1] -  Running                 sleep 500 &

 

# fg %1

sleep 500

<Ctrl + Z>

^Z[1] + Stopped (SIGTSTP)        sleep 500 &

 

# bg %1

[1]     sleep 500 &

 

 

(3). (Job) 종료

 

프로세스() 종료(Process Exit)

# kill %1 (Process Termination)

# stop %1 (Process Stop)

 

- Ctrl+Z  (Foreground Process Stop)

- stop %1 (Background Process Stop)

 

 

[EX] 프로세스 종료

# kill %1

[1] + Terminated               sleep 500 &

 

# kill %2

[2] + Terminated               sleep 600 &

 

 

 

[참고] 솔라3리스에서 실시간 프로세스를 확인하는 명령어

sdtprocess (GUI, Graphic User Interface)

prstat     (CLI, Command Line Interface)

 

# sdtprocess

or

CDE -> pannel -> Desktop Control -> Find Process

 

sdtprocess 기능(Function)

- 정열하는 방법(CPU, MEM Sor2ting)

- Refresh 시간 지정 방법(Sampling Time)

- 프로세스 찾기(Find Process)

- 프로세스 종료(Process Kill)

 

# prstat

[참고] prstat 프로세스 모니터링

http://blog.naver.com/jwsanta?Redirect=Log&logNo=60009529440

http://blog.naver.com/jwsanta?Redirect=Log&logNo=60009529471

http://blog.naver.com/jwsanta?Redirect=Log&logNo=60009529513

 

 

[참고] UNIX 실시간 프로세스 확인 명령어

- SUN  Solaris : prstat, sdtprocess

- HP  HP-UX   : glance, top

- IBM  AIX     : topas, nmon

 

 

[참고] 유닉스 성능 점검 툴

- sar      system activity reporter

- vmstat   report virtual memory statistics

- iostat   report I/O statistics

- netstat  show network status

- mpstat   report per-processor or per-processor-set statistics


[
참고] 솔라리스 성능에 관련한 점검 툴 

[참고] 솔라리스 성능에 관련한 점검 툴

/root/docs/Reference/SolarisPerformanceAdminTool.txt

 

 

 

[참고] 시그널

 

# man -s 3head signal

     A signal is an asynchronous notification of an event. A sig-

     nal  is said to be generated for (or sent to) a process when

     the event associated with that signal first occurs. Examples

     of such events include hardware faults, timer expiration and

     terminal activity, as well as the invocation of the  kill(2)

     or  sigsend(2)  functions.   In some circumstances, the same

     event generates signals for multiple  processes.  A  process

     may  request  a  detailed  notification of the source of the

    signal  and  the  reason   why   it  was   generated.   See

    siginfo(3HEAD).

 

     Signals can be generated  synchronously  or  asynchronously.

     Events directly caused by the execution of code by a thread,

     such as a reference to an unmapped, protected, or bad memory

     can  generate  SIGSEGV or SIGBUS; a floating point exception

     can generate   SIGFPE;  and  the  execution  of  an  illegal

    instruction can generate SIGILL. Such events are referred to

     as traps; signals generated by traps are said to be synchro-

    nously  generated.  Synchronously generated signals are ini-

     tiated by a specific thread and are delivered to and handled

     by that thread.

 

     Signals may also be generated by calling kill(), sigqueue(),

     or  sigsend().  Events  such as keyboard interrupts generate

     signals, such as SIGINT, which are sent to the  target  pro-

     cess.  Such  events  are  referred to as interrupts; signals

     generated by interrupts are said to be  asynchronously  gen-

     erated. Asynchronously generated signals are not directed to

     a particular thread but are handled by an  arbitrary  thread

     that meets either of the following conditions:

 

        o  The thread is blocked in a call  to  sigwait(2)  whose

          argument includes the type of signal generated.

 

        o  The thread has a signal mask that does not include the

          type  of  signal generated. A process responds to sig-

           nals in similar ways whether it is using  threads   or

          it   is   using  lightweight  processes  (LWPs).  See

          thr_create(3THR). Each process may  specify  a  system

          action  to be taken in response to each signal sent to

           it, called the signal's disposition.  All  threads  or

          LWPs  in the process share the disposition. The set of

          system signal actions for  a  process  is  initialized

          from  that  of its parent. Once an action is installed

           for a specific signal, it  usually  remains  installed

          until another disposition is explicitly requested by a

           call to either  sigaction(), signal() or  sigset(), or

          until   the  process  execs().  See  sigaction(2)  and

          signal(3C). When a process execs,  all  signals  whose

          disposition  has  been set to catch the signal will be

           set to SIG_DFL. Alternatively, a process  may  request

           that the system automatically reset the disposition of

           a signal to  SIG_DFL after it  has  been  caught.  See

          sigaction(2) and signal(3C).

 

 

 

[참고] nice & renice

 

프로세스의 우선 순위 조정 명령어

- nice   : 프로세스의 실행 시킬때 우선 순위를 정의할 수 있다.

          (invoke a command with an altered scheduling priorit)

- renice : 실행중인 프로세스의 우선 순위를 정의할 때 사용한다.

 

 

 

(1). nice 명령어

 

     The nice utility invokes command, requesting that it be  run

     with a different system scheduling priority. The priocntl(1)

     command is a more general interface to scheduler functions.

 

     nice 명령어는 다른 시스템 스케줄링 우선순위가 동작을 요청할때

     사용하는 명령어이다.

 

     The invoking process (generally the user's shell) must be in

     a scheduling class that supports nice.

 

     사용자 쉘에서 사용하는 프로세스 요청은 스케줄링 클래스 중에

     존재해야 한다. 이때 nice 명령어를 사용할 수 있다.

 

     If the C shell (see csh(1)) is used, the full  path  of  the

    command  must be specified; otherwise, the csh built-in ver-

     sion of nice will be invoked. See csh Builtin below.

 

     csh을 사용한다면 nice 명령어의 전체 경로를 지정해야 한다.

     렇지 않으면 csh 내장명령어인 nice가 실행된다.

 

 

(명령어 형식)

# nice CMD

# nice -10 CMD

# nice --10 CMD

# nice -n 10 CMD

# nice -n -10 CMD

 

- 포그라운드로 프로그램을 실행하면 기본적인 NI 값은 20이다.

- 백그라운드로 프로그램을 실행하면 기본적인 NI 값은 24이다.

- "# nice CMD" 실행을 하면 NI 값은 10이 높아진다.

- "# nice --10 CMD" 실행을 하면 NI 값은 10이 낮아진다.

- "# nice -10 CMD" 실행을 하면 NI 값은 10이 높아진다.

 

NI --> 증가, PRI --> 증가, 우선순위 --> 낮아짐

NI --> 감소, PRI --> 감소, 우선순위 --> 높아짐

 

 

[EX] nice 명령어 실습

[TERM1]

# admintool &

# admintool

 

[TERM2]

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2329   561  0  40 20 d4eb6a50   2284 d5fbc94a 21:25:34 pts/6    0:00 admintool

 8 S     root  2328   561  0  52 24 d4f57858   2284 d5fb607a 21:25:28 pts/6    0:00 admintool

 

[TERM1]

admintool 종료 후

# nice admintool &

# nice admintool

 

[TERM2]

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2340   561  0  70 30 d4f57858   2284 d5fb65ba 21:27:40 pts/6    0:00 admintool

 8 S     root  2339   561  0  82 34 d4eb6a50   2284 d5fb607a 21:27:31 pts/6    0:00 admintool

 

[TERM1]

admintool 종료 후

# nice --10 admintool &

# nice --10 admintool

 

[TERM2]

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2366   561  0  40 10 d4f54e58   2284 d5f7c572 21:34:22 pts/6    0:00 admintool

 8 S     root  2365   561  0  40 14 d4e64748   2284 d5fb8d32 21:34:13 pts/6    0:00 admintool

 

 

[TERM1]

admintool 종료후

# nice -5 admintool &

# nice -5 admintool

 

[TERM2]

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2356   561  0  67 29 d4f54e58   2284 d5f8f14a 21:31:21 pts/6    0:00 admintool

 8 S     root  2357   561  0  55 25 d4e64748   2284 d5fb8d32 21:31:29 pts/6    0:00 admintool

 

 

 


(2). renice 명령어

 

     The renice command alters the scheduling priority of one  or

     more  running  processes.  By  default,  the processes to be

     affected are specified by their process IDs.

 

     renice 명령어는 하나 또는 그 이상의 프로세스의 스케줄링 우선

     순위를 조정하는 명령어이다.

 

     If the first operand is a number within the valid  range  of

    priorities  (-20  to 20), renice will treat it as a priority

     (as in all but the first synopsis form).  Otherwise,  renice

     will treat it as an ID (as in the first synopsis form).

 

     만약 첫번째 연산자가 숫자라면(우선순위 범위: -20 ~ 20) renice

     명령어는 우선순위를 다루게 된다. 그렇지 않다면, renice 명령어

     는 그것을 ID(PID)로 다루게 된다.

 

  Altering Process Priority

     Users other than the privileged  user  may  only  alter  the

    priority  of  processes they own, and can only monotonically

     increase their "nice value" within the range 0 to  19.  This

    prevents  overriding  administrative  fiats.  The privileged

     user may alter the priority  of  any  process  and  set  the

     priority to any value in the range -20 to 19. Useful priori-

     ties are: 19 (the affected  processes  will  run  only  when

     nothing else in the system wants to); 0 (the "base" schedul-

     ing priority),; and any negative value (to  make  things  go

     very  fast).  20  is  an  acceptable nice value, but will be

     rounded down to 19.

 

     권한이 있는 사용자들은 단지 자신의 프로세세에 대한 우선순위를

     조정할 수 있다. 그리고 "nice value" (value is 0 to 19) 명령어

     를 통해서 우선순위를 일정하게 증가만 시킬수 있다. 이것은 관리

     자의 명령어 수행과 중첩되는 것을 막아 준다.  권한이 있는 사용

     자 어떤 프로세스의 우선순위를 조정할 수 있을 것이다.  그리고

     우선순위를 설정하기 위한 값의 범위는 "-20 ~ 19"로 설정 할 수

     있다.

     19 => 일반적인 우선순위(시스템에서 영향을 받지 않는 경우)

     0  => "base" 스케줄링 우선순위

     negative value => 더 높은 우선순위를 나타냄

     20 => 사용할 수 있는 nice 값이다. 그러나 19로 설정할 수도 있

     .

 

 

(명령어 형식)

 

# renice 15 PID

# renice -15 PID

# renice -n 15 PID

# renice -n -15 PID

 

- 포그라운드로 프로그램을 실행하면 기본적인 NI 값은 20이다.

- 백그라운드로 프로그램을 실행하면 기본적인 NI 값은 24이다.

- "# renice CMD" 실행을 하면 현재 NI 값에 10이 더 높아진다.

- "# renice 10 CMD" 실행을 하면 NI 값은 기본값(20) 10이 더 높아진다.

- "# renice -10 CMD" 실행을 하면 NI 값은 기본값(20) 10이 더 낮아진다.

 

NI --> 증가, PRI --> 증가, 우선순위 --> 낮아짐

NI --> 감소, PRI --> 감소, 우선순위 --> 높아짐

 

 

[EX] renice 명령어 실습

[TERM1]

# admintool &

# admintool

 

[TERM2]

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  52 24 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  40 20 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

# renice 5 2474     

# renice 5 2475

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  55 25 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  55 25 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

# renice 10 2474

# renice 10 2475

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  70 30 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  70 30 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

# renice 40 2474

renice: 40:getpriority: No such process

# renice 40 2475

renice: 40:getpriority: No such process

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  97 39 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  97 39 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

renice 명령어 다음에 있는 40 PID 번호로 인식했다. renice 명령어의 최대 범위는 20

지이다. 이것을 넘으면 renice 명령어를 그냥 실행 한 것과도 같아 진다. renice 명령어를

우선순위 값 없이 사용한다면 이전의 NI 값에 10을 더하게 된다. 하지만 NI의 최대 범위는

39를 넘을 수 없다.

 

아래와 같이 원래 우선순위로 조정한다.

 

# renice 4 2474

# renice 0 2475


# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474  561  0  52 24 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  40 20 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

# renice 2474

# renice 2475

# pps admintool

 F S      UID  PID  PPID  C PRI NI     ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  82 34 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  70 30 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

# renice 2474

# renice 2475

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  97 39 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  97 39 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

renice 명령어 다음에 있는 40 PID 번호로 인식했다. renice 명령어의 최대 범위는 20
지이다. 이것을 넘으면 renice 명령어를 그냥 실행 한 것과도 같아 진다. renice 명령어를
우선순위 값 없이 사용한다면 이전의 NI 값에 10을 더하게 된다. 하지만 NI의 최대 범위는
39
를 넘을 수 없다.

아래와 같이 원래 우선순위로 조정한다.

 

# renice 4 2474

# renice 0 2475

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  52 24 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  40 20 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

# renice -10 2474

# renice -10 2475

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  40 10 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  40 10 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

# renice -19 2474

# renice -19 2475

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  40  1 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  40  1 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

# renice -25 2474

# renice -25 2475

# pps admintool

 F S      UID  PID  PPID  C PRI NI    ADDR     SZ    WCHAN    STIME TTY      TIME CMD

 8 S     root  2474   561  0  40  0 d4e64748   2284 d5fb607a 22:17:42 pts/6    0:00 admintool

 8 S     root  2475   561  0  40  0 d4eb6350   2284 d5f61c12 22:17:47 pts/6    0:00 admintool

 

 renice 명령어를 통해서 NI 값의 최소 범위는 -19이다. 이것보다 더 큰 값을 쓰더라도 모

  -19로 인식된다.

 renice 명령어를 통해서 NI 값의 최소 범위는 -19이다. 이것보다 더 큰 값을 쓰더라도 모
-19로 인식된다.

 


2008. 8. 8. 01:15

Chapter 7. Korn Shell Characteristic

Chapter 7.  Korn Shell Characteristic

_________________________________

 

 

Redirection

Pipe

Korn Shell Function

Variable

Korn Shell Metacharacter

History

Alias

Environment File

 

 

■ 커널의 기능

- 하드웨어 자원 관리

- Device 관리

- 메모리 , 가상메모리 관리

 

 

쉘의 기능(Shell Function)

- 명령어 해석기(Command Interpreter)

- 프로그램 할수 있는 언어(Programable Language)

 

 

(1). 방향 재지정(Redirection)

 

 

fd(파일 기술자, File Descriptor)

 

[EX] 프로그램에서의 File Descriptor

main()

{

    int fd;

    fd=open(......);

}

 

 

예약되어진 파일 기술자(File Descriptor)

---------------------------------------

번호  설 명

---------------------------------------

0    표준입력 stdin (Standard Input)

1    표준출력 stdout(Standard Ouput)

2    표준에러 stderr(Standard Error)

---------------------------------------

 

 

stdin(Keyboard)======> SHELL ========> stdout(Monitor)

                            |

                            |

                     stderr(Monitor)

 

         [그림] 표준입력, 표준출력, 표준에러

 

[EX] 표준출력, 표준에러의 예

# ls /var /nodir

 

 

[EX] 표준입력, 표준출력의 예

# cat

Hello    stdin

Hello    stdout

Solaris

Solaris

<Ctrl + D>

 

# cat <  /etc/passwd

# cat >  filename

Hello

Solaris

<Ctrl + D>

# cat filename

 

 

 

(1.1) 입력 재지정(Redirection stdin)

 

[FORMAT]  CMD   <   filename

          CMD  0<  filename

          CMD  <<  filename(X) => Here Documentation

 

# mailx  -s "Solaris TEST" root@example.com < mail.txt

 

[참고] mailx 명령어를 통한 메일 보내기

# mailx  root

Subject: Solaris TEST  <---- 메일 제목 입력("Solaris TEST")

test mail for user01  <---- 내용 입력

<ctrl+D>  or  .        <---- <Ctrl + D> 입력

#

 

 

 

(1.2) 출력 재지정(Redirection stdout)

 

[FORMAT]  CMD   >   filename

          CMD  1>   filename

           CMD  >>   filename

          CMD  1>>  filename

 

# ls -l > file.txt

# cat file.txt

 

[참고] '>>'(출력 리다이렉션)을 사용한 파일 내용 추가

 

----file1----

    1111

    2222

-------------

 

# echo 1111 > file1

# echo 2222 > file1

# cat file1

# echo 3333 >> file1

 

 

 

(1.3) 에러 재지정(Redirection stderr)

 

[FORMAT]  CMD  2>   filename

          CMD  2>>  filename

 

# ls /var /nodir > file.txt

 

Standard Output

Standard Error

 

# ls /var /nodir 2> file.txt

 

Standard Output

Standard Error

 

# ls /var /nodir > file1.txt 2>    file2.txt

 

Standard Output

Standard Error

 

# ls /var /nodir > file1.txt 2>&1    

// > 로 표준 출력을 file1.txt에 주고 2> 로 표준에러를 &1(표준출력) 로 리디렉션

 

[참고]  Redirection : CMD > filename

         PIPE        : CMD | CMD

 

# ls -l  1> 1

 

[참고] 터미널 출력이 있는 명령어 수행시

# cmd > file.log      (X)

# cmd > file.log 2>&1 (0)

 

[참고] CMD 2>/dev/null

일반사용자 전체 시스템의 파일과 디렉토리 목록중에 core 파일을 찾을려고 할때 검색할려고

하는 내용보다 권한이 되지 않아서 'Permission Denied' 에러 메세지가 더 많이 출력되는 경

우가 존재할 수 있다. 이런 경우 명령어의 마지막에 '2>/dev/null'을 붙여서 에러메세지는

보지 않고 정상적인 출력 결과만 보는 경우가 있다.

 

$ find / -name core -type f 2>/dev/null

 

 

[참고] confiugre --prefix=/usr/local/apache 2> apache.log

# ./configure --prefix=/usr/local/apache 2> apache.log

# ./configure --prefix=/usr/local/apache > apache.log 2>&1

 

 

 


(2). pipe

앞의 CMD의 출력 결과가 뒤의 CMD 입력값으로 들어간다.

 

[FORMAT] CMD  |    CMD

            -------

            -------

           Kernel Buffer

 

 

# ls -l | grep Error (X)

 

 

# ls -l > file.txt

# grep Error file.txt

 

ls -l          grep Error file.txt

      file.txt

 

# ls -l | grep Error

    ----------

    ----------

   Kernel Buffer

 

 

[EX] pipe 활용 예

# ps -ef | more          (# CMD | more) 한페이지가 넘는 페이지 출력 방법 지정

# ps -ef | grep   inetd  (# CMD | grep inetd) 앞단의 명령어의 출력 결과 중 패턴 검색

 

 

[참고] tee 명령어

 

# ps -ef | grep inetd > file.log

      -------             A

              ------------+

       -------

# ps -ef | grep inetd | tee file.log

 

                ----------           

                ---+ +----          

                    | |

                  file.log

 

EX) tee 명령어 실습

CMD > file.log

CMD | tee file.log

# cal 2002 > file1.log

# cal 2002 | tee file2.log

 

tee 입력값을 화면과 파일에 동시에 출력 시켜줌

 


(3) 콘셀의 기능(Korn Shell Function)

 

# set -o

....

ignoreeof         off

....

markdirs off

....

noclobber         off

....

vi                on

....

 

# set -o vi

# set +o vi

 

 

 

(3.1) 파일 덮어쓰기 방지 기능

 

set -o noclobber

 

# set -o noclobber

# set -o | grep noclobber

# echo 1111 > file1

# echo 2222 > file1

ksh: file1: file already exists    <----- 메세지 확인

 

[참고] CMD >| file1

# echo 3333 >| file1

 

 

(3.2) 파일 이름 자동 완성 기능 & 명령행 편집

 

Filename Completion & Command Line Edit

set -o vi

set -o emacs

# set -o vi

# export EDITOR=vi

# export VISUAL=vi

 

 

(a). 명령행 편집(Command Line Edit)

k (pre-CMD)

j (back-CMD)

h(<-), l(->)

w, b, dd, d$, d0

 

[EX] Command Line Edit

# find / -name core -type f

<Ctrl + C>

# <ESC><K>

# find / -name file1 -type f

 

 

(b). 파일 이름 자동 완성 기능(Filename Completion)

(실습 준비)

# cd /test

# rm -r *

# mkdir dirname1

# touch file.log

 

(자동 완성 기능 실습)

# cd dir<ESC><\>

 

# cd /test

# mkdir dir2

# cd dir<ESC><\>

<ESC><=>

1) dir2/

2) dirname1/

# cd dirn<a><ESC><\>

 

[참고] 와일드 카드(Wild Card)

# cd dirn*

dirname1

dir1

 

[참고] Copy & Paste

(1). Select, Drag & Drop

(2). Mouse Right Button Click & Edit Menu Selection

(3). Ctrl + Insert, Shift + Insert

 

 

 

 

 

[정리] 긴 이름을 가진 파일/디렉토리 다루기

(a). 파일이름자동 완성 기능 사용

(b). 와일드 카드 사용

(c). 복사 & 붙이기

 

 

 

 

 

(3.3) 로그 아웃 방지 기능

 

set -o ignoreeof

 

EOF(End Of File)의 의미를 갖는 <Ctrl + D>가 존재한다.

 

<Ctrl + D>의 의미는?

(a). 파일의 끝을 알려 주는 기능

(b). 현재 프로그램 종료()의 기능

갖는다.

 


(a). 파일의 끝 의미를 갖는 <Ctrl + D>

# mailx root

> Subject : TEST

hello

<Ctrl + D>

 

(b). 현재 프로그램() 종료의 의미를 갖는 <Ctrl + D>

# telnet 172.16.8.254

root 사용자로 로그인

# <Ctrl + D> => 로그아웃된다.

 

# telnet 172.16.8.254

root 사용자로 로그인

# set -o ignoreeof

# <Ctrl + D> => 로그아웃 되지 않는다.

# exit

 

 

 

(4) 변수(Variable)

- 지역 변수(Local Variable)

- 환경 변수(Global Variable, Environment Variable)

- 특수 변수(Special Variable)

// 지역변수와 환경변수의 차이는 export 되었는지에 따라 다르다.

 

(4.1) 변수 선언(Variable Define)

 

sh ------> ksh ------> zsh ------> bash

 

(본쉘 스타일)

(a). 변수를 선언하는 방법

# VAR=5    (변수의 값으로는 숫자나 문자 구별하지 않는다.)

# VAR=hello

# export VAR

 

(b). 변수의 내용을 확인하는 방법

# echo $VAR

 

(c). 변수의 내용을 초기화 하는 방법

# unset VAR

 

(콘쉘 스타일)

(a). 변수를 선언하는 방법

# export VAR=hello

 

(b). 변수의 내용을 확인하는 방법

# print $VAR

 

(c). 변수의 내용을 초기화 하는 방법

# unset VAR

 

 

[EX] 변수 선언 테스트

# VAR=hello

# echo $VAR

# unset  VAR

# echo $VAR

 

 

 

(4.2) export의 의미

# ps

   PID TTY      TIME CMD

   408 pts/3    0:00 ksh

 

# VAR1=5

# VAR2=10

# export VAR2

 

# ksh

# ps

   PID TTY      TIME CMD

   408 pts/3    0:00 ksh

   994 pts/3    0:00 ksh

 

# echo $VAR1

# echo $VAR2

 

# exit

# echo $VAR1

# echo $VAR2

 

 

VAR1=5,  VAR2=10

-----------------+                      +-----------------

                |                   |

                | VAR1=?, VAR2=?    |

                +-------------------+

 

 

 

(4.3) EDITOR, VISUAL

기본적인 편집기를 선언할 때 사용.

 

# EDITOR=vi

# EDITOR=/usr/bin/vi

# export EDITOR

or

# VISUAL=vi

# VISUAL=/usr/bin/vi

# export VISUAL

or

# set -o vi

 

[참고] 기본적인 편집기 선언

OS(썬 개발 프로그램)   : Default Editor (set -o vi)

Oracle DB              : EDITOR

 

 

[참고] set / env

set   : 모든 변수(지역변수 + 환경변수)

env   : 환경변수

 

# VAR1=ITBANK   => 지역변수

# VAR2=SOLARIS  => 환경변수

# export VAR2

 

# set | grep VAR1 (0)

VAR1=ITBANK

# set | grep VAR2 (0)

VAR2=SOLARIS

 

# env | grep VAR1 (X)

# env | grep VAR2 (0)

VAR2=SOLARIS

 

0: View

X: Not View

 

 

 

(4.4) PS1

쉘 프롬프트를 정의할 때 사용하는 변수

 

- root 사용자의 쉘프롬프트 : #

- 일반 사용자의 쉘프롬프트 : $

 

# PS1=[solarisXXX]#

# export PS1

 

# PS1='$PWD> '

# PS1='[$PWD]# '

# export PS1

 

[참고] Bash Shell에서의 PS1 정의 방법

쉘프롬프트: [solaris254@root:/]#

(ksh ) # PS1=[`hostname`@$LOGNAME:'$PWD]# '// 명령어+자신의이름+현재폴더

(bash) # PS1='[\h@\u:\w]$$'

 

 

(4.5) PATH

명령어 검색 위치 지정 변수

 

# PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/dt/bin:/usr/ccs/bin:/usr/openwin/bin:/usr/ucb

# export PATH

 

EX) ls 명령어 수행

# ls -l

# /usr/bin/ls -l

# cd /usr/bin

# ./ls -l

 

 

[참고] 스크립트 디렉토리

/root/bin, /root/shell : 스크립트 디렉토리

# PATH=$PATH:/root/shell

# export PATH

# script.sh

 

 

[참고] 명령어 실행시 에러 메시지

# cmd

......

ksh: command: not found

......

# find / -name cmd -type f

- 1> 명령어가 없는 경우(-> 명령어 설치)

- 2> PATH 변수에 명령어의 경로가 정의가 않은 경우(-> PATH 변수에 경로 추가)

 

EX) ethereal & printmgr

# ethereal (ksh : ethereal: not found) => 프로그램이 설치 안된 경우

# printmgr (ksh : printmgr: not found) => PATH 변수에 경로가 추가 되지 않은 경우

 

 

 

(4.6) MANPATH

매뉴얼 페이지 검색 경로를 지정할 때 사용

 

# MANPATH=/usr/man:/usr/dt/man:/usr/local/man

# export MANPATH

 

# man ls

(매뉴얼 페이지가 보인다.)

# echo $MANPATH

......:/usr/man:...... (/usr/man ---> /usr/share/man)

 

 

[참고] 매뉴얼 페이지 디렉토리 확인

# cd /usr/share/man

# ls

 

 

 

(4.7) LD_LIBRARY_PATH

라이브러리의 경로를 검색할때 사용하는 변수

 

# LD_LIBRARY_PATH=/usr/lib:/usr/local/lib:/usr/local/lib

# export LD_LIBRARY_PATH

 

라이브러리

- 동적 라이브러리(Dynamic Lib.)    : XXXXXX.so

- 정적 라이브러리(Static Lib.)     : XXXXXX.a

 

EX) ls 명령어의 동적 라이브러리 확인

# ldd /usr/bin/ls

         libc.so.1  =>    ?

         libdl.so.1 =>    /usr/lib/libdl.so.1

         /usr/platform/SUNW,Ultra-5_10/lib/libc_psr.so.1

......

ld.so.1: gs: fatal error: libpng.so.2 : open fail : no such file or directory

......

 

# find / -name "libpng.so.2" -type f 2>/dev/null

- libpng.so.2 라이브러리를 찾은 경우

- libpng.so.2 라이브러리를 찾을 수 없는 경우

 

(a). 라이브러리 파일을 찾은 경우

# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

 

(b). 라이브러리 파일을 못 찾은 경우

http://docs.sun.com -> 검색창 -> "libpng.so.2"-> SUNWxxx

http://www.sunfreeware.com

# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

 

 

[참고] 솔라리스 패키지 설치시 고려해야 하는 변수

패키지(Package)

-----------------------

Binary Command(Daemon)  => /usr/local/bin

Configuration File

Library                 => /usr/local/lib

Manual                  => /usr/local/man

Documentation

-----------------------

- PATH

- MANPATH

- LD_LIBRARY_PATH

 

 

 

(4.8) 기타 환경 변수

HOME / PWD / LOGNAME

# echo $HOME

/

# echo $PWD

/test

# echo $LOGNAME

root

 

EX) $HOME의 활용

# cd

# cd $HOME

 

 

 

(4.9) 특수 변수(Special Variable)

- $ : 현재 쉘의 PID 번호를 저장하고 있다.

- ? : 바로 이전 명령어의 정상 실행 여부에 대한 결과 값이 들어 있다.

- ! : 바로 이전 백그라운드 프로세스에 대한 PID 번호를 저장하고 있다.

- 인자변수($0, $1, $2, ....)

 

# echo $$

450

# ps

 

# cal

# echo $?

 

# ls /nodir

# echo $?

 

# sleep 200 &

[1] 450

# echo $!

 

 

[참고] Login Variables

---------------------------------------------------------------

변수이름   선언주체         설명

---------------------------------------------------------------

LOGNAME    login            사용자 로그인 이름 정의

HOME       login            사용자의 홈디렉토리 정의

SHELL      login            사용자의 기본 쉘 정의

PATH       login            사용자의 명령어 검색 경로 정의

MAIL       login            사용자의 mailbox 경로 정의

TERM       login            사용자의 사용 터미널 정의

LPDEST     기본 선언 아님   기본 프린터 정의

PWD        shell            현재 작업 디렉토리 정의

PS1        shell            쉘 프롬프트 정의(sh, ksh)

prompt     shell            쉘 프롬프트 정의(csh)

---------------------------------------------------------------

 

 

 

 

 

[정리] 변수(Variable)

 

- 변수 선언 방법(Variable Definition)

- export 의미?

- 쉘 환경 변수(Shell Environment Variable)

         EDITOR, PATH, MANPATH, LD_LIBRARY_PATH

 

- 지역변수(Locale Variable)

- 환경변수(PATH, MANPATH, LD_LIBRARY_PATH, etc)

- 특수변수(Special Variable)

         $$, $?, $!

 

 

 

 

 

 

 

(5) Korn Shell Metacharater

 

- ' ' :  작은 따옴표(single quote)

- " " :  큰 따옴표(double quote, $, ` `, \)

- ` ` :  역 따옴표(back quote)

- \   :  역 슬래쉬(back slash)

- ;   :  세미콘론(semicolon)

 

[EX] 작은 따옴표 실습(single quote)

// 작은 따옴표는 안에 들어 있는 모든 것들의 쉘 해석을 막는다. 특별한 의미가 없이 그냥 하나의 문자로 인식이 된다. 문자는 공백을 포함한다.

# echo $HOME

# echo '$HOME'

 

[EX] 큰 따옴표 실습(double quote)

// 큰 따옴표는 작은 따옴표와 같은 동작을 하지만 $ , ``, \ 문자의 해석은 제외한다.

# echo "$HOME"

# echo "$HOME is my   directory."

 

[EX] 역 따옴표 실습(back quote)

// 쉘은 역따옴표 안에 있는 것을 명령어로 생각 하고 실행하게 된다.

 

# hostname

# echo `hostname`

# echo `date`

# echo "`hostname` is my hostname.!!!"

# echo "$(hostname) is my hostname.!!!"

 

[EX] 역 슬래쉬 실습(back slash)

// 쉘은 역 슬래쉬 뒤에 오는 것의 의미를 제한하도록 한다.

# echo $HOME

# echo \$HOME

# echo "\$HOME is my directory"

 

# find / -name core -type f -exec rm {}     \;

# find / -name core -type f -exec rm {}     ';'

 

(참고) \

-> `명령어` : 명령어 실행 결과 출력 표시

-> 명령어 \ : 명령어가 아직 끝나지 않음을 표시

         # ls -l

         # ls \

         > -l

 

[EX] 세미콜론 테스트(semicolon)

excution mutliple command a line

 

# date ; cal ; ls -l

# date

# cal

# ls -l

 

 

 

(6) history

 

 

|        | STACK

|        |

|        |

+--------+

 

# history

# history -r (reverse)

# history -n (not number)

# history -5

 

[참고] 히스토리 참고 파일 및 변수

~/.sh_history 히스토리 내용을 지속적으로 저장하는 파일

HISTSIZE    히스토리를 기록하는 Stack의 크기를 지정하는 파일

HISTFILE    히스토리 내용을 지속적으로 저장하는 파일 이름 지정

 

[EX] HISTSIZE, HISTFILE 변수 지정

# HISTSIZE=128 ; export HISTSIZE

# HISTFILE=~/.sh_history ; export HISTFILE

 

     HISTSIZE

           If this variable is set when  the  shell  is  invoked,

          then  the  number  of previously entered commands that

           are accessible by this shell will be greater  than  or

          equal to this number.  The default is 128.

 

     HISTFILE

           If this variable is set when  the  shell  is  invoked,

          then  the  value is the pathname of the file that will

           be used to store the  command  history.  (See  Command

          re-entry below.)

 

 

[참고] r (re-excution)

# history

# r

# r 450

# r vi

# r etc=var 450          ( 450 # vi /etc/dir1/dir2/dir3/filename)

 

 

 

(7) alias

 

선언 방법       # alias    cp='cp -i'

 

선언 확인 방법  # alias

                # alias    cp

 

선언 해제 방법  # unalias cp

 

 

[참고] unalias & Backslash

# \rm -r dir1

 

EX) \rm -r dir1 실습

# cd /test

# mkdir dir1

# cd dir1

# touch file1 file2 file3 file4

# cd ..

# alias rm='rm -i'

# rm -r dir1

rm: examine files in directory dir1 (y/n)? <Ctrl + C>  <----- '<Ctrl + C> 입력

# \rm -r dir1

 

(참고) rm -f (force)

# rm -rf dir1 (일부 유닉스)

 

 

 

 

[정리] 콘쉘의 특징

- Redirection

- Pipe

- Korn Shell Function

- Variable

- Metacharacter

- history

- alias




(8) 환경 파일

 

사용자 로그인시   적용되는 환경파일

 

/etc/profile : 전체 사용자 환경 설정 파일

~/.dtprofile : CDE 환경 사용자 환경 설정 파일 (DTSROUCEPROFILE=true)

~/.profile   : 개인 사용자 환경 설정 파일  (ENV=/.kshrc)

~/.kshrc     : 개인 사용자 환경 설정 파일

 

 

사용자가 CDE 환경으로 로그인하게 되는 경우

/etc/profile

~/.dtprofile

~/.profile

~/.kshrc

파일들이 읽혀 진다. 

 

사용자가 Command Line Login을 하는 경우

/etc/profile

 

~/.profile

~/.kshrc

파일들이 읽혀 진다.

 

/etc/profile ~/.dtprofile, ~/.profile은 로그인시에 한번 읽혀 지고, ~/.kshrc 파일은 콘

쉘이 실행될때 마다 실행이 된다.

 

 

(8.1) /etc/profile

* ~/.profile ~/.kshrc        파일에 정의 될수 있는 모든것들에 대해 정의 가능

* 시스템의 모든 사용자에게 적용할 것에 대한 정의

 

 

(8.2) ~/.profile

* 변수 선언

- PATH

- ENV

- EDITOR

- 기타

 

 

(8.3) ~/.kshrc

* 특정 변수 선언(PS1)

* set -o 설정

* alias  설정

 

 

[참고] 솔라리스 기본 환경 파일 해석

/etc/profile

~/.profile   (-> ENV_main.sh)

~/.kshrc     (-> ENV_main.sh)

 

 

(a). /etc/profile 파일의 해석

 

---------------- /etc/profile 해석-------------------------------

trap ""  2 3 -----> /etc/profile 파일을 실행하는 동안(로그인시) 2번 시그널,

                    3번 시그널을 받아도 종료하지 않는다.

export LOGNAME PATH

-----> 변수 export(/usr/bin/login)

 

if [ "$TERM" = "" ]      -----> $TERM 변수가 선언 안되어 있으면

then

        if /bin/i386     -----> i386(32bits) 일반운영체제

        then

                TERM=sun-color

        else

                TERM=sun

        fi

        export TERM

fi

 

#       Login and -su shells get /etc/profile services.

#       -rsh is given its environment in its .profile.

 

case "$0" in               -----> -ksh /etc/profile

-sh | -ksh | -jsh | -bash)          A

                                    +----- $0

        if [ ! -f .hushlogin ] -----> ~/.hushlogin 파일이 존재하지 않으면    

        then

                /usr/sbin/quota -----> Quota 실행

                #       Allow the user to break the Message-Of-The-Day only.

                trap "trap '' 2"  2

                /bin/cat -s /etc/motd  -----> 로그인시 /etc/motd 내용 출력

                trap "" 2

 

                /bin/mail -E    -----> 새로운 메일이 존재 하면

                case $? in

                0)

                        echo "You have new mail."

                        ;;

                2)

                        echo "You have mail."

                        ;;

                esac

        fi

esac

 

umask 022    -----> UMASK 설정

trap  2 3

--------------------------------------------------------------------

(b). ~/.profile 해석

 

------------------------ ~/.profile 해석 ----------------------------

# (1). stty erase ^H

stty erase ^H    # <Backspace>

# stty erase ^?  # <Delete>

 

-----> Set Terminal Type

         # tty

         # stty

         # stty -a

         ..... erase = ^h .....

         # stty erase <DELETE>

 

# (2). ENV Variable

ENV=~/.kshrc

-----> 추가적인 환경 파일 정의

 

 

# (3). EDITOR Variable

EDITOR=/usr/bin/vi

-----> 기본적인 편집기 선언 변수

 

 

# (4). PATH Variable

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/ucb

PATH=$PATH:/usr/dt/bin:/usr/ccs/bin:/usr/openwin/bin

PATH=$PATH:/usr/lib/netsvc/yp:/usr/apache/bin

PATH=/usr/sfw/bin:/usr/sfw/sbin:/usr/local/sbin:/usr/local/bin:$PATH

PATH=/usr/local/ssl/bin:$PATH

-----> 명령어의 실행 위치 정의 변수

 

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/ucb\

:/usr/dt/bin:/usr/ccs/bin:/usr/openwin/bin\

:/usr/lib/netsvc/yp:/usr/apache/bin\

:/usr/sfw/bin:/usr/sfw/sbin:/usr/local/sbin:/usr/local/bin\

:/usr/local/ssl/bin

 

 

# (5). MANPATH Variable

MANPATH=/usr/share/man:/usr/man:/usr/openwin/share/man

MANPATH=/usr/sfw/share/man:/usr/local/man:/usr/local/ssl/man:$MANPATH

 

 

# (6) LD_LIBRARY_PATH Variable

LD_LIBRARY_PATH=/usr/lib:/usr/secure/lib:/usr/local/lib

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/ssl/lib:/usr/sfw/lib

 

 

export ENV EDITOR PATH MANPATH LD_LIBRARY_PATH

---------------------------------------------------------------------------

 

 


(c). ~/.kshrc 파일의 해석

 

------------------------ ~/.kshrc 파일 해석 -------------------------------

# (1). set -o

set -o vi

set -o trackall  -----> Tracked Alias // 사용된 명령어를 PATH를 뒤지지 않고 기억하고 있다 (빠른검색)

# set -o ignoreeof

# set -o noclobber

 

 

# (2). PS1 Variable

-----> 쉘 프롬프트 정의 변수

# PS1=[$LOGNAME@`hostname`:'$PWD]# '            # EX) [root@solaris254:/]#

# PS1=[`hostname`@'$PWD]# '                     # EX) [solaris254@/]#

# PS1='$PWD'"[`hostname`]# "                    # EX) /etc[sun02]#

# PS1='$PWD> '                                  # EX) /etc>

PS1=['$PWD]# '                                  # EX) [/]#

export PS1

 

 

# (3). alias

# (a). 기본적인 alias

alias c='clear'

alias h='history'

alias cp='cp -i'

alias mv='mv -i'

alias rm='rm -i'

alias ls='ls -hF'

alias llt='ls -aihlF'

alias ll='ls -ailhF | more'

 

# (b). 필요한 경우 선언하는 alias

alias lsf='ls -al | grep ^-'

alias lsd='ls -al | grep ^d'

alias dir='ls -ailhF | more'   -----> 윈도우즈 명령어 실행 alias

alias ipconfig='ifconfig -a'   -----> 윈도우즈 명령어 실행 alias

 

#alias cat='cat -n'

alias df='df -h'

alias nslookup='/usr/sbin/nslookup'

 

# (c). 편리한 기능의 alias

/*

         Webserver(Apache)

         /etc/apache/httpd.conf -----> Configuration File

         /var/apache/htdocs     -----> Source Directory

         /var/apache/logs       -----> Log Directory

         설정 파일을 빨리 편집하도록 하는 기능

*/

alias fconfig='vi /etc/ftpd/ftpaccess'

alias hconfig='vi /etc/apache/httpd.conf'

# 소스디렉토리 이동

alias hdir='cd /var/apache/htdocs'

# 로그파일 모니터링

alias mlog='tail -f /var/adm/messages'

alias slog='tail -f /var/adm/sulog'

alias sslog='tail -f /var/log/syslog'

 

 

# (4). Function

-----> alias pps='ps -ef | head -1 ; ps -ef | grep $1' 같은 기능 제공

pps () {

    if [ $# -ne 1 ] ; then

        echo Usage : $0 Process

    fi

    /usr/bin/ps -elf | head -1

    /usr/bin/ps -elf | grep $1 | grep -v grep

}

 

ppss () {

    if [ $# -ne 1 ] ; then

        echo Usage : $0 Process

    fi

    /usr/ucb/ps -aux | head -1

    /usr/ucb/ps -aux | grep $1 | grep -v grep

}

 

-------------------------------------------------------------------------

 

 

 

 

 

(8.4) 쉘별 환경 파일(sh/ksh/csh User Initialization File)

_______________________________________________________________________________

 

Shell   User           Description

        Initialization

        File

_______________________________________________________________________________

 

sh      /etc/profile    Defines system wild environment at login

        $HOME/.profile  Defines user's environment at login

 

csh     /etc/.login     Defines system wild environment at login

        $HOME/.cshrc    Defines user's environment for all C shells

                        invoked after login shell

        $HOME/.login    Defines user's environment at login

 

ksh     /etc/profile    Defines system wild environment at login

        $HOME/.profile  Defines user's environment at login

        $HOME/$ENV      Defines user's environment at login in the file

                        specified by the Korn shell's ENV environment variable

_______________________________________________________________________________

 

 


[참고] 배쉬쉘 환경 파일(Bash Shell User Initialization Files)

/etc/profile        전체 사용자 환경 파일

~/.bash_profile      사용자 개인 환경 파일

~/.bashrc            사용자 개인 환경 파일

 

 

 

(8.5) 사용자 기본 환경 파일(Default User Initialization Files)

 

/etc/skel (skelton)

_________________________________________

 

Shell           Default File

_________________________________________

 

csh            /etc/skel/local.login

                /etc/skel/local.cshrc

ksh            /etc/skel/local.profile

_________________________________________

 

 

 

[EX] /etc/skel 디렉토리

# useradd -m -d /export/home/user03 -s /bin/ksh user03

# passwd user03

 

# ls -al /export/home/user03

# ls -al /etc/skel

 

# cat > /etc/skel/.exrc

set showmode

set number

<Ctrl + D>

 

# useradd -m -d /export/home/user04 -s /bin/ksh user04

# passwd user04

 

# ls -al /export/home/user04

# ls -al /etc/skel

 

 

 

[참고] 관리자가 사용자의 환경 초기화하는 방법

- /etc/profile 사용하는 방법

- /etc/skel 사용하는 방법

 

 

 


(8.6) 사용자 변수 선언(User Variable Definition)

 

사용자 변수 선언시 sh 계열과 csh 계열은 차이점이 존재한다.

 

(a). csh 계열(csh/tcsh style)

 

변수 선언 방법    # setenv VAR 5

 

변수 확인 방법    # echo $VAR

 

변수 해제 방법    # unset VAR

 

 

 

(b). sh 계열(sh/ksh/zsh/bash style)

 

변수 선언 방법    # VAR=5

                  # export VAR

 

변수 확인 방법    # echo $VAR

 

변수 해제 방법    # unset VAR


2008. 8. 7. 21:37

Chapter 6. Vi 편집기

Chapter 6.  Vi Editor

________________________

 

screen-oriented(visual) display editor based on ex

 

(1). vi 편집기의 특징(Visual Editor Characteristic)

 

- 전체 화면 모드 편집기(Full Screen Editor, Visual Editor)

- ex 편집기의 기능 확장 편집기(vi editor based on ex.)

 

[참고] /root/docs/Fundamental/Ref_vi_example.txt

 

 

 

(2). vi  편집기 실행하기

 

# vi  (: w filename)

# vi filename

# vi -r  filename (recovery)   // 복구 모드

# vi L                       // 리스트 찾기 , 에러난 파일

# vi +38 filename             // 수정 작업을 38(특정)라인에서 바로 시작할 때!

 

     -L    Lists the name of all files saved as the result of  an

          editor or system crash.

 

     -r filename

          Edits  filename  after  an  editor  or  system  crash.

          (Recovers  the  version  of  filename  that was in the

          buffer when the crash occurred.)

 

[EX] vi -r filename 형식의 예

# mailx

..... (중략) .....

A copy of an editor buffer of your file "/etc/vfstab" was saved on solaris254

when the system went down.

This buffer can be retrieved using the "recover" command of the editor.

An easy way to do this is to give the command "vi -r /etc/vfstab".

This works for "edit" and "ex" also.

 

 

[EX] vi -L 형식의 예

# vi -L

/usr/preserve/root:

On   1 01 at 09:00, saved 0 lines of file ""

On   1 17 at 12:27, saved 61 lines of file "/.kshrc"

On   2 15 at 10:13, saved 21 lines of file "/etc/dfs/dfstab"

On   1 31 at 19:48, saved 11 lines of file "/tmp/crontabVwaWPh"

/var/tmp:

No files saved.

 

 

 

(3). vi  Mode 변경

 

- Command Mode (ESC Mode), Edit Mode

- Input/Insert Mode

- Last Line Mode(Ex Mode)

 

 

<Command Mode>  ----- (i, a, o, I, A, O) -----> <Input Mode>

   A   |        <---- (    ESC         ) ------

   |   |

   |   |

   |   +------------- (<Shift+:>, /, ? ) -----> <Last Line Mode>

  +----------------- (    Enter       ) ------

  

* insert, append, open line

 

              [그림] vi 편집기 모드 변환

 

 

 

(4). Command Mode

(4.1) Move

- h, j,  k, l                // 상하좌우 커서이동

- b, w                       // b : back word 이동 , w : word 이동

- 0(^),  $                   // $ : 라인끝 이동  0(^) : 현재행의 처음으로~

- Ctrl+F / Ctrl+B          // 페이지단위 이동

 

- G, 1G, 10G               // nG    : n행으로 이동

- :5, :10                  //  n  : n행으로 이동

 

 

 

(4.2) Delete

- x, dd(=D), 3dd(=3D)      // x : 현재커서의 한글자 삭제

- :1,3d                    // 1 ~ 3 라인 삭제

- dw                       // 한 단어 삭제

- d0, d$          // d0 : 현재커서에서 라인 처음까지 삭제 , d$ : 현재커서에서 라인 끝가지 삭제

- dG                       // dG : 현재커서에서 문서의 마지막까지 삭제

- 3dd                      // 현재에서 3라인 삭제

- d1G                      // 현재에서 1라인까지 삭제

 

(4.3) Copy(Yank) & Paste

- yy(=Y), 3yy(3Y), p or    P                 // yy : 1라인 복사

- :1,3 co 5                                 // 1라인부터 3라인 까지 복사 5라인아래에 paste

- :1,3 m 5                                  // 1~ 3 까지 5라인 밑으로 move

 

 

 

(4.4) Search

- /New,  n or N                     // 탐색 결과에서 n -> 정방향 탐색 N -> 역방향 탐색

- ?New,  n or N                     // /pattern -> 현재에서 정방향탐색

                                   // ?pattern -> 현재에서 역방향 탐색

 

 

 


(4.5) Search & Replace

- :%s/Old/New/g               // %s   : search    ,  /g   : gloval  문서전체의~

                       // old 를 찾아 new로 치환

- :5,10s/Old/New/g     // 5~ 10 라인 ~  "

 

EX) : %s/Hello/HELLO/g

     1,$ => 5,10s/Hello/HELLO/g

     search

     globally => %s/Hello/HELLO/ , %s/Hello/HELLO/g

 

EX) :5,10s/^/#/

    :5,10s/^#//

 

    :5,10s/^/    / (4 blank character)

 

 

 

(4.6) Undo

- u, U            //실행 취소

 

 

 

(4.7) Join Line

- J               // 아래 라인을 현재 라인으로 붙여 준다.

 

 

 

(4.8) Replace

- r, R            // r : 현재커서의 한문자를 치환 , R : 현재커서부터 치환상태로

 

 

 

(4.9) Save & Quit

- :w              // 저장

- :w filename     // filename으로 저장

- :w!             // 강제저장

- :q              // 종료

- :q!             // 강제 종료

- :wq             // 저장 후 종료

- :wq!(root Use)  // 강제 저장 종료

- :!CMD           // vi 편집기 에서 쉘 명령어 실행

 

[참고] Save & Quit

- :x

- :wq

- ZZ

 

 

 


(5). vi  편집기의 환경 설정

 

(5.1). vi 편집기 사용시 환경설정

# vi filename

.....

: set                              // 현재 setting 목록

: set all                          // 설정할수 있는 모든 목록

: set number  (or :set nu)        // 라인넘버 부여

: set nonumber (or :set nonu)      // 번호 없앰

 

[EX] vi 편집기의 기능(:set all)

+- 기능이름---+--- number    --> : set number

|            +--- nonumber -->  : set nonumber

+- 기능이름=               --> : set 기능이름=

 

 

 

(5.2). vi 편집기 환경파일

 

* ex editor  =>  vi editor  => vim editor (iMprove vi)

 ~/.exrc                      ~/.vimrc

 

# vi ~/.exrc

set nu showmode sm ai

 

or

 

# vi ~/.exrc

set number                 // 편집기의 라인번호

set showmode               // 편집기의 모드 표시

set showmatch              // 편집기 작업시 매칭되는 문자들을 표시한다.

set autoindent             // 자동 들여쓰기

 

 

[참고] set list, set ic

set list - Display invisible charaters, such as ^I for a Tab and as $ for end-of-line

set ic   - Instructs searches to ignore case


출처 : http://cafe.daum.net/bscsolaris

2008. 8. 7. 18:50

Chapter 5. Unix Basic Commands _ 아카이브/압축 관련 명령어

압축(Compress)

compress / uncompress CMD

gzip / gunzip CMD

 

아카이브(Archive)

tar CMD

cpio CMD

 

압축 + 아카이브

zip CMD

jar CMD

 


아카이브 vs 압축

아카이브는  묶음을 만드는 것이며 압축과는 다르다.


 


 

compress/uncompress CMD

___________________________

 

compress, uncompress, zcat - compress, uncompress  files  or display expanded files

 

[compress]

     The compress utility will attempt to reduce the size of  the

     named files by using adaptive Lempel-Ziv coding. Except when

     the output is to the standard  output,  each  file  will  be

    replaced  by  one  with  the extension .Z, while keeping the

     same ownership modes, change times and  modification  times.

     If  appending  the  .Z  to  the file pathname would make the

     pathname exceed 1023 bytes, the command  will  fail.  If  no

     files  are  specified, the standard input will be compressed

     to the standard output.

 

[uncompress]

     The uncompress utility will restore files to their  original

     state  after  they  have  been compressed using the compress

     utility. If no files are specified, the standard input  will

     be uncompressed to the standard output.

 

[zcat]

     The  zcat  utility  will  write  to  standard   output  the

    uncompressed  form  of files that have been compressed using

     compress. It is the equivalent of uncompress -c. Input files

     are not affected.

 

 

 

---- file1 -----

aaaaa                                  a(addr1,addr2,addr3,....)

bbbbb              ====Compress===>    b(addr1,addr2,addr3,....)

ccccc                                  .......

----------------

 

                      [그림] 압축의 원리

 

 


(압축에 대한 예1)

- 똑같은 페이지 수를 가지고 있는 두개의 파일을 압축하더라도 압축 효율은 서로 틀리다.

  이유는 반복되는 글자 수가 서로 틀리기 때문이다.

 

(압축에 대한 예2)

- 압축된 파일을 다시 압축하거나 바이너리 파일을 다시 압축하는 경우는 압축효율이 떨어

  질수 있다. 이유는 반복되는 글자가 많지 않고 글자 종류의 수가 증가 하기 때문이다.

 

  Compress File --- Compress ---> size(?)

  Binary File   --- Compress ---> size(?)

 

 

(파일 압축)

# compress file

file.Z

 

(파일 압축 확인)

# zcat file.Z

# uncompress -c file.Z

 

(파일 압축 해제)

# uncompress file.Z

file

 

 

[EX] compress 명령어 실습

# cd /test

# cp /etc/inet/inetd.conf file1

 

# compress file1

file1.Z

# ls -l (File Size)

 

# zcat file1.Z (0)

# cat file1.Z  (X)

 

# uncompress file1.Z

# ls -l (File Size)

 

 

 

 

 


gzip/gunzip CMD

____________________

 

gzip, gunzip, gzcat - compress or expand files

 

[gzip]

     Gzip reduces the size of the named  files  using  Lempel-Ziv

    coding  (LZ77).  Whenever possible, each file is replaced by

     one with the extension .gz, while keeping the same ownership

    modes,  access  and modification times.  (The default exten-

     sion is -gz for VMS, z for MSDOS, OS/2 FAT, Windows  NT  FAT

     and Atari.)  If no files are specified, or if a file name is

    "-", the standard input is compressed to the  standard  out-

     put.   Gzip will only attempt to compress regular files.  In

    particular, it will ignore symbolic links.

 

[gunzip]

     gunzip takes a  list  of  files  on  its  command  line  and

     replaces each file whose name ends with .gz, -gz, .z, -z, _z

     or .Z and which begins with the correct magic number with an

    uncompressed  file  without  the original extension.  gunzip

     also recognizes the special  extensions  .tgz  and  .taz  as

    shorthands   for  .tar.gz  and  .tar.Z  respectively.   When

    compressing, gzip  uses  the  .tgz  extension  if  necessary

     instead of truncating a file with a .tar extension.

 

[gzcat]

     gzcat is identical to gunzip -c. (On some systems, zcat  may

     be  installed  as  gzcat  to  preserve  the original link to

     compress.) gzcat uncompresses either a list of files on  the

    command   line   or  its  standard  input  and  writes  the

    uncompressed data on standard output.  gzcat will uncompress

     files that have the correct magic number whether they have a

     .gz suffix or not.

 

 

(파일 압축)

# gzip file

file.gz

 

(파일 압축 확인)

# gzcat  file.gz

or

# gunzip -c file.gz

 

(파일 압축 해제)

# gzip -d file.gz (-d : decompress)

file

or

# gunzip file.gz

file

 

 


[EX] gzip 명령어 실습

# cp /etc/inet/inetd.conf file2

# gzip file2

file2.gz

# ls -l     (파일의 크기 점검)

 

# gzcat file2.gz (0)

# cat file2.gz  (X)

 

# gzip -d file2.gz

file1

# ls -l     (파일의 크기 점검)

 

 

 

 

 

tar CMD

____________________

 

create tape archives and add or    extract  files

 

(명령어 형식)

# tar cvf file.tar file1 file2 file3   (c: create)

# tar tvf file.tar                     (t: contents)

# tar xvf file.tar                     (x: extract)

 

 

[참고] 테이프 백업 방법(Tape Device Backup)

# tar cvf /dev/rmt/0n /export/home

# tar cvf /dev/rmt/0n file1 file2 file3

 

 

[참고] 디렉토리 마이그레이션(Migration)

Directory Copy using tar CMD.

작업 내용:  /test1 => /test2

 

# cd /test1

# tar cvf - . | (cd /test2 ; tar xvf -)

 

 

[EX] tar 명령어 실습

(실습 준비)

# cd /test

# rm -r *

 

# cp /etc/passwd file1

# cp file1 file2

# cp file1 file3

# ls -l file*

 

(tar 명령어를 사용한 실습)

# tar cvf file.tar file1 file2 file3

# ls -l file*

 

# rm file1 file2 file3

# tar tvf file.tar

 

# tar xvf file.tar

# ls -l file*

 

(tar 명령어를 사용한 디렉토리 마이그레이션)

# mkdir -p /test1

# mkdir -p /test2

 

# cp /etc/default/* /test1

# ls /test1

 

# cd /test1

# tar cvf - . | (cd /test2 ; tar xvf -)

 

# ls /test1

# ls /test2

 

 

 

 

 

cpio CMD

____________________

 

copy file archives in and out

 

     The cpio command  copies  files  into  and  out  of  a  cpio

     archive. The cpio archive may span multiple volumes. The -i,

     -o, and -p options select the action to  be  performed.  The

    following  list describes each of the actions. These actions

     are mutually exclusive.

 

  Copy In Mode

     cpio -i (copy in) extracts files from  the  standard  input,

     which  is  assumed  to  be the product of a previous cpio -o

     command. Only files with names that match one  of  the  pat-

     terns are selected. See sh(1) and OPERANDS for more informa-

     tion about pattern. Extracted files are conditionally copied

     into  the  current  directory  tree,  based  on  the options

     described below. The permissions of the files will be  those

     of the previous cpio -o command. The owner and group will be

     the same as the current user, unless the current user is the

    super-user. If this is the case, owner and group will be the

     same as those resulting from the previous cpio  -o  command.

    Notice  that  if cpio -i tries to create a file that already

     exists and the existing file is  the  same  age  or  younger

    (newer),  cpio will output a warning message and not replace

     the file. The -u  option  can  be  used  to  unconditionally

     overwrite the existing file.

 

  Copy Out Mode

     cpio -o (copy out) reads a list of file path names from  the

    standard  input  and copies those files to the standard out-

     put, together with path name and status information  in  the

     form  of  a  cpio  archive. Output is padded to an 8192-byte

     boundary by default or  to  the  user-specified  block  size

     (with  the  -B  or  -C  options) or to some device-dependent

     block size where necessary (as with the CTC tape).

 

  Pass Mode

     cpio -p (pass) reads a list of  file  path  names  from  the

     standard input and conditionally copies those files into the

    destination directory tree, based on the  options  described

     below.

 

 

     -i    (copy in) Reads an archive from the standard input and

          conditionally  extracts  the files contained in it and

          places them into the current directory tree.

 

     -o    (copy out) Reads a list of file path  names  from  the

          standard  input and copies those files to the standard

          output in the form of a cpio archive.

 

     -p    (pass) Reads a list of file path names from the  stan-

          dard  input  and conditionally copies those files into

           the destination directory tree.

 

     -c    Reads or writes header information in ASCII  character

           form for portability. There are no UID or GID restric-

          tions associated with this  header  format.  Use  this

          option  between  SVR4-based  machines,  or  the -H odc

          option between unknown machines. The -c option implies

          the  use  of  expanded  device numbers, which are only

          supported on  SVR4-based  systems.  When  transferring

          files  between  SunOS  4  or  Interactive UNIX and the

          Solaris 2.6 Operating environment or  compatible  ver-

           sions, use -H odc.

 

     -v    Verbose. Prints a list of file and extended  attribute

          names. When used with the -t option, the table of con-

          tents looks like the output of an ls -l  command  (see

          ls(1)).

 

     -b    Reverses the order of the bytes within each word.  Use

           only with the -i option.

 

     -B    Blocks input/output 5120  bytes  to  the  record.  The

          default buffer size is 8192 bytes when this and the -C

          options are not used. -B does  not  apply  to  the  -p

 

     -d    Creates directories as needed.

 

     -m    Retains previous file modification time.  This  option

           is ineffective on directories that are being copied.

 

     -I file

          Reads the  contents  of  file  as  an  input  archive,

          instead  of the standard input. If file is a character

          special device, and the current medium has  been  com-

          pletely read, replace the medium and press <RETURN> to

           continue to the next medium. This option is used  only

           with the -i option.

 

     -O file

          Directs the output of cpio to  file,  instead  of  the

          standard output. If file is a character special device

           and the current medium is full, replace the medium and

           type a carriage return to continue to the next medium.

           Use only with the -o option.

 

cpio는 표준 입력으로부터 파일의 이름을 입력받고, 표준출력으로 목록명을 얻어서

하나 또는 복수개의 파일을 압축하는데 사용된다. cpio 3개의 다름 모드가 존재

한다.

 

Copy In   Mode : cpio -i, 표준 입력으로 들어온 파일들을 extract 한다.

Copy Out  Mode : cpio -o, 표준 입력으로 부터 파일을 얻어서 이들 파일을 가지고

                    그들의 pathname과 함께, 새로운 파일을 생성한다.

Pass Mode      : cpio -in, copy-out 모드와 같다. 다만 새로운 파일이 생기는 것이

                    아니라 디렉토리 구조를 그대로 copy 한다는 것만 다르다.

 

(명령어 형식 예)

# find . -print | cpio -o[aBcv] > file.list

# cpio -ivt < file.list

# cpio -i[cdlmv] < file.list

# find . -print | cpio -p[adlmuv] directory

 

[EX1] 현재 디렉토리를 tape Backup 

# find . -print | cpio -ocvB > /dev/rmt/0

 

[EX2] Tape의 목차를 출력

# cpio -iBtv < /dev/rmt/0

 

[EX3] Backup 받은 tape로부터 restore

# cpio -iBvd < /dev/rmt/0

 

[EX4] 특정 파일을 find 명령어로 출력하여 archive file restore

# find . -name 'file*' -print | cpio -ocvB > file.list

 

[EX5] 디렉토리 /export/home/user01 디렉토리를 /export/home/user02 backup

# cd /export/home/user01

# find . -print | cpio -pdmv /export/home/user02

 

[EX6] 현재 디렉토리 파일들을 새로운 파일(newfile)로 아키이빙

# ls | cpio -ocv > /test/newfile

 

[EX7] 디렉토리 안에서 파일 풀기

# cd /test

# cat newfile | cpio -icd "memo/a1" "memo/b*"



zip CMD

____________________

 

zip, zipcloak, zipnote, zipsplit - package  and  compress (archive) files

 

     zip is a compression and file packaging  utility  for  Unix,

     VMS,  MSDOS,  OS/2,  Windows NT, Minix, Atari and Macintosh,

     Amiga and Acorn RISC OS.

 

     It is analogous to a combination of the UNIX commands tar(1)

     and  compress(1)  and  is compatible with PKZIP (Phil Katz's

     ZIP for MSDOS systems).

 

# man zip

.....

     -r   Travel the directory structure recursively;  for  exam-

          ple:

 

              zip -r foo foo

 

          In this case, all the files and directories in foo  are

          saved  in  a zip archive named foo.zip, including files

          with names starting with ".", since the recursion  does

          not  use  the shell's file-name substitution mechanism.

          If you wish to include only a specific  subset  of  the

          files  in directory foo and its subdirectories, use the

          -i option  to  specify  the  pattern  of  files  to  be

          included.   You  should  not use -r with the name ".*",

          since that matches ".."  which will attempt to  zip  up

          the parent directory (probably not what was intended).

.....

 

# man unzip

.....

     -c   extract files to stdout/screen (``CRT'').  This  option

          is  similar  to  the  -p option except that the name of

          each file is printed as it is extracted, the -a  option

          is  allowed,  and  ASCII-EBCDIC conversion is automati-

          cally performed if appropriate.   This  option  is  not

          listed in the unzip usage screen.

.....

 

(파일 압축)

# zip file.zip file1 file2 file3

 

(파일 압축 확인)

# unzip -c file.zip

 

(파일 압축 해제)

# unzip  file.zip

 

[참고] 명령어 호환

Unix zip 명령어<-> Unix jar 명령어

Unix zip 명령어<-> Window zip 명령어




jar CMD

____________________

 

archive  tool for Java archives

 

# jar cvf file.jar file1 file2 file3

# jar tvf file.jar

# jar xvf file.jar

 

 

 

 

 

dd CMD

---------------------

 

convert and copy a file

 

     The dd utility copies the specified input file to the speci-

     fied  output  with  possible conversions. The standard input

     and output are used by default. The input and  output  block

     sizes  may  be  specified  to take advantage of raw physical

     I/O. Sizes are specified in bytes; a number may end with  k,

     b,  or  w  to  specify  multiplication  by  1024, 512, or 2,

    respectively. Numbers may also be separated by x to indicate

     multiplication.

 

     The dd utility reads the input one block at  a  time,  using

     the  specified input block size. dd then processes the block

     of data actually returned, which could be smaller  than  the

    requested  block  size. dd applies any conversions that have

     been specified and writes the resulting data to  the  output

     in blocks of the specified output block size.

 

 

# man dd

.....

     if=file

          Specifies  the  input  path.  Standard  input  is  the

           default.

 

     of=file

          Specifies the output  path.  Standard  output  is  the

          default.  If  the  seek=expr  conversion  is  not also

          specified, the output file will  be  truncated  before

          the  copy begins, unless conv=notrunc is specified. If

          seek=expr is specified, but conv=notrunc is  not,  the

          effect  of  the copy will be to preserve the blocks in

           the output file over which dd seeks, but no other por-

           tion  of  the  output  file will be preserved. (If the

           size of the seek plus the size of the  input  file  is

          less  than  the  previous size of the output file, the

          output file is shortened by the copy.)

 

     bs=n  Sets both input and output block  sizes  to  n  bytes,

          superseding ibs= and obs=. If no conversion other than

          sync, noerror, and notrunc is  specified,  each  input

          block  is  copied  to  the  output  as  a single block

           without aggregating short blocks.

 

     skip=n

          Skips n input blocks (using the specified input  block

          size)  before starting to copy. On seekable files, the

          implementation reads the blocks or seeks past them. On

           non-seekable  files,  the blocks are read and the data

           is discarded.

 

     seek=n

          Skips n blocks (using the specified output block size)

          from  beginning of output file before copying. On non-

          seekable files, existing blocks  are  read  and  space

          from  the current end-of-file to the specified offset,

           if any, is filled with null bytes. On seekable  files,

          the  implementation  seeks  to the specified offset or

          reads the blocks as described for non-seekable files.

 

     count=n

          Copies only n input blocks.

.....     

 

(명령어 형식)

# dd if=filename of=filename bs=n seek=n skip=n count=n

(if : Input File, of : Output File, bs : Block Size)

 

 

[EX1] 큰 파일 생성(Big File creation)

# dd if=/dev/zero of=/swap/swapfile bs=1024 count=102400

 

[EX2] VTOC/Super Block 삭제

# dd if=/dev/zero of=/dev/rdsk/c0t0d0s4 bs=512 count=1

# dd if=/dev/zero of=/dev/rdsk/c0t0d0s4 bs=512 count=32

# dd if=/dev/zero of=/dev/rdsk/c0t0d0s1 bs=512 skeep=11 count=1

 

[EX3] 디스크 마이그레이션(Disk Migration)

# dd if=/dev/dsk/c0t0d0s2 of=/dev/dsk/c0t1d0s2

# dd if=/dev/rdsk/c0t0d0s2 of=/dev/rdsk/c0t1d0s2 bs=4096

# dd if=/dev/rdsk/c0t0d0s2 of=/dev/rdsk/c0t1d0s2 bs=128k

 

[EX4] 테잎 장치에 백업

# dd if=/dev/rdsk/c0t0d0s7 of=/dev/rmt/0

# dd if=/dev/rmt/0 of=/dev/rmt/1

 

[참고문서] /root/docs_html/Reference/DiskMigration.txt


출처 : http://cafe.daum.net/bscsolaris

2008. 8. 7. 17:47

Chapter 5. Unix Basic Commands _ 링크 관련 명령어

ln CMD

__________

 

make hard or symbolic links to files

 

     The ln utility may be used to create  both  hard  links  and

    symbolic  links.  A  hard link is a pointer to a file and is

    indistinguishable from the  original  directory  entry.  Any

     changes to a file are effective independent of the name used

     to reference the file. Hard links may not span file  systems

     and may not refer to directories.

 

■ 하드 링크(Hard Link)

■ 심볼릭 링크(Symbolic Link, Soft Link)

 

 

(1) 하드 링크(Hard Link)

# ln file1 file2

- file1, file2의 용량은    같은가?

- file1, file2 inode number    같은가?

- file1을 편집하면 file2의 내용은 어떤가?

- "ls -li file*"하면 특이한 변화는 있는가?

- When Original   File Delete!!

- filesystem을 넘어서 링크를 걸수 있는가?

 

 

(2) 십볼릭 링크(Symbolic Link)

# ln -s  file1 file2

- file1, file2의 용량은    같은가?

- file1, file2 inode number    같은가?

- file1을 편집하면 file2의 내용은 어떤가?

- "ls -li file*"하면 특이한 변화는 있는가?

- When Original   File Delete!!

- filesystem을 넘어서 링크를 걸수 있는가?

 

 

(기본 설정 점검)

- 파일에 관련한 하드 링크는 1이다.

- 디렉토리 관련한 하드 링크는 2이다.

 

(실습 준비)

# mkdir /test

# cd /test

# rm -r *

 

(기본 설정 점검 실습)

# touch file1

# ls -l file1

-rw-r--r--   1 root     other          0  2  5 15:42 file1

Hard Link Count : 1

 

# mkdir dir1

# ls -l

drwxr-xr-x   2 root     other        512  1  8 20:47 dir1

Hard Link Count : 2

 

 

[EX] 하드 링크 실습

# echo 111 > file1

# cat file1

 

# ln file1 file2

# ls -l        (파일의 크기 점검, 링크 카운트)

# ls -li      (Inode 번호 점검)

# echo 2222 >> file2

# cat file2

 

# cat file1    (파일의 내용 확인)

 

# rm file1    (원본 파일(Original File)을 지우면!!)

# cat file2

 

 

[EX] 심볼릭 링크 실습

# ln -s file2 file3

# ls -l        (파일의 크기 점검, 링크 카운트 점검)

# ls -li      (Inode 번호 점검)

# echo 3333 >> file3

# cat file2    (파일의 내용 점검)

 

# rm file2    (원본 파일(Original File)을 지우면!!)

# cat file3

 

 

[참고] 일반 파일의 하드 링크 확인 방법(링크 카운트 값을 확인한다.)

file1 file2가 하드링크가 되어 있는지 확인 하는 방법

- ls 명령어의 -i 옵션을 사용하여 Inode 번호를 확인 한다.

         # ls -li file*

- find 명령어의 -inum 옵션을 사용한다.

         # find . -inum 450 -type f



심볼릭 vs 하드 링크

다른 파티션or 슬라이스를 넘어서 링크를 걸 수 있다.

하드링크에서는 모든게 원본 파일이 된다.



출처 : http://cafe.daum.net/bscsolaris

2008. 7. 22. 13:28

Chapter 5. Unix Basic Commands _ 파일/디렉토리 검색 관련 명령어

검색에 관련한 명령어

grep 명령어

find 명령어



grep CMD

__________________

search a file for a pattern

globally/regular/expression

The grep utility searches text files for a pattern and

prints all lines that contain that pattern. It uses a com-

pact non-deterministic algorithm.

Be careful using the characters $, *, [, ^, |, (, ), and \

in the pattern_list because they are also meaningful to the

shell. It is safest to enclose the entire pattern_list in

single quotes '...'.

If no files are specified, grep assumes standard input. Nor-

mally, each line found is copied to standard output. The

file name is printed before each line found if there is more

than one input file.


(
명령어 형식)

grep OPTION(s) PATTERN filename


(
기본 사용법)

# grep root /etc/passwd


[
참고] 실무 사용예

# CMD | grep inetd

# cat /etc/passwd | grep root (# grep root /etc/passwd)

# ps -ef | grep inetd

# pkginfo | grep Apache

# patchadd -p | grep 115158-10


# cat /var/adm/messages | grep 'Jan'

# cat /var/adm/messages | grep 'Jan 15'

# cat /var/adm/messages | grep 'Jan 15 14:'

# cat /var/adm/messages | grep 'Jan 15 14:26:'

# cat /var/adm/messages | grep warn

# cat /var/adm/messages | grep inetd


(
옵션 사용법)

# grep -c root /etc/passwd (-c : count) // -c : 개수

# grep -n root /etc/passwd (-n : number line) // -l : 찾은 라인 넘버

# grep -l root /etc/hosts /etc/passwd /etc/group (-l : list files) // - : 찾은 파일 list

# grep -v root /etc/passwd (-v : inVerse, except) // -v : 제외

# grep -i root /etc/passwd (-i : ignore case, 대문자/소문자) // -I : 대소문자 구분 없이


[
참고] -c, -n 옵션

쉘 스크립트에서 많이 활용하고 있다.


[
참고] grep -v 명령어 실습

# prtconf

# prtconf | grep -v not

Not attached devide


[
참고] grep -l 명령어 실습

부팅과정(Boot Sequence)

Server PowerON => POST => Boot Program => Kernel => init process

......

Server Error

......

# grep -l "Server Error" /etc/rc?.d/* // Sever Error 메시지를 나타낸 파일 리스트를 보여줌

/etc/rcS.d/S30network.sh

# vi S30network.sh

....

/Server Error

....

if [ Condition ] ; then

Statement(Action)

else

echo "Server Error"

fi



(
패턴 사용법)

정규화된 표현식(Regular Expression)

. no...y //임의의 문자 1개 대용

[ab] [Rr]oot // [Rr] oot고정 R or r 매치

[a-c] [a-c]bc // [a-c] bc고정 a,b,c 에서 매치

[^a] [^a]bc // [^a] bc고정 첫글자 a를 제외한 한 개 글자 ?????????????

? /etc/rc?.d/ // ? 한 개의 모든 문자

* file* // file 뒤에 모든 것 1나 이상의

^root ^root // 라인의 처음이 root로 시작

root$ root$ // 라인의 끝이 root



# grep 'PATTERN(s)' filename

# grep 'no...y' /etc/passwd

# grep '[Rr]oot' /etc/passwd

# grep 'r*t' /etc/passwd

# grep '^root' /etc/passwd

# grep 'root$' /etc/group

[참고] egrep / fgrep

- egrep 명령어(Extended grep)

- fgrep 명령어(Fixed grep)

# egrep '(Network|uucp) Admin' /etc/passwd

# fgrep '*' /etc/system




find CMD

__________________

find files

The find utility recursively descends the directory hierar-

chy for each path seeking files that match a Boolean expres-

sion written in the primaries given below.

find will be able to descend to arbitrary depths in a file

hierarchy and will not fail due to path length limitations

(unless a path operand specified by the application exceeds

PATH_MAX requirements).



(1). find / -name core -type f

                                d

(2). find / -user user01 -group    staff -type f

(3). find / -atime -7  -type f (atime : access time)

             -mtime  7          (mtime : modify time)

                    +7

(4). find / -perm -4000    -o -perm -2000 -type f

            -perm  755

                   -755

(5). find / -size  3000c -type f

                    +3000c

                    -3000c

(6). find / -name core -type f -exec rm {} \;


(EX) find CMD
실습


(
실습 준비)

# cd /test

# rm -r *

# touch file1 file2

# mkdir dir1 dir2

# touch dir1/file1

# touch dir2/file3

 

/ - test -+- dir1 - file1

          +- dir2 - file3

          +- file1

          +- file2


[
그림] 실습 환경


(
첫번째 형식) find / -name core -type f

# cd /test

# find . -name file1 -type f

./dir1/file1

./file1


[
참고] # find . -name "*.log" -type f


(
두번째 형식) find / -user user01 -group staff

# ls -l file1 (file1: root other)

# chown user01 file1

# ls -l file1 (file1: user01 other)

# find . -user user01 -type f

./file1


(
세번째 형식) find / -mtime 7 -type f

# cd dir2

# touch file1 file2 file3 file4 file5 file6

# date

현재 시간: 126 1111 (23 1750)

# touch -t 12051111 file2

# touch -t 12041111 file3

# touch -t 12031111 file4

# touch -t 12021111 file5

# touch -t 12011111 file6


파일은 미래에 만들었다는 것은 없다

아래와같이 된다.

                                               mtime +3

                                               +----+

                                                                       mtime -3

                                                        20 21 22+----+----+

                                                          19 mtime 3

                                            ----+----+----+----+----+----+----+----+----+----+

                                                17   18   19   20   21   22

                                                                            now


# ls -l file*

# find . -mtime 3 -type f

./file4

# find . -mtime -3 -type f

./file3

./file1

./file2

# find . -mtime +3 -type f

./file5

./file6


(4번째 형식) find / -perm -4000 -o -perm -2000 -type f

-perm 644  (rw-r--r--)

-perm -644 (rw-r--r--)

      -6XX  rw-

            rwx

      -4XX  r--

            r-x

            rw-

            rwx

-perm -4000 (최소한 SetUID bit 인것)


# find /test -perm 644 -type f

# find /test -perm -644 (rw-r--r--)

(rwxr-xr-x)


# cd /test

# mkdir dir3

# cd dir3

# touch file1 file2 file3 file4 file5 file6 file7 file8

# chmod 000 file1 (---)

# chmod 100 file2 (--x)

# chmod 200 file3 (-w-)

# chmod 300 file4 (-wx)

# chmod 400 file5 (r--)

# chmod 500 file6 (r-x)

# chmod 600 file7 (rw-)

# chmod 700 file8 (rwx)


# find . -perm 600 -type f -ls (rw-) //
600

# find . -perm -400 -type f -ls (r--) // 400 이상


(
다섯번째 형식) find / -size 500c -type f

# cd /test/dir2

# cp /etc/passwd file10

# ls -l file10 (size : 560 bytes)

# cp /etc/inet/inetd.conf file11

# ls -l file11 (size : 6961 bytes)


# find . -size 560c -type f // size
가 딱 560c

# find . -size +560c -type f // size 560c 초과

# find . -size -560c -type f // size 560c 미만


(
여섯번째 형식) find / -name core -type f -exec rm {} \;

# cd /test

# find . -name file1 -type f

# find . -name file1 -type f -exec rm {} \;

# ls -R



[
참고] find 명령어 활용예


■ 로그 파일 정책(Log Policy)

- 로그 디렉토리 안에 로그 파일이 최근 30일 로그 기록만 남기도록 한다.

# crontab -e

Mi Ho Da Mo We CMD

0 5 1 * * find /Log_Dir -name "*.log" -type f -mtime +30 -exec rm {} \;

분 시 일 월 주


find 명령어의 다른 옵션들

# find / -nouser -type f

# find / -nogroup -type f

# find / \( -type f -o -type d \) -perm -0002 -ls

# find / -perm -o=w -type f -print


find 명령어를 통한 퍼미션 변경

/test/dir01 -+- file1

             +- file2

             +- dir02 - file3

             +- dir03


file* => 640(rw-r-----)


# find /test/dir01 -type f -exec chmod 640 {} \;

# find /test/dir01 -type f -name "*.log" -exec chmod 640 {} \;


[EX] find
명령어를 활용한 퍼미션 변경

# find /test/dir01 -type f -ls

# find /test/dir01 -type f -exec chmod 640 {} \;

# find /test/dir01 -type f -ls


[
참고] 로그 파일이 너무 많다면 !!!!!

- Log_Dir/* (100만개 이상의 로그파일)


# cd /Log_Dir

# rm *

로그 파일을 지울수 없거나 혹은 지우것을 확인하기 어렵다.

# cd ..

# ls

Log_Dir

# rm -r Log_Dir

# ps

# rm -r Log_Dir &

# while [ 1 ]

> do

> ps | grep rm | grep -v grep

> sleep 2

> done


[
참고] 서버 해킹을 당한 경우의 간단한 처리


(1).
로그 백업

# cp -r /var /backup/var.20060816

# cd /var/adm/"logfile"


(2).
히스토리 확인

# history > /backup/history.20060816

# cat ~/.sh_history



(3).
프로세스 확인

# ps -ef | more


(4). find
명령어 활용

# find / -mtime -7 -type f 2>/dev/null

# find / -nouser -type f

# find / -perm -2 -type f


출처 : http://cafe.daum.net/bscsolaris

2008. 7. 22. 12:07

Chapter 5. Unix Basic Commands _ 자주 사용되지는 않는 명령어

자주 사용되지는 않는 명령어

cmp CMD / diff CMD

sort CMD

file CMD

 

 

 

cmp CMD / diff CMD

__________________

 

compare  two files    // 텍스트 비교

 

     The cmp utility compares two files. cmp will write no output

     if  the  files  are the same. Under default options, if they

     differ, it writes to  standard  output  the  byte  and  line

     numbers  at  which  the first difference occurred. Bytes and

     lines are numbered beginning with 1. If one file is an  ini-

     tial subsequence of the other, that fact is noted. skip1 and

     skip2 are initial byte offsets into file1 and file2  respec-

     tively,  and  may  be  either  octal or decimal; a leading 0

     denotes octal.

 

     The diff utility will compare  the  contents  of  file1  and

     file2  and write to standard output a list of changes neces-

     sary to convert  file1  into  file2.  This  list  should  be

     minimal. Except in rare circumstances, diff finds a smallest

     sufficient set of file differences. No output will  be  pro-

     duced if the files are identical.

 

(명령어 형식)

# cmp file1 file2 두개의 파일에 대한 간략한 차이점 확인

# diff file1 file2         두개의 파일에 대한 자세한 차이점 확인

# diff -c file1 file2      // -c  : 좀더 디테일하게

 

[EX] cmp 명령어 실습

# cd /test

# cat >  file1

1111

2222

3333

<CTRL + D>

# cat file1

 

# cp file1 file2

 

# cat >  file3

1111

2222

4444

<CTRL + D>

# cat file3

 

file1 <------> file2 : 같은 파일

file1 <------> file3 : 다른 파일

# cmp file1 file2

# cmp file1 file3

file1 file3 differ: char 11, line 3

 

# diff file1 file2

# diff file1 file3

# diff -c file1   file3

 

 

[참고] cmp 명령어를 사용한 백업 파일과 원본 파일 비교

 

  원본 DISK                  백업 테이프

--------------            ----------------

 

설정파일

/etc/ftpd/ftpaccess       /etc/ftpd/ftpacess

  A                                   |

--|------------               --------|-------

  |                                   |

  +--->  원본 파일과 비교 <--------+ 복구

 

# cd /test

# cp /etc/ftpd/ftpaccess /test

# cp ftpaccess ftpaccess.orig

# vi ftpaccess

......

[수정 전]

chmod           no              anonymous

delete          no              anonymous

[수정 후]

chmod           yes             anonymous

delete          yes             anonymous

 

# diff ftpaccess ftpaccess.orig

(출력 결과 분석)

 

 

[참고] cmp 명령어를 통한 파일의 무결성 점검(File Consistency Check)

 

파일 무결성 점검 스크립트 파일의 원리(File Check Principle)

(1). /etc/passwd => /etc/passwd.old

(2). cmp /etc/passwd /etc/passwd.old

 

cmp /etc/passwd   /etc/passwd.old   > file.txt

 

if [ -s  file.txt ] ; then

    Action1

else

    Action2

fi

 

[참고] 172.16.8.254:/root/shell/check_file.sh

# mkdir /root

# rcp -r 172.16.8.254:/root/shell /root

 

 

sort CMD

______________________

 

sort, merge, or   sequence check text files

 

     The sort command sorts lines of all the named files together

     and writes the result on the standard output.

 

     Comparisons are based on one or  more  sort  keys  extracted

     from  each line of input. By default, there is one sort key,

     the entire input line. Lines are ordered  according  to  the

     collating sequence of the current locale.

 

(명령어 형식)                 // separate default : 스페이스 ,

# sort /etc/passwd

# sort -r /etc/passwd           (-r : reverse , 거꾸로 내림차순)

# sort -t : -k 3 -n /etc/passwd (-t : seperate, -k : key, -n : number)

# sort -k 3 filename            // -f #     : 필드 구분, # 은 구분자

# sort -k 3,5 filename          // -k 필드 3,5 sort

 

 

[참고] 많이 실행되는 sort 명령어 실행 방법

# CMD |  sort

# CMD |  sort -r

# CMD |  sort -k  3

 

 

[EX] sort 명령어 실습

# rcp 172.16.8.254:/root/conf_sample/DB.txt  /test

# cat DB.txt

Chan1   10      20      30      50

Chan2   20      25      31      20

Chan3   30      20      30      40

Chan4   50      20      30      80

# sort DB.txt

# sort -r DB.txt

# sort -k 3 -n DB.txt

# sort -k 3,5 -n DB.txt

 

 

[EX] sort 명령어 활용 예

 

(윈도우 컴퓨터의 예)

c:\   9.9G/10G

 

# cd /var

# df h       // -h : human

# du -sk /var

# du -sk * | sort

# du -sk * | sort -n

# du -sk * | sort -nr | more

 

- s : sum

- k : kbytes

 

 

file CMD

____________________

 

determine file type

 

     The file utility performs a series of  tests  on  each  file

     supplied  by  file  and,  optionally, on each file listed in

     ffile in an attempt to classify it. If the  file  is  not  a

     regular  file,  its file type is identified.  The file types

     directory, FIFO, block special, and  character  special  are

     identified  as  such.  If the file is a regular file and the

     file is zero-length, it is identified as an empty file.

 

(명령어 형식)

# file /etc/passwd

 

[EX] 파일의 종류 확인

# file /etc/passwd        

/etc/passwd:    ascii text (ASCII 파일)

 

# file /usr/bin/ls        

/usr/bin/ls:    ELF 32-bit MSB executable SPARC Version 1, dynamically linked, stripped (Binary 파일)

 

# file /var/adm/utmpx     

/var/adm/utmpx: data (Data 파일)

 

# file /etc/hosts /etc    

/etc/hosts:     ascii text

/etc:           directory (Directory 파일)

 

 

[참고] 특정 디렉토리 하위의 많은 파일들의 형식

# cd /var

# file *

 

 

Windows -> 파일.확장자(0)

Unix    -> 파일.확장자(X)

 

 

[EX] file 명령어의 활용예

Internet File :   file.tar.gz  ->  file.tar (Modification)

 

# mv file.tar.gz file.tar

# ls -l  file.tar

# tar xvf file.tar

# file file.tar

 

# mv file.tar file.tar.gz

# gzip -d file.tar.gz

# tar xvf file.tar

 


출처 : http://cafe.daum.net/bscsolaris
2008. 7. 21. 01:22

Chapter 5. Unix Basic Commands _ 파일 속성 정보 변경 명령어

■ 파일의 속성 정보 변경(File Attribution Chaging)

chown CMD

chgrp CMD

chmod CMD



# ls -l filename

-rw-r--r-- 1 user01 staff size mtime filename

Filetype :

Mode/Perm : chmod

Link Count : ln

Ownership : chown

Groupship : chgrp

Filesize :

mtime : touch

filename : mv



chown CMD

__________________

change file ownership // 소유권 변경

The chown utility will set the user ID of the file named by

each file to the user ID specified by owner, and, option-

ally, will set the group ID to that specified by group.

If chown is invoked by other than the super-user, the set-

user-ID bit is cleared.

Only the owner of a file (or the super-user) may change the

owner of that file.


# ls -l filename

-rw-r--r-- 1 user01 staff ..... filename


(
명령어 형식)

# chown user02 filename (# chown UID filename)

# chown user02:other filename (# chown user02.other filename: X)

# chown -R user02 dir01

// -R recursive : 하위로~부터


[EX] chown
명령어 실습


(
실습 준비)

# cd /test

# rm -r *

# touch file1

# ls -l file1

-rw-r--r-- 1 root other ..... file1

(chown user01 filename 형식 실습)

# chown user01 file1

# ls -l

(chown user01:staff filename 형식 실습)

# chown user02:staff file1

# ls -l


[EX] chown -R
명령어 실습


(
실습 준비)

# cd /test

# mkdir dir1

# mkdir -p dir1/dir2/dir3

# touch dir1/file1

# touch dir1/file2

(chown -R user01:other dir 형식 실습)

# chown -R user01:other dir1

# ls -lR


chgrp CMD

__________________

change file group ownership // 파일의 소유 그룹권을 변경

The chgrp utility will set the group ID of the file named by

each file operand to the group ID specified by the group

operand.


# ls -l filename

-rw-r--r-- 1 user01 staff ..... filename


(
명령어 형식)

# chgrp other filename (# chgrp GID filename)


[EX] chgrp
명령어 실습

# cd /test

# ls -l file1

-rw-r--r-- 1 user02 staff ..... file1

# chgrp other file1

# ls -l


chmod CMD

__________________

change the permissions mode of a file // 파일의 권한을 변경

The chmod utility changes or assigns the mode of a file. The

mode of a file specifies its permissions and other attri-

butes. The mode may be absolute or symbolic.


# ls -l filename

-rw-r--r-- 1 user01 staff ..... filename

- : file type (-, d, l)

rw- : owner perm.

r-- : group perm.

r-- : other perm.

1 : link count(hard link)

user01 : ownership

staff : groupship

size : bytes

mtime : modify time



[
참고] rw-r--r-- : 퍼미션 모드(Permission Mode)


퍼미션 변경 방법

■ 심볼릭 모드 방법(Symbolic Mode)

■ 옥탈 모드 방법(Octal Mode, Absolute Mode)


(1)
심볼 모드 방법(Symbolic Mode)

심볼들의 정의

-> u(user), g(group), o(other), a(all)

-> +(plus), -(minors), =(equal)

-> r(read), w(write), x(eXcution)

chmod u + r filename

g - w

o = x // other 권한을 기존의 값과 상관없이 x만으로 셋팅이 된다.

a


[EX]
심볼 모드를 사용한 퍼미션 변경 실습

# touch file1

# ls -l file1

-rw-r--r-- 1 root other 0 mtime file1

# chmod u+x file1

# chmod g-r file1

# chmod a=rwx file1

# chmod u-r,g+x file1


(2)
옥탈 모드 방법(Octal Mode)

rwx : 7

rw- : 6

r-x : 5

r-- : 4

-wx : 3

-w- : 2

--x : 1

--- : 0

chmod 755 filename (rwxr-xr-x)


[EX]
옥탈모드(Octal Mode)를 사용한 퍼미션 변경 방법 실습

# touch file1

# ls -l file1

-rw-r--r-- 1 root other 0 mtime file1

# chmod 744 file1

# chmod 754 file1


[
참고] chmod -R (Recusive)

chmod 명령어에 -R 옵션을 사용하는 경우는 잘 사용되지 않는 경우이며 반드시 사용해야 하

는 경우 ls 명령어의 -lR 옵션을 통해서 백업을 받아 두어야 한다.


(
특정 디렉토리 하위의 모든 퍼미션 변경의 경우)

# ls -lR > perm.txt

# chmod -R 755 dir01


(
특정 디렉토리 하위의 특정 파일 퍼미션 변경의 경우)

/test/dir01

- file1

- file2

- dir02 - file3

- dir03

file* => 640(rw-r-----)

# cd /test

# find /test/dir01 -type f -exec chmod 640 {} \;

# find /test/dir01 -type f name “*.log” -exec chmod 640 {} \;


[
참고] File & Directory permission 의미

___________________________________________________________________________________

file r read 파일의 read권한은 파일안을 볼 수 있거나 복사할 수 있음

w write write 권한은 파일안의 내용을 추가 하거나 삭제, 변경 가능

x execution execution 권한은 파일을 실행할 수 있다는 의미

Dir. r ls read 권한은 디렉토리 하위 내용을 ls 할 수 있음

w add, delete write 권한은 디렉토리 하위의 내용을 삭제, 추가, 변경 가능

x cd execution 권한은 디렉토리 하위로 cd 할 수 있음

___________________________________________________________________________________


[EX]
파일 퍼미션 실습

반드시 user01, user02 사용자가 존재해야 한다.


[TERM1] user01
사용자 윈도우

# telnet localhost

user01 사용자로 로그인

$ touch file1

$ ls -l

-rw-r--r-- 1 user01 staff 0 mtime file1


[TERM2] user02
사용자 윈도우

# telnet lcoalhost

user02 사용자로 로그인

$ cd ~user01

$ vi file1

Test for user02

:wq! (파일의 내용을 넣을 수 없다.)

-rw-r--r-- 1 user01 staff 0 mtime file1

                           A       A

                           |        |

         V        |

                          user02 V

                                   user02's group


[EX]
디렉토리 퍼미션 실습


[TERM1] user01
사용자 윈도우

$ mkdir dir1

$ ls -ld dir1 (rwxr-xr-x user01 staff)

$ chmod 775 dir1

$ ls -ld dir1 (rwxrwxr-x user01 staff)

$ touch dir1/file2


[TERM2] user02
사용자 윈도우

$ cd ~user01

$ cd dir1

$ rm file2 (파일을 지울수 있다.)

$ mkdir dir2 (디렉토리를 지울수 있다.)



umask CMD

__________________

get or set the file mode creation mask

# touch file1

# mkdir dir1

# ls -l file1 (644,rw-r--r--)

# ls -ld dir1 (755,rwxr-xr-x)


* 002, 022, 027

* default permission

file : 666 (Max Perm)

dir : 777 (Max Perm)

# umask

# umask 002

# umask

# touch file2

# ls -l file2 (664, rw-rw-r--)

# mkdir dir2

# ls -ld dir2 (775, rwxrwxr-x)

# umask 027

# umask

# touch file3

# mkdir dir3

# ls -l

---------------------------

File Dir.

---------------------------

666 777

umask 022 022

---------------------------

644 755

---------------------------

비트의 and 연산 è - 연산과 같음

비트의 or 연산 è 특정비트 mask 할시


[
참고] /etc/profile umask 정의

umask 022



(3).
특수 퍼미션(SetUID, SetGID, Sticky Bits)

SetUID, SetGID 의미(SetUID, SetGID Means)

Sticky Bits 의미(Sticky Bits Means)

■ 특수 퍼미션 설정(Special Permission configuration)



(3-1) SetUID, SetGID
의미(SetUID, SetGID Means)

일반 사용자가 자신의 패스워드를 변경하기 위해 passwd 명령어를 사용할 수 있다. 하지만 passwd 명령어의 원 권한자는 root인데 파일을 실행 하는 동안 setuid를 가짐으로서 root의 역할을 가질 수 있는 것이다.

$ passwd

$ ls -l /etc/passwd (r--r--r-- root sys, 444)

r--r--r--

$ ls -l /etc/shadow (r-------- root sys, 400)

r--------

$ ls -l /usr/bin/passwd

r-sr-sr-x root sys


[user01]

$ passwd

===================

[root] /etc/passwd (root, sys)

/etc/shadow

===================

$ id


[user01]

$ ls -l /usr/bin/su

r-sr-xr-x root sys


[user01]

$ su -

====================

....

ksh(fork) (root)

....

====================

$ id

[user01]

ksh (user01)

-------------------+                                            +-----------------

                                      |                                             |

                                      |               ksh(root)               |

                                      +----------------------+


[
참고] 해킹 기법(Hacking Tech.)

// 임시파일 추적할 때 pfiles 를 이용 프로세스가 생성 시킨 file을 추적할 수 있다.


- Stack Buffer Overflow

- Heap Buffer Overflow

- Race Condition

- IP Spoofing

- etc


[Race Condition]

- SetUID filename

- tmp file make

- Hacker known a tmp filename

$ ./su.sh (user01, SetUID root)

---- su.sh ---------                                       ------ crack.sh ------

         (root)

                                                /tmp/.tmp1

                                                                            ----------------------

                                                                            ------ test.sh -------


---------------------                                  ----------------------


[Backdoor]

# cp /usr/bin/ksh /tmp

# chmod 4755 /tmp/ksh

(-rwxr-xr-x 1 root other 209268 3 15 10:37 /tmp/ksh*)

(-rwsr-xr-x 1 root other 209268 3 15 10:37 /tmp/ksh*)

# telnet localhost

user01 사용자로 로그인

$ cd /tmp

$ ./ksh

# id -a

- File Name for Backdoor

# touch " " (blank :4)

# touch ". "

# touch /dev/rdsk/c0t0d0p7

# touch /tmp/.Rx2Pailb




(3-2). Sticky Bits
의미(Sticky Bits Means)

Sticky bit는 일반적으로 디렉토리에 주어지는 의미이다. 디렉토리에 sticky bits가 주어지면 그 디렉토리 하위의 모든 파일과 디렉토리들은 다른 사용자가 볼 수 있지만 지우거나 수정을 할 수 없다.

예로 게시판을 들 수 있다.

# ls -ld /tmp

drwxrwxrwt 7 root sys 336 1 14 19:35 /tmp

/export/home/user01 <=======> /tmp

user02

......



(3-3).
특수 퍼미션 설정(Sfecial Permission Configuration)

SetUID : 4 r

SetGID : 2 w

Sticky Bits : 1 x


(a). SetUID
설정 방법

# chmod 4755 filename

rwxr-xr-x => rwsr-xr-x

# chmod 4100 filename(Min Permission) --x------ -> --s------

# chmod 4655 filename(-rwSr-xr-x) rw-r-xr-x -> rwSr-xr-x


(b). SetGID
설정 방법

# chmod 2755 filename

rwxr-xr-x => rwxr-sr-x

# chmod 2010 filename(Min Permission) -----x--- -> -----s---

# chmod 2765 filename(-rwxrwlr-x) rwxrw-r-x -> rwxrwlr-x



[
참고] Solaris(Public Writable Directory)

디렉토리에 관련해서 SetGID를 설정하는 것은 Symbolic Mode 방식으로만 가능하다.

# chmod g+s dirname (# chmod u+s filename)

                                                      g+s

                                                      o+t

======= dirname ========== (rwxrwsr-x) root class1

user01 make -> file1 (user01:class1)

user02 make -> file2 (user02:class1)

==========================


======== dirname ========== (root class2) rwxrwxr-x

user01 make -> file1 (user01:staff1)

user02 make -> file2 (user02:staff2)

===========================


# groupadd class2

# usermod -G class2 user01

# usermod -G class2 user02



(d). Sticky Bits
설정 방법

# chmod 1777 dirname

rwxrwxrwx -> rwxrwxrwt

# chmod 1001 dirname(Min Permission) --------x -> --------t

# chmod 1776 dirname(drwxrwxrwT) rwxrwxrw- -> rwxrwxrwT


(e). SetUID / SetGID
파일 검색(SetUID/SetGID Search)

# find / -perm -4000 -type f

# find / -perm -2000 -type f // -2000 : 최소 2000을 만족하는~

# find / ( -perm -4000 -o -perm -2000 ) -type f (올바른 형식 X)

# find / \( -perm -4000 -o -perm -2000 \) -type f (올바른 형식 0)



[
참고] -o : OR, -a : AND


[EX] SetUID / SetGID
관리자의 정책

- 홈디렉토리(/export/home) 하위에는 SetUID, SetGID는 존재하면 안된다.

- 홈디렉토리(/export/home) 하위에 SetUID, SetGID 파일 존재 유무를 정기적으로 찾아서

점검한다.

사용자 홈디렉토리 : /export/home/user01......


(
정책1) SetUID, SetGID 검색하는 경우

# find /export/home \( -perm -4000 -o -perm -2000 \) -type f


(
정책2) SetUID, SetGID 검색하고 삭제하는 경우

# find /export/home -perm -4000 -exec rm {} \;


(
정책3) SetUID, SetGID 생성시키는 사용자 경고 메세지 출력

- 사용자(user01)가 현재 로그인 되어 있는 상태 (who, w, talk 명령)

- 사용자(user01)가 현재 로그인 되어 있지 않은 상태 (/etc/profile)

# cat /etc/warnning.txt

Warnning

# vi /etc/profile

.....

if [ $LOGNAME = user01 ] ; then # # echo $LOGNAME

/bin/cat -s /etc/warnning.txt

fi

.....


[EX] WAS(Web Application Server)

- 상용 : Tmaxsoft JEUS, BEA Web Logic, IBM WebSphere, Oracle WAS, Sun WAS, .....

- 무료 : Jserv, Tomcat, Resin


Webserver (80, 8080) -> root
권한 필요

-> UNIX Port 번호 : Well-known Port(~1024)


Web Daemon(Example : httpd)

PORT 1 ~ 1023 : 반드시 root 권한 필요

PORT 1024 ~ : 일반사용자 권한으로도 가능

httpd (80) : 반드시 root 권한 필요

httpd (8080) : 일반사용자 권한으로도 가능


위의 경우 문제가 생길수 있다. 실제 실무에서는 서버 시스템에 root 사용자와 WAS 서비스

사용자가 구분되어 있는 경우가 많다. 일반사용자인 wasuser로서 WAS 프로그램을 설치하고

운용하기 때문에 데몬을 시작하는 스크립트가 wasuser 사용자의 권한으로 되어 있어서 이

사용자가 웹 데몬을 띄우게 되면 "Permission Denied"가 발생한다.


WAS -> wasuser
사용자

-------------------------

OS -> root 사용자


데몬 : httpd

데몬 띄우는 스크립트 : startup (: # service httpd restart)


* wasuser
httpd(80) 데몬을 띄울수 있도록 설정하는 관리자의 설정이 필요

# chown root:sys /was/bin/startup (root sys rwxr-xr-x -> rws-----x)

# chmod 4701 /was/bin/startup (root sys rwx-----x -> rws-----x)

or

# vi startup.c

main()

{

system(/was/bin/startup);

}

# gcc -o startup_C startup.c

# chmod 4701 startup_C

출처 : http://cafe.daum.net/bscsolaris

2008. 7. 21. 00:20

Chapter 5. Unix Basic Commands _ 사용자와 통신할때 사용하는 명령어

사용자와 통신(Communication) 할수 있는 명령어

mailx CMD

write CMD

talk CMD


mailx CMD

__________________

interactive message processing system

The mail utilities listed above provide a comfortable, flex-

ible environment for sending and receiving mail messages

electronically.


(
명령어 형식)

# mailx

# mailx -H -u user01

# mailx -s "Test Mail" root@example.com < mailx.txt


[EX]
메일 보내기 / 받기 실습

# mailx user01

Subject : Test Mail <----- "Test Mail" 입력

Hello Test <----- 메일 내용 입력

<Ctrl + D> or <.>

# su - user01

$ mailx

.....

>N 2 Super-User Mon Jan 14 19:32 17/722 Mail for TEST

? 2 <----- '2' 입력

Message 2:

From root@solaris254.example.com Mon Jan 14 19:32:53 2008

Date: Mon, 14 Jan 2008 19:32:53 +0900 (KST)

From: Super-User <root@solaris254.example.com>

To: user01@solaris254.example.com

Subject: Mail for TEST

Hello, user01

? q <----- 'q' 입력

#

# man mailx

.....

-H Print header summary only.

-u user

Read user's mailbox. This is only effective if user's

mailbox is not read protected.

-s subject

Set the Subject header field to subject. subject

should be enclosed in quotes if it contains embedded

white space.

.....


[
주의] mailx 명령어를 통해서 메일을 보내기 위해서는 다음과 같이 호스트의

이름의 설정이 메일 주소를 쓰는 형식과 같이 선언 되어 있어야 한다. 선언이

되어 있지 않다면 "solaris254.example.com" 같은 부분을 선언해 줘야 한다.

# vi /etc/hosts

......


[
수정 전]

172.16.8.254 solaris254 loghost


[
수정 후]

172.16.8.254 solaris254 solaris254.example.com loghost

                                                         ...... A

                                                                |

                                                                +---- 새로 입력



write CMD

__________________


write to another user

The write utility reads lines from the user's standard input

and writes them to the terminal of another user.

user01 -----> user02

user01 <----- user02


(
명령어 형식)

# write user01



talk CMD

__________________

talk to another user

The talk utility is a two-way, screen-oriented communication

program.

user01 <-----> user02 (메신저 기능)

# talk user01@localhost


[
참고] user01 <==> user02 talk

user01 Window) # talk user02@localhost

user02 Window) # talk user01@localhost


[EX] root
사용자가 user01 사용자에게 talk 신청


[TERM1] user01
사용자 윈도우

# telnet localhost

user01 사용자로 로그인


[TERM2] root
사용자 윈도우

# who -----> user01 사용자 로그인 확인

# w -----> user01 사용자 활동량 점검

# talk user01@localhost


[TERM1] user01
사용자 윈도우

# talk root@localhost


출처 : http://cafe.daum.net/bscsolaris

2008. 7. 21. 00:03

Chapter 5. Unix Basic Commands _ 기타 관리용 명령어

기타 관리용 명령어

■ wc CMD

■ su CMD

■ id CMD

■ groups CMD

■ last CMD

■ who CMD

■ w CMD

■ rusers CMD

wc CMD

_________________

display a count of lines, words and characters in a file

The wc utility reads one or more input files and, by

default, writes the number of newline characters, words and

bytes contained in each input file to the standard output.

# wc /etc/passwd

# wc -l /etc/passwd // line count

# wc -w /etc/passwd // word count

# wc -c /etc/passwd // character count


[
참조] wc -l 명령어 응용예

# cat /etc/passwd | wc -l

# pkginfo | wc -l

# patchadd -p | wc -l

# ps -ef | wc -l


(
시스템 성능/사용량 카운트 수집)


(
첫번째 ) Apache Webserver

- apache 1.3.X (Process 방식)

- apache 2.X (Thread 방식)

Web Client -----------------> Web Server

http://Server httpd

# ps -ef | grep httpd | wc -l > httpd.count

// process counting


(
두번째 )

# df -k

# df -k / | tail -1 | awk '{print $5}' > df.count


(
세번째 )

# ftpcount | grep realuser | awk '{print $5}' > ftp.count


su CMD

__________________

become super user or another user

The su command allows one to become another user without

logging off or to assume a role. The default user name is

root (superuser).


(
명령어 형식)

su [user]

su - [user]


■ End User => root (O) EX) user01 => root

■ End User => End User (O) EX) user01 => user02

■ root => End User (O) EX) root => user01

■ root => root (X)

Becoming User bin While Retaining Your Previously

Exported Environment

To become user bin while retaining your previously exported

environment, execute:

example% su bin

Example 2: Becoming User bin and Changing to bin's Login

Environment

To become user bin but change the environment to what would

be expected if bin had originally logged in, execute:

example% su - bin

su 명령어에 "-"(Dash) 기호가 없는 경우에는 사용자의 EUID/EGID 값을 받게 되지만 사용자의 환경 변수들은 이전 사용자의 환경변수값을 받는다. 사용자만 전환하게 되는 것이다. su 명령어에 "-" 기호가 있는 경우에는 사용자의 EUID/EGID 값을 받게 되는 것 뿐만 아니라원본 사용자가 새로 로그인 한것 처럼 해준다. 사용자가 로그인을 하게 되면 홈디렉토리로 로그인 하게 되고 사용자의 환경 파일들을 읽어 들이기 때문에 사용자의 환경으로 적용되게 된다.

[EX] "su bin / su - bin" 명령어 실습

# cd /etc

# pwd

# su user01

(a). shell prompt (# echo $PS1)

(b). current directory (# pwd)

(c). echo $PATH

# id

# exit

# cd /etc

# pwd

# su - user01

(a). shellp prompt (# echo $PS1)

(b). current directory (# pwd)

(c). echo $PATH

$ id

$ exit


[
참고] 오라클 사용자로 전환(When Oracle User Switching)

(시나리오) root 사용자로 작업을 하다가 oracle 사용자로 전환 해야 하는 경우 다음과

명령어를 사용하지 않는다면 문제가 발생할 있다. 이것은 oracle 사용자의 홈디렉토

리에 존재하는 환경파일(: ~/.profile) 변수 설정이 되지 않는다면 oracle 사용자가

정상적으로 작업을 할수 없기 때문이다.


[EX]
스크립트에서 많이 사용되는 su 명령어의

To execute command with the temporary environment and permissions of user bin

# su - bin -c "command args"



id CMD

__________________

return user identity

If no user operand is provided, the id utility writes the

user and group IDs and the corresponding user and group

names of the invoking process to standard output. If the

effective and real IDs do not match, both are written. If

multiple groups are supported by the underlying system,

/usr/xpg4/bin/id also writes the supplementary group affili-

ations of the invoking process.

(명령어 형식)

# id

# id -a

# id user01


[
참고] root 사용자의 UID, GID

UID=0(root), GID=1(other)


[
참고] UID, GID, EUID, EGID

- UID/GID - who am i // login 당시 !!!

- EUID/EGID - id, whoami // 현재 내가 누구인지

- UID (User Identification)

- EUID(Effective UID)

- GID (Group Identification)

- EGID(Effective GID)


[EX] UID, GID, EUID, EGID
개념의 이해

# telnet localhost

user01 사용자로 로그인

$ id

uid=100(user01) gid=100(class1)

$ /usr/ucb/whoami

user01

$ who am i

user01 pts/9 Feb 2 01:48 (localhost)

$ su - root

Password: <----- root 사용자 암호 입력

# id

uid=0(root) gid=1(other)

# /usr/ucb/whoami

root

# who am i

user01 pts/9 Feb 2 01:48 (localhost)

===== HOSTA ===== ===== HOSTB ======

# telnet HOSTB ------------> user01 사용자로 로그인

$ id

$ whoami

$ who am i

$ su - root

# id

# whoami

# who am i

----------------------------

UID EUID

----------------------------

500 500 --> user01 사용자로 로그인 했을때

500 0 --> "su - root" 명령어 수행

----------------------------



groups CMD

__________________

print group membership of user

The command groups prints on standard output the groups to

which you or the optionally specified user belong. Each user

belongs to a group specified in /etc/passwd and possibly to

other groups as specified in /etc/group. Note that

/etc/passwd specifies the numerical ID (gid) of the group.

The groups command converts gid to the group name in the

output.

(명령어 형식)

# groups

# groups user01

# groups user01 user02


[
참조] /etc/group 그룹 정의


[EX] groups
명령어 실습

# groups

other root bin sys adm uucp mail tty lp nuucp daemon

# groups user01

staff

# groups user01 root

user01 : staff

root : other root bin sys adm uucp mail tty lp nuucp daemon



last CMD

-------------

display login and logout information about users and terminals

The last command looks in the /var/adm/wtmpx file, which

records all logins and logouts, for information about a

user, a terminal, or any group of users and terminals. Argu-

ments specify names of users or terminals of interest. If

multiple arguments are given, the information applicable to

any of the arguments is printed. For example, last root con-

sole lists all of root's sessions, as well as all sessions

on the console terminal. last displays the sessions of the

specified users and terminals, most recent first, indicating

the times at which the session began, the duration of the

session, and the terminal on which the session took place.

last also indicates whether the session is continuing or was

cut short by a reboot.

The pseudo-user reboot logs in when the system reboots.

Thus, # last reboot

(명령어 형식)

# last

# last user01

# last reboot

+----------+

| |

| User |

| |

+----------+

| |

| reboot |

| |

+----------+


(
명령어 출력 화면 해석)

# last user01

.....

user01 pts/11 localhost Sat Jan 12 14:51 - 15:29 (00:38)

----------------------------------------------------

필드 설명

----------------------------------------------------

user01 사용자의 이름

pts/11 제어 터미널(가상 터미널)

localhost 원격 호스트

Sat Jan 12 14:51 로그인 시간

15:29 로그아웃 시간

(00:38) 사용한 시간

----------------------------------------------------


# last reboot

......

reboot system boot Thu Jan 10 15:39

----------------------------------------------------

필드 설명

----------------------------------------------------

reboot 가상사용자

system boot 상태정보

Thu Jan 10 15:39 리부팅 시간

----------------------------------------------------



[
참고] wtmpx, utmpx 파일

/var/adm/utmpx - who 명령어 참조

/var/adm/wtmpx - last 명령어 참조

at linux

/var/adm/utmp – who

/var/adm/wtmp - last



[EX] /var/adm/utmpx & /var/adm/wtmpx

# cd /var/adm

# mv wtmpx wtmpx.old

# last

# who

# mv wmtpx.old wtmpx



exit CMD

--------------

End the application

Terminate the process, returning returnCode to the system as

the exit status. If returnCode isn't specified then it

defaults to 0.

(명령어 형식)

# exit [Number]

[참고] exit Number

0 : 정상 종료(Normal Termination)

1 ~ 255 : 비정상 종료(Abnormal Termination)


[EX1]
현재 터미널 종료

# exit


[EX2]
로그 아웃

# telnet 172.16.8.254

root 사용자로 로그인

# hostname

# exit


[EX3]
서브 종료

# bash

# ps

# exit



who CMD

__________________

who is on the system // 현재 로그인된 사용자 정보 확인

The who utility can list the user's name, terminal line,

login time, elapsed time since activity occurred on the

line, and the process-ID of the command interpreter (shell)

for each current UNIX system user. It examines the

/var/adm/utmpx file to obtain its information. If file is

given, that file (which must be in utmpx(4) format) is exam-

ined. Usually, file will be /var/adm/wtmpx, which contains a

history of all the logins since the file was last created.


(
명령어 형식)

# who

# who -r (현재 Runlevel 확인)

# whoami (현재 사용자 정보 확인)

# who am i (로그인한 사용자 정보 확인)

# who -H (Headline, 헤드라인 정보 표시)


(
명령어 출력 화면 해석)

# who

root pts/4 1 14 09:57 (192.168.222.1:0.0)

----------------------------------------------------

필드 설명

----------------------------------------------------

root 사용자 정보

pts/4 제어 터미널

1 14 09:57 로그인 시간

192.168.222.1 원격호스트

----------------------------------------------------


[
참고] /var/adm/utmpx

# mv /var/adm/utmpx /var/adm/utmpx.old

# who

# mv /var/adm/utmpx.old /var/adm/utmpx


[EX] 172.16.8.254 login Test

# telnet 172.16.8.254

user01 사용자로 로그인

$

(At solaris254)

# who


whodo / w CMD

__________________

who is doing what // 현재 로그인한 사용자가 수행중인 명령어 확인

The whodo command produces formatted and dated output from

information in the /var/adm/utmpx and /proc/pid files.

The display is headed by the date, time, and machine name.

For each user logged in, device name, user-ID and login time

is shown, followed by a list of active processes associated

with the user-ID. The list includes the device name,

process-ID, CPU minutes and seconds used, and process name.


(
명령어 형식)

# whodo

# whodo user01

# whodo -l (w CMD 명령어 출력 형태로 출력)

# man whodo

.....

-l Produce a long form of output. The fields displayed

are: the user's login name, the name of the tty the

user is on, the time of day the user logged in (in

hours:minutes), the idle time - that is, the time

since the user last typed anything (in hours:minutes),

the CPU time used by all processes and their children

on that terminal (in minutes:seconds), the CPU time

used by the currently active processes (in

minutes:seconds), and the name and arguments of the

current process.

.....


(
명령어 출력 화면 해석)

# w

.....

user01 pts/8 7:16오후 -ksh

----------------------------------------------------

필드 설명

----------------------------------------------------

user01 사용자이름

pts/8 제어터미널

7:16오후 명령어 수행시간

-ksh 수행 명령어

----------------------------------------------------


[EX]
악의적인 사용자 로그아웃 시킴


[TERM1]
사용자 윈도우

# telnet localhost

user01 사용자로 로그인

$ vi /etc/passwd


[TERM2]
관리자 윈도우

# w

# w user01 (# w | grep user01)


[
참고] 사용자 활동 모니터링

# while [ 1 ]

> do

> w user01

> sleep 2

> done


[TERM3]
관리자 윈도우

# ps -U user01

ksh's PID(450)

# kill -9 450



rusers CMD

__________________

who is logged in on remote machines

The rusers command produces output similar to who(1), but

for remote machines. The listing is in the order that

responses are received, but this order can be changed by

specifying one of the options listed below.

A remote host will only respond if it is running the rusersd

daemon, which may be started up from inetd(1M) or

listen(1M).


(
명령어 형식)

# rusers -a

# rusers -h

# rusers -l

# rusers 172.16.8.202

# man rusers

.....

-a Give a report for a machine even if no users are

logged on.

-h Sort alphabetically by host name.

-l Give a longer listing in the style of who(1).

.....



출처 : http://cafe.daum.net/bscsolaris