캠핑과 개발


## // MySQL의 default configuration 파일의 위치는 한 곳에 지정되거나
## // 어딘가에 명확히 명시되어서 실행되지 않는 것이 일반적이다.
## // 이런 경우, 현재 mysql server가 어느 위치에 있는 my.cnf 파일을 읽었는지 궁금한 경우가 많다.
## // 또한 my.cnf 파일은 RPM으로 MySQL library만 설치해도 /etc/my.cnf 파일이 생성되므로
## // mysql server가 DBA가 준비해둔 설정 파일을 읽었는지, 아니면 위처럼 의도하지 않게 
## // 생성된 my.cnf 파일을 읽고 있는지 의심이 되는 경우가 매우 허다한데, 
## // 이런 경우에는 아래와 같이 mysql server 프로세스가 기본적으로 찾게 되는 my.cnf 파일의
## // 경로를 우선순위대로 확인해볼 수 있다.

${MYSQL_HOME}/bin/mysqld --verbose --help | grep -A 1 'Default options'

Default options are read from the following fi
les in the given

'DEVELOPMENT > Database' 카테고리의 다른 글

index 생성  (0) 2012.05.17
Oracle Hint  (0) 2012.05.17
mysql 소스 설치  (0) 2011.11.29
ORACLE 명령문  (0) 2011.08.02
MERGE INTO 사용법  (0) 2011.07.09


http://dev.mysql.com 에서 다운로드 후 설치

mysql 5.1 바이너리 설치

[바이너리 버전 설치 순서]
shell> groupadd mysql
shell> useradd -g mysql mysql
shell> cd /usr/local
shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf -
shell> ln -s full-path-to-mysql-VERSION-OS mysql
shell> cd mysql
shell> chown -R mysql .
shell> chgrp -R mysql .
shell> scripts/mysql_install_db --user=mysql
shell> chown -R root .
shell> chown -R mysql data
shell> bin/mysqld_safe --user=mysql &

이제 기본 데이터베이스 설치를 위해 아래의 코드 실행. script 디렉토리 안에서 mysql_install_db를 실행하니 아래와 같이 FATAL ERROR가 발생했다. 
그러므로 아래 빨간 색으로 표시된 것처럼 mysql의 탑 디렉토리에서 실행해야 성공한다.

[root@localhost bin]# cd ../scripts
[root@localhost scripts]# ls
mysql_install_db
[root@localhost scripts]# ./mysql_install_db 

FATAL ERROR: Could not find ./bin/my_print_defaults

If you compiled from source, you need to run 'make install' to
copy the software into the correct location ready for operation.

If you are using a binary release, you must either be at the top
level of the extracted archive, or pass the --basedir option
pointing to that location.

[root@localhost scripts]# pwd
/usr/local/mysql/scripts
[root@localhost scripts]# cd ..
[root@localhost mysql]# ./scripts/mysql_install_db 
Installing MySQL system tables...
090720 14:01:07 [Warning] Forcing shutdown of 2 plugins
OK
Filling help tables...
090720 14:01:07 [Warning] Forcing shutdown of 2 plugins
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:

./bin/mysqladmin -u root password 'new-password'
./bin/mysqladmin -u root -h localhost.localdomain password 'new-password'

Alternatively you can run:
./bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:
cd . ; ./bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd ./mysql-test ; perl mysql-test-run.pl

Please report any problems with the ./bin/mysqlbug script!

The latest information about MySQL is available at http://www.mysql.com/
Support MySQL by buying support/licenses from http://shop.mysql.com/

이제 기본 DB(mysql, test)의 설치가 끝났다. mysql 디렉토리를 보면 data라는 새 디렉토리가 생성되었을 것이다.

mysql 실행
mysql 게정으로 로긴 후
mysql]$ /usr/local/mysql/bin/mysqld_safe &

mysql 종료
mysqladmin -u root -p shutdown

root로 접속하기 (여기서 root는 시스템의 root계정이 아니라, mysql의 관리계정이다)
처음 설치시 root의 패스워드는 없다.

사용형식) mysql -u MySQL계정명 -p 접속할데이터베이스명
mysql]$ mysql -u root -p mysql

database내 테이블 조회
mysql> show tables;

테이블 스키마 조회
mysql> desc <테이블명>;


자동 시작 등록

#!/bin/sh
vi /etc/rc.d/rc.local

/usr/local/mysql/bin/mysqld_safe &

 

- 데몬이 무사히 실행됐다면 서버 시작시에 자동실행되도록 한다.
  # cp /usr/local/mysql/support-files/mysql.server /etc/rc.d/init.d
  # ln -s ../init.d/mysql.server /etc/rc.d/rc0.d/K01mysql
  # ln -s ../init.d/mysql.server /etc/rc.d/rc3.d/S90mysql

 
/var/run/mysqld/mysqld.pid를 생성하지 못할경우
cd /var/run
mkdir mysqld
chown mysql mysqld
chgrp mysql mysqld 



 

'DEVELOPMENT > Linux' 카테고리의 다른 글

linux shell 스크립트  (0) 2012.01.13
Fedora 16 | systemctl - 서비스 관리 명령어  (0) 2011.12.01
ssh 접속 설정.  (0) 2011.11.29
linux 방화벽 열기  (0) 2011.11.29
sftp root 계정 접속 설정  (0) 2011.07.27


일단 크게

  1. ssh 관련 설정파일을 수정하고
  2. 방화벽설정을 열어준다.

정도로 접속이 가능하게 된다.
fedora12 에서 ssh 설정 관련 패키지 설정파일은 "/etc/ssh" centos는 /etc/ssh/sshd-config에 있습니다.


파일을 열어보면...

[root@localhost /]# cat /etc/ssh/sshd_config
#       $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options change a
# default value.

Port 8103
AddressFamily inet
ListenAddress 192.168.0.104
#ListenAddress ::

# Disable legacy (protocol version 1) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol 1
Protocol 2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile     .ssh/authorized_keys

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
GSSAPIAuthentication yes
#GSSAPICleanupCredentials yes
GSSAPICleanupCredentials yes

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no
UsePAM yes

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10
#PermitTunnel no
#ChrootDirectory none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem       sftp    /usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       ForceCommand cvs server
[root@localhost /]#


파일에서 vi 에디터로  주황색으로 표시된부분만 수정해준다. (위 내용은 현재 사용하고있는 테스트 서버의 내용)

Port 8103 는 Listen 포트를 변경하는 부분... 기본값은 22

포트를 변경하였을때에는 /etc/services 파일과 방화벽에서 해당포트를 열어주어야한다. (여기서는 8103)

AddressFamily inet 는 ipv4, ipv6 에 대한 옵션이라고함. inet 으로 설정하면 ipv4 에 대해서만 bind 한다고함.

ListenAddress 192.168.0.104는 Listen 할 아이피를 설정해주는 부분.
SyslogFacility AUTHPRIV   로그에대한 옵션임 로그파일이 저장되는 곳을 지정. AUTHPRIV 가 기본값. 기본값일때에는
/var/log/secure 에 로그를 기록하게됨.

LogLevel INFO 로그레벨은 Info 로 지정함으로써 왠만한 기록은 다 기록된다고 함.

PermitRootLogin no 는 ssh 접속시 루트 계정으로 접속을 허용하느냐 마느냐 임...


특정 계정만 ssh 접속을 허용하는 경우

#LoginGraceTime 2m
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
AllowUsers admin guest test1 test2




이제 ssh 데몬을 재시작한다.

[root@localhost /]# /etc/init.d/sshd restart
sshd 를 정지 중:                                           [  OK  ]
sshd (을)를 시작합니다:                                    [  OK  ]
[root@localhost /]#


방화벽이 꺼져있는 상태이고, 포트가 기본인 22로 설정 되어있을경우에는 여기까지하면 완료가된다.

참고로...

ssh 버전확인은...
[root@localhost /]# rpm -qa | grep ssh
openssh-clients-5.2p1-31.fc12.i686
openssh-server-5.2p1-31.fc12.i686
trilead-ssh2-213-6.fc12.i686
openssh-5.2p1-31.fc12.i686
libssh2-1.2-2.fc12.i686
openssh-askpass-5.2p1-31.fc12.i686
[root@localhost /]#


ssh 상태보기는...
[root@localhost /]# /etc/init.d/sshd status
openssh-daemon (pid  7931)를 실행하고 있습니다..
[root@localhost /]#




자... 이제 /etc/services 파일과 방화벽에서 해당포트를 열어주는 작업을 해주자.

ssh             8103/tcp                          # The Secure Shell (SSH) Protocol

ssh 에 관한 부분에서 포트번호를 바꾸어준다.


그리고 방화벽 파일을 변경하여 포트를 열어주자

[root@localhost /]# cat /etc/sysconfig/iptables
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 8103 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
[root@localhost /]#


이렇게 해주면...

ssh 프로그램으로 원격접속이 가능하게 된다.

참고로...

방화벽 상태 알아보기
/sbin/service iptables status

방화벽 올리고 내리기
/sbin/service iptables stop
/sbin/service iptables start


[출처] http://pippen80.cafe24.com/255



'DEVELOPMENT > Linux' 카테고리의 다른 글

Fedora 16 | systemctl - 서비스 관리 명령어  (0) 2011.12.01
linux mysql 바이너리 버전 설치  (0) 2011.11.29
linux 방화벽 열기  (0) 2011.11.29
sftp root 계정 접속 설정  (0) 2011.07.27
linux 명령어 - nohup  (0) 2011.07.21

ex ) 8080 포트 열기
[root@blogserver bin]# vi /etc/sysconfig/iptables

# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT

-A INPUT -m state --state NEW -m tcp -p tcp --dport 8103 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 21 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j ACCEPT

-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT



[root@blogserver bin]#
[root@blogserver bin]# /etc/init.d/iptables restart
iptables: 방화벽 규칙을 지웁니다: [  OK  ]
iptables: chain을 ACCEPT 규칙으로 설정 중:  filter [  OK  ]
iptables: 모듈을 언로드하는 중: [  OK  ]
iptables: 방화벽 규칙 적용 중:  [  OK  ]
[root@blogserver bin]#
[root@blogserver bin]# /etc/init.d/iptables status
테이블: filter
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0          
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0          
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:8103
5    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:3306
6    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:21
7    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:8080 
8    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination        
1    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination        

[root@blogserver bin]#



방화벽 상태 알아보기
/sbin/service iptables status

방화벽 올리고 내리기
/sbin/service iptables stop
/sbin/service iptables start


특정 아이피 막기
iptables -A INPUT -s xx.xx.xx.xx -j DROP

특정 아이피 해제
iptables -D INPUT -s xx.xx.xx.xx -j DROP

특정 IP  웹  접속 차단
iptables -A INPUT -s xx.xx.xx.xx -p tcp --dport 80 -j DROP


해당 C class 웹 접속 차단
iptables -A INPUT -s 210.221.204.0/24 -p tcp --dport 80 -j DROP



[출처] http://pippen80.cafe24.com/271


'DEVELOPMENT > Linux' 카테고리의 다른 글

linux mysql 바이너리 버전 설치  (0) 2011.11.29
ssh 접속 설정.  (0) 2011.11.29
sftp root 계정 접속 설정  (0) 2011.07.27
linux 명령어 - nohup  (0) 2011.07.21
Linux IP 변경  (0) 2011.07.21

리눅스를 사용하다 보면 shell 이나 프로그램들을 데몬처럼 계속 올려서 사용할 경우가 있다 
기본적으로 명령어 뒤에 & 를 붙혀 실행하면 백그라운드 프로세스로 실행되지만
ssh 접속을 끝거나 터미널을 종료하면 실행이 종료된다.
(bash 에 터미널이 끊겨도 종료안되게 하는 옵션도 있다고 함 shopt | grep huponexit로 확인가능 off 명 옵션이 적용안된거임)

그래서 nohup을 사용하면 shell이나 실행 파일을 데몬처럼 계속 실행하게 할수 있음


[사용법]
$ nohup run.sh &
(shell 파일 또는 실행 파일의 퍼미션이 755이어야 함)

$ ps -ef | grep [실행파일명]  으로 프로세스 확인가능
프로세스를 죽이려면 ps로 pid를 알고 
$ kill -9 [pid]  로 죽이면 됨

기본적으로 nohup을 실행하면 nohup.out의 로그파일이 남게 됨
이 파일명은 변경하여 사용가능

nohup /usr/local/java/bin/java -jar XDreamyi3shop.jar &

nohup -> 터미널에서 로그아웃을 해도 실행시킨 프로그램은 종료되지 않고 계속 돈다.
& -> 백그라운드 실행.. ps -aux를 치면.. 프로그램이 돌고 있음을 알 수 있다.


[출처] http://www.wakgu.com/category/2?page=4




'DEVELOPMENT > Linux' 카테고리의 다른 글

linux 방화벽 열기  (0) 2011.11.29
sftp root 계정 접속 설정  (0) 2011.07.27
Linux IP 변경  (0) 2011.07.21
linux 명령어 - chmod  (0) 2011.07.21
[명령어] service 방화벽 상태 및 설정  (0) 2011.05.25

chmod 751 폴더

앞에 7은 소유자권한부분
중간 자리의 5는 그룹소속자권한
마지막 자리의 1은 일반다른사용자권한 부분


* 표시되는 퍼미션
0   ---   아무런 권한이 없음
1   --x   실행(eXecution)권한만 있음
2   -w-  쓰기(Write) 권한만 있음
3   -wx  쓰기와 실행의 권한만 있음
4   r--    읽기(read)권한만 있음
5   r-x    읽기와 실행권한만 있음
6   rw-   읽기와 쓰기 권한만 있음
7   rwx   읽기, 쓰기, 실행 권한이 있음

숫자로 하지 않고..
문자열로 권한을 줄 수 있다.

u : 소유자(user)를 의미함
g : 그룹(group)를 의미함
o : 다른사용자(other)를 의미함
a : 모두(all)를 의미함 (Default)

예 : chomd o+rw a_file  <-- 이건은 다른 사용자에게 읽기와 쓰기의 권한을 준것임.
여기서 + 의 기호의 의미는 권한을 부여한다는 의미이며..
- 의 의미는 권한을 제거한다는 의미가 된다.

ex) chomd a+r testfile  <-- testfile 파일의 권한을 모든 사용자가 읽기를 가능하겠다는 의미.
ex) chomd a+rx testfile  <-- testfile 파일의 권한을 모든 사용자가 읽기와 실행이 가능하겠다는 의미.



//----------------------------------

전체 설정을 변경한다면..

옵션으로 -R 이나 --recursive

chmod -R g+rw 폴더

//----------------------------------

[출처] http://www.wakgu.com/198?category=0


# 방화벽 상태 알아보기
   service iptables status

# 방화벽 올리고 내리기
   service iptables stop
   service iptables start

# 방화벽 설정 수정하기
   vi /etc/sysconfig/iptables

# 방화벽 해제
   iptable -F 혹은
   ipchains -F

lokkit -q --disabled 라고 하면 방화벽이 해제됩니다.
iptables -F라고 직접 명령을 주어도 됩니다 F는 Flush 를 뜻합니다.
Kernel 2.2대의 linux 배포판이라면 ipchains -F 하면 됩니다.

'DEVELOPMENT > Linux' 카테고리의 다른 글

Linux IP 변경  (0) 2011.07.21
linux 명령어 - chmod  (0) 2011.07.21
[명령어] history 이전에 실행된 명령어 출력  (0) 2011.05.25
linux 명령어 - ln 심볼릭 링크  (0) 2011.05.25
linux - netstat  (0) 2011.02.14


이전에 실행된 명령어를 보여줍니다. 이런 명령어들을 이용하여 간단하기 이전 명령을 재 실행할 수 있습니다.

[사용법] history

[출력 예] 
  120  mv apache-tomcat-5.5.33.tar.gz /usr/local
  121  cd /usr/local
  122  ls
  123  cd ls
  124  ls
  125  cd ..
  126  ls
  127  cd local
  128  ls
  129  ls
  130  chmod 755 apache-tomcat-5.5.33.tar.gz
  131  ls
  132  la
  133  ls
  134  ll
  135  tar -xvzf apache-tomcat-5.5.33.tar.gz

다음과 같은 리스트 목록이 나오면 해당 명령어 앞에 나오는 숫자를 이용해 간단하게 해당 명령어를 재 실행 할 수 있습니다.

[사용법]
하나 사용시 : ![숫자]
여러개 사용시 : ![숫자];!숫자;![숫자]


'DEVELOPMENT > Linux' 카테고리의 다른 글

linux 명령어 - chmod  (0) 2011.07.21
[명령어] service 방화벽 상태 및 설정  (0) 2011.05.25
linux 명령어 - ln 심볼릭 링크  (0) 2011.05.25
linux - netstat  (0) 2011.02.14
linux에 mysql 설치하기  (0) 2010.01.05




리눅스의 바로가기로 심볼릭 링크와 하드링크가 있습니다.

하드링크
하드링크는 파일을 직접 가르키는 것입니다. 이 링크를 삭제하면 해당 파일도 삭제가 됩니다.

[사용법] ln [타켓] [링크될 이름]



심볼릭링크
하드링크와 반대로 링크가 삭제되어도 파일은 그대로 있습니다. 단순 바로가기입니다.

[사용법] ln  -s  [타겟]  [링크될 이름]


예제 : 

ln -s /webroot/home/httpd/test.com/index.php /home/vivek/index.php



'DEVELOPMENT > Linux' 카테고리의 다른 글

[명령어] service 방화벽 상태 및 설정  (0) 2011.05.25
[명령어] history 이전에 실행된 명령어 출력  (0) 2011.05.25
linux - netstat  (0) 2011.02.14
linux에 mysql 설치하기  (0) 2010.01.05
vi 사용하기  (0) 2009.09.10

netstat는 시스템의 네트워크 연결 상태(tcp, udp, 소켓연결)을 보여주는 유틸리티입니다.

사용 방법은 netstat [options] 으로 사용하면 됩니다. 

 

* 옵션

 옵션

설명 

 -a

 모든 소켓을 보기. 이 옵션을 안 넣으면 상태가 Established 상태인 것만 나온다. 동일 옵션은 --all

 -c

 현재 실행 명령을 매 초마다 실행. 동일 옵션은 --continuous

    => netstat -anc (해당 명령을 매 초마다 실행.)

    => netstat 10 (-c 옵션이 안 들어가도 해당 숫자만큼 시간이 지난후에 명령어 실행.)

 -e

 확장 정보 추가. User 부분과 Inode 열이 추가된다. 동일 옵션은 --extend

 -g

  멀티캐스트에 대한 그룹별 정보를 보여줌 (IPv4/IPv6). 동일 옵션은 --groups

 -i

 인터페이스별 통계값. -I=(인터페이스명) / --interface=(인터페이스명) 을 하면 해당 인터페이스값만 보기도 가능.

 -l

 대기중인 소켓 리스트만 보여준다. 동일 옵션은 --listening

 -n

 도메인 주소를 읽어들이지 않고 숫자로 출력한다. --numeric-hosts --numeric-ports --numeric-users 명령어가 합쳐진 옵션. 동일 옵션은 --numeric

 --numeric-hosts : 호스트 부분을 IP로 출력.

 --numeric-ports : 포트 부분을 숫자로 출력.

 --numeric-users : 유저 부분을 숫자로 출력(UID).

 -o

연결 대기 시간 표기. 동일 옵션은 --timers

 -p

 PID(프로세서 ID) 와 사용중인 프로그램명이 표시된다. 동일 옵션은 --program

 -r

 라우팅 테이블 보기. 'route' 명령어와 동일. 동일 옵션은 --route

 -s

 프로토콜 요약 정보. 동일 옵션은 --statistics

 -t

 TCP 프로토콜 보기. 연결된 것만 나옴. 동일 옵션은 --tcp

 -u

 UDP 프로토콜 보기. 동일 옵션은 --udp

 -v

 버전 보기.

 -w

 RAW 프로토콜 보기. 동일 옵션은 --raw

 -A

 프로토콜별로 보기. 종류는 inet, unix, ipx, ax25, netrom, ddp 가 있음. 동일 옵션은 --protocol

    => netstat -A inet (TCP 프로토콜 연결 상태만 보기)

    => netstat --protocol=inet (위의 명령어와 동일)

 -M

 마스커레이딩 정보 표시. 동일 옵션은 --masquerade


 

* netstat 상태값

 정보

 설명

 Proto

 프로토콜 종류. TCP / UDP / RAW 가 있음.

 Recv-Q

 해당 프로그램이 현재 받는 바이트 표기.

 Send-Q

 해당 프로그램이 현재 보내는 바이트 표기.

 Local Address

 출발지 주소 및 포트. 자신의 주소 및 포트.

 Foreign Address

 목적지 주소 및 포트.

 State

 포트의 상태

    => CLOSED : 연결이 완전히 종료된 상태

    => CLOSED_WAIT : TCP 연결이 상위 응용프로그램 레벨로부터 연결 종료를 기다리는 상태

    => CLOSING : 흔하지 않으나 주로 확인 메세지가 전송 도중 유실된 상태

    => ESTABLISHED : 연결이 완료된 상태.

    => FIN_WAIT1 : 클라이언트가 서버에게 연결을 끊고자 요청하는 상태(FIN을 보낸 상태)

    => FIN_WAIT2 : 서버가 클라이언트로부터 연결 종료 응답을 기다리는 상태(서버가 클라이언트로 부터 최초로 FIN을 받은 후, 클라이언트에게 ACK을 주었을때)

    => LAST_ACK : 호스트가 원격지 호스트의 연결 종료 요구 승인을 기다리는 상태

    => LISTEN :  대기중인 포트. 포트가 열려 있고 클리이언트의 요청을 기다리는 상태.(대기중 상태)

    => SYN_RECV : 연결 요청을 받은 후에 확인 값을 기다리는 상태.

    => SYN_SENT : 클라이언트가 서버에게 연결을 요청한 상태

    => SYN_RECEIVED :  서버가 클라이언트로부터 접속 요구를 받아 클라이언트에게 응담을 하였지만, 아직 클라이언트에게 확인 메세지를 받지 못한 상태

    => TIME_WAIT : 연결은 종료되었지만 종료된 후 기다리는 상태. 약 1분 정도이며 -o 옵션으로 확인 가능. 시간이 다 지나면 사라짐.

    => UNKNOWN : 소켓의 상태를 알 수 없음.



TCP 플래그

 플래그

설명 

 SYN

Synchronization. 

세션을 설정하는 데 사용되며 초기에 시퀀스 번호를 임의로 생성하여 보냄. 100%는 아니지만 대부분 클라이언트측에서 보내는 플래그 

 ACK

Acknowledgement. 

받는 사람이 보낸 사람 시퀀스 번호에 TCP 계층에서 길이 또는 데이터 양을 더한 것과 같은 ACK를 보냄.

ACK의 번호와 응답을 통해 보낸 패켓에 대한 손실을 판단하여 재전송 하거나 다음 패킷을 전송

 FIN

Finish.

세션을 종료시키는데 사용되며, 보낸 사림이 더 이상 보낼 데이터가 없음을 보여줌.

 RST

Reset.

재설정을 하는 과정이며, 양방향에서 동시에 일어나는 중단 작업.

비정상적인 세션 연결 끊기에 해당

 PSH

 Push.

대화형 트래픽에 사용되며, 버퍼가 채워지기를 기다리지 않고 데이터를 전달. 데이터는 버퍼링 없이 바로 위 Layer가 아닌 7 Layer의 응용프로그램으로 바로 전달

 URG

Urgent.

Urgent point가 유효한 것인지를 나타냄. Urgent point란 전송하는 데이터 중에서 긴급히 전달해야 하는 내용이 있을 경우 사용 



기본 사용법

netstat -t 현재 접속중의 포트들의 상태 내용 확인

netstat -nap (열려 있는 모든 포트)

netstat -l 또는 netstat -nap | grep LISTEN (LISTEN 되는 모든 포트)

netstat -nap | grep ESTABLISHED | wc -l ( 모든 서비스 동시 접속자 수)

netstat -nap | grep :80 | grep ESTABLISHED | wc -l ( 웹 동시 접속자 수)

netstat -natc (열려있는 모든 TCP 포트를 일정시간마다 반복 출력한다) 


 

* 예제.

1. 인터넷 연결 상태 보기.


[root@navi-linux ~]# netstat -A inet

Active Internet connections (w/o servers)

Proto Recv-Q Send-Q Local Address               Foreign Address             State

tcp        0      0 navi-linux:35212            123.123.123.123:http           ESTABLISHED

tcp        0      0 navi-linux:56976            61-111-58-50.kidc.net:http  ESTABLISHED

tcp        0    314 navi-linux:telnet           231.231.231.231:netcheque     ESTABLISHED

 


2. 통계값 보기 (프로토콜별).


[root@navi-linux ~]# netstat -s

Ip:

    1141245 total packets received

    355 with invalid addresses

    0 forwarded

    0 incoming packets discarded

    1007688 incoming packets delivered

    1050768 requests sent out

    24 dropped because of missing route

Icmp:

    24 ICMP messages received

    0 input ICMP message failed.

    ICMP input histogram:

        destination unreachable: 22

        echo requests: 1

        echo replies: 1

    141 ICMP messages sent

    0 ICMP messages failed

    ICMP output histogram:

        destination unreachable: 135

        echo request: 5

        echo replies: 1

IcmpMsg:

        InType0: 1

        InType3: 22

        InType8: 1

        OutType0: 1

        OutType3: 135

        OutType8: 5

Tcp:

    64013 active connections openings

    16 passive connection openings

    10 failed connection attempts

    12 connection resets received

    6 connections established

    901778 segments received

    941524 segments send out

    2915 segments retransmited

    0 bad segments received.

    163 resets sent

Udp:

    105794 packets received

    4 packets to unknown port received.

    0 packet receive errors

    106216 packets sent

UdpLite:

TcpExt:

    1 ICMP packets dropped because socket was locked

    4112 TCP sockets finished time wait in fast timer

    2 packets rejects in established connections because of timestamp

    111607 delayed acks sent

    12 delayed acks further delayed because of locked socket

    Quick ack mode was activated 901 times

    112 packets directly queued to recvmsg prequeue.

    832 packets directly received from prequeue

    464924 packets header predicted

    48 packets header predicted and directly queued to user

    125499 acknowledgments not containing data received

    1063 predicted acknowledgments

    6 congestion windows recovered after partial ack

    0 TCP data loss events

    2 timeouts after SACK recovery

    393 other TCP timeouts

    901 DSACKs sent for old packets

    78 DSACKs received

    6 connections reset due to unexpected data

    10 connections reset due to early user close

    356 connections aborted due to timeout

    TCPDSACKIgnoredOld: 4

    TCPDSACKIgnoredNoUndo: 6

    TCPSackShiftFallback: 2

IpExt:

    InMcastPkts: 7643

    OutMcastPkts: 42

    InBcastPkts: 124586

    InOctets: 752411380

    OutOctets: 172659736

    InMcastOctets: 2477680

    OutMcastOctets: 11674

    InBcastOctets: 13876218

 

3. 통계값 보기 (인터페이스별).


[root@navi-linux ~]# netstat -i

Kernel Interface table

Iface       MTU Met    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR

Flg

eth0       1500   0  2168579      0      0      0  1053363      0      0      0

BMRU

eth1       1500   0        0      0      0      0        0      0      0      0

BMU

eth2       1500   0        0      0      0      0        0      0      0      0

BMU

lo        16436   0       20      0      0      0       20      0      0      0

LRU

 

4. 열려 있는 TCP 포트 보기.


[root@navi-linux ~]# netstat -lnt -A inet

Active Internet connections (only servers)

Proto Recv-Q Send-Q Local Address               Foreign Address             State

tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN

tcp        0      0 0.0.0.0:34580               0.0.0.0:*                   LISTEN

tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN

 

5. 연결된 TCP 포트 보기.


[root@navi-linux ~]# netstat -nt -A inet

Active Internet connections (w/o servers)

Proto Recv-Q Send-Q Local Address               Foreign Address             State

tcp        0      0 111.111.111.111:33659         123.123.123.123:80             ESTABLISHED

tcp        0      0 111.111.111.111:56976         61.111.58.50:80             ESTABLISHED

tcp        0    134 112.112.112.112:23            121.121.121.121:4008          ESTABLISHED

 

6. 모든 열려있는 포트 보기.

[root@navi-linux ~]# netstat -ant -A inet


Active Internet connections (w/o servers)

Proto Recv-Q Send-Q Local Address               Foreign Address             State


tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN

tcp        0      0 0.0.0.0:34580               0.0.0.0:*                   LISTEN

tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN


tcp        0      0 111.111.111.111:33659         123.123.123.123:80             ESTABLISHED

tcp        0      0 111.111.111.111:56976         61.111.58.50:80             ESTABLISHED

tcp        0    134 112.112.112.112:23            121.121.121.121:4008          ESTABLISHED

 

7. 특정 포트나 호스트 모니터링 하기. (1초마다 80포트(인터넷)를 보기. ':80' 라는 텍스트가 들어간 라인을 보여준다. netstat -A inet -n | grep :80 을 1초마다 실행하는 결과이다.)

[root@navi-linux ~]# netstat -A inet -n -c | grep :80

 

tcp        0      0 111.111.111.111:56214         123.123.123.123:80             ESTABLISHED

tcp        0      0 111.111.111.111:56976         61.111.58.50:80             ESTABLISHED

 

8. 네트워크 자원을 사용중인 프로그램 종료 하기.


[root@navi-linux ~]# netstat -A inet -atp

Active Internet connections (servers and established)

Proto Recv-Q Send-Q Local Address               Foreign Address             Stat

e       PID/Program name

tcp        0      0 *:sunrpc                    *:*                         LIST

EN      856/rpcbind

tcp        0      0 *:34580                     *:*                         LIST

EN      935/rpc.statd

tcp        0      0 *:ssh                       *:*                         LIST

EN      3681/sshd

tcp        0      0 navi-linux:47270            111.111.111.111:http           ESTA

BLISHED 2263/firefox

tcp        0      0 navi-linux:41638            111.111.111.111:http           ESTA

BLISHED 2263/firefox

tcp        0      0 navi-linux:telnet           222.222.222.222:netplan       ESTA

BLISHED 943/in.telnetd: 172

tcp        0      0 navi-linux:46763            111.111.111.111:http           ESTA

BLISHED 2263/firefox

tcp        0      0 navi-linux:47264            111.111.111.111:http           TIME

_WAIT   -

tcp        0      0 navi-linux:52984            123.123.123.123:ftp          ESTA

BLISHED 886/filezilla

tcp        0      0 navi-linux:56581            61-111-58-50.kidc.net:http  ESTA

BLISHED 1857/clock-applet

tcp        0      0 navi-linux:47273            111.111.111.111:http           ESTA

BLISHED 2263/firefox

 

파일질라가 네트워크를 이용중이다. 프로그램을 종료시키자. -p 옵션이 들어가 있어야 한다. 맨 우측 886/filezilla 가 보인다. 왼쪽이 프로세서 ID(PID)이고 오른쪽이 실행이름이다.

 

[root@navi-linux ~]# kill 886

 

kill 명령어로 파일질라의 PID를 입력하여 프로그램을 종료시킨다.

 

[root@navi-linux ~]# netstat -A inet -atp

Active Internet connections (servers and established)

Proto Recv-Q Send-Q Local Address               Foreign Address             Stat

e       PID/Program name

tcp        0      0 *:sunrpc                    *:*                         LIST

EN      856/rpcbind

tcp        0      0 *:34580                     *:*                         LIST

EN      935/rpc.statd

tcp        0      0 *:ssh                       *:*                         LIST

EN      3681/sshd

tcp        0      0 navi-linux:57621            111.111.111.111:http           ESTA

BLISHED 2263/firefox

tcp        0      2 navi-linux:telnet           222.222.222.222:netplan       ESTA

BLISHED 943/in.telnetd: 172

tcp        0      0 navi-linux:42278            111.111.111.111:http           ESTA

BLISHED 2263/firefox

tcp        0      0 navi-linux:52984            123.123.123.123:ftp          TIME

_WAIT   -

tcp        0      0 navi-linux:56581            61-111-58-50.kidc.net:http  ESTA

BLISHED 1857/clock-applet

 

재확인결과 없어져있다. TIME_WAIT 은 연결 종료 후 1분간 보인다.

 

현재 얼마나 많은 네트워크 접속이 있는지 확인하기

while [ true ]

do

net_status=`netstat -t | wc -l`

dt=`date "%Y-%m-%d %H:%M:%S"


echo "${dt} : ${net_status}"

done

결과

2012-02-06 12:03:32 : 5402

2012-02-06 12:03:35 : 5412




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

윈도우용 netstat

시작 - 실행 - cmd 에서 커맨드 입력 상태로 먼저 들어간다.

Netstat활성 TCP 연결, 컴퓨터 수신 포트, 이더넷 통계, IP 라우팅 테이블, IPv4 통계(IP, ICMP, TCP, UDP 프로토콜에 대한 통계), IPv6 통계(IPv6, ICMPv6, IPv6를 통한 TCP, IPv6를 통한 UDP 통계)를 표시합니다. netstat를 매개 변수 없이 사용하면 활성 TCP 연결을 표시합니다.

구문
netstat [-a] [-e] [-n] [-o] [-p Protocol] [-r] [-s] [Interval]

매개 변수
-a
모든 활성 TCP 연결과 컴퓨터가 수신하는 TCP 및 UDP 포트를 표시합니다.
-e
바이트 수 및 보내고 받은 패킷과 같은 이더넷 통계를 표시합니다. 이 매개 변수는 -s와 함께 사용할 수 있습니다.
-n
활성 TCP 연결을 표시합니다. 주소 및 포트 번호는 숫자로 표시되고 이름을 확인하는 작업은 수행하지 않습니다.
- o
활성 TCP 연결을 표시하고 각 연결의 프로세스 ID(PID)를 포함합니다. Windows 작업 관리자의 프로세스 탭에서 PID 기반 응용 프로그램을 찾을 수 있습니다. 이 매개 변수는 -a, -n 및 -p와 함께 사용할 수 있습니다.
-p Protocol
Protocol을 사용하여 지정한 프로토콜의 연결을 표시합니다. 이 경우 Protocol은 tcp, udp, tcpv6, udpv6이 될 수 있습니다. 매개 변수를 -s와 함께 사용하면 프로토콜이 통계를 표시합니다. Protocol은 tcp, udp, icmp, ip, tcpv6, udpv6, icmpv6, ipv6가 될 수 있습니다.
-s
프로토콜에 의해 통계를 표시합니다. 기본적으로 TCP, UDP, ICMP 및 IP 프로토콜에 대한 통계를 표시합니다. IPv6 프로토콜을 설치하면 IPv6를 통한 TCP, IPv6를 통한 UDP, ICMPv6, IPv6 프로토콜에 대한 통계가 표시됩니다. -p 매개 변수는 프로토콜의 집합을 지정하는 데 사용할 수 있습니다.
-r
IP 라우팅 테이블의 내용을 표시합니다. 이것은 route print 명령과 같습니다.
Interval
Interval초마다 선택한 정보를 다시 표시합니다. 통계를 다시 표시하지 않으려면 Ctrl+C를 누릅니다. 이 매개 변수를 생략하면 netstat는 선택한 정보를 한 번만 표시합니다.
/?
명령 프롬프트에서 도움말을 표시합니다.
설명
이 명령과 함께 사용되는 매개 변수는 슬래시(/) 대신 하이픈(-)을 앞에 붙여야 합니다.
netstat는 다음과 같은 정보에 대한 통계를 제공합니다.
Proto
프로토콜(TCP 또는 UDP) 이름입니다.

로컬 주소
사용되고 있는 로컬 컴퓨터의 IP 주소와 포트 번호입니다. -n 매개 변수를 지정하지 않으면 IP 주소 및 포트 이름에 해당하는 로컬 컴퓨터의 이름이 표시됩니다. 포트를 아직 설정하지 않은 경우 포트 번호가 별표(*)로 나타납니다.

외부 주소
소켓이 연결된 원격 컴퓨터의 IP 주소와 포트 번호. -n 매개 변수를 지정하지 않으면 IP 주소 및 포트에 해당하는 이름이 표시됩니다. 포트를 아직 설정하지 않은 경우 포트 번호가 별표(*)로 나타납니다.

(state)
TCP 연결 상태를 표시합니다. 가능한 상태는 아래와 같습니다.

CLOSE_WAIT

CLOSED

ESTABLISHED

FIN_WAIT_1

FIN_WAIT_2

LAST_ACK

LISTEN

SYN_RECEIVED

SYN_SEND

TIMED_WAIT

TCP 연결 상태에 대한 자세한 내용은 RFC 793을 참조하십시오.

이 명령은 인터넷 프로토콜(TCP/IP) 프로토콜이 네트워크 연결의 네트워크 어댑터 속성의 구성 요소로 설치된 경우에만 사용할 수 있습니다.

이더넷 통계 및 모든 프로토콜 통계를 표시하려면 다음과 같이 입력합니다.

netstat -e -s

TCP 및 UDP 프로토콜의 통계를 표시하려면 다음과 같이 입력합니다.

netstat -s -p tcp udp

활성 TCP 연결 및 프로세스 ID를 5초마다 표시하려면 다음과 같이 입력합니다.

nbtstat -o 5

숫자 형식을 사용하여 활성 TCP 연결 및 프로세스 ID를 표시하려면 다음과 같이 입력합니다.

nbtstat -n -o

* 옵션

  -a : 모든 연결 및 열린 포트를 확인한다. 리눅스의 -a 옵션과 동일.

  -b : 현재 연결이 어떤 프로그램이 사용중인지 표시한다. PID(프로세서 ID)도 표시된다. 리눅스의 -p 옵션과 동일.

  -e : 인터페이스의 통계치를 보여준다. 윈도우용은 기본적인것만 나오고 리눅스는 매우 자세히 나온다. 리눅스의 -i 옵션과 동일.

  -n : 주소 및 포트를 숫자 형식으로 표시. 리눅스의 -n 옵션과 동일.

  -o : 현재 연결이 어떤 프로그램이 사용중인지 PID(프로세서 ID)만 표시한다.

  -r : 라우팅 테이블을 표시한다. route print와 동일하다. 리눅스의 -r 옵션과 동일.

  -s : 프로토콜별 통계치를 보여준다. 리눅스의 -s 옵션과 동일.

  -v : -b 옵션과 같이 사용시 아주 자세히 어떤 파일들이 네트워크 연결에 쓰는지 볼 수 있다. 정보 수집을 하여 시간이 오래 걸린다.

  숫자 : 숫자값을 입력하면 해당 초만큼 간격으로 명령을 반복 실행한다. 정지는 Ctrl+C
[출처] 리눅스 명령어 - netstat (네트워크 연결 상태)|작성자 유미화