shell script상에서 자동화를 하고 싶은 암호 입력 부분은 다음과 같이 해결할 수 있다.

 

 

#!/bin/sh

 

INSTALL_DIR=/usr/local/mysql

 

$INSTALL_DIR/bin/mysql -u root << !
use mysql;
update user set password=password('1234') where user ='root';
flush privileges;
!

 

 

 

'unix and linux' 카테고리의 다른 글

grep 사용  (0) 2007.12.30
shell 상에서 사용하는 옵션 지정하기-shopt  (0) 2007.12.29
grep을 이용하여 여러개의 패턴으로 먼가를 찾기  (0) 2007.12.28
bash if 문 비교  (0) 2007.11.30
[bash] 로깅 시간 출력  (0) 2007.11.14
Posted by '김용환'
,
grep -E "111.111.111.111|222.222.222.222" a.txt

'unix and linux' 카테고리의 다른 글

shell 상에서 사용하는 옵션 지정하기-shopt  (0) 2007.12.29
쉘 자동화 -mysql (shell)  (0) 2007.12.29
bash if 문 비교  (0) 2007.11.30
[bash] 로깅 시간 출력  (0) 2007.11.14
netstat 과 tcp 상태  (0) 2007.10.31
Posted by '김용환'
,

bash if 문 비교

unix and linux 2007. 11. 30. 10:02

 

shell script 상에서 항상 혼란스러워 하는 것중의 하나가 바로 scalar 비교이다.

결과가 없으면 string type이 아니라,  scalar type이다. 그러므로, "$aaa" == "" 이렇게 비교를 해야 한다..

쩝쩝..

 

 

http://linuxcommand.org/wss0100.php

 

 

Stay Out Of Trouble

by William Shotts, Jr.

Now that our scripts are getting a little more complicated, I want to point out some common mistakes that you might run into. To do this, create the following script called trouble.bash. Be sure to enter it exactly as written.

#!/bin/bash

number=1

if [ $number = "1" ]; then
    echo "Number equals 1"
else
    echo "Number does not equal 1"
fi
       

When you run this script, it should output the line "Number equals 1" because, well, number equals 1. If you don't get the expected output, check your typing; you made a mistake.

Empty variables

Edit the script to change line 3 from:

number=1
       

to:

number=
       

and run the script again. This time you should get the following:

[me@linuxbox me]$ ./trouble.bash
/trouble.bash: [: =: unary operator expected.
Number does not equal 1

As you can see, bash displayed an error message when we ran the script. You probably think that by removing the "1" on line 3 it created a syntax error on line 3, but it didn't. Let's look at the error message again:

./trouble.bash: [: =: unary operator expected

We can see that ./trouble.bash is reporting the error and the error has to do with "[". Remember that "[" is an abbreviation for the test shell builtin. From this we can determine that the error is occurring on line 5 not line 3.

First, let me say there is nothing wrong with line 3. number= is perfectly good syntax. You will sometimes want to set a variable's value to nothing. You can confirm the validity of this by trying it on the command line:

[me@linuxbox me]$ number=
[me@linuxbox me]$

See, no error message. So what's wrong with line 5? It worked before.

To understand this error, we have to see what the shell sees. Remember that the shell spends a lot of its life substituting text. In line 5, the shell substitutes the value of number where it sees $number. In our first try (when number=1), the shell substituted 1 for $number like so:

if [ 1 = "1" ]; then
       

However, when we set number to nothing (number=), the shell saw this after the substitution:

if [ = "1" ]; then
       

which is an error. It also explains the rest of the error message we received. The "=" is a binary operator; that is, it expects two items to operate upon - one on each side. What the shell was trying to tell us was that there was only one item and there should have been a unary operator (like "!") that only operates on a single item.

To fix this problem, change line 5 to read:

if [ "$number" = "1" ]; then
       

Now when the shell performs the substitution it will see:

if [ "" = "1" ]; then
       

which correctly expresses our intent.

This brings up an important thing to remember when you are writing your scripts. Consider what happens if a variable is set to equal nothing.

Missing quotes

Edit line 6 to remove the trailing quote from the end of the line:

   echo "Number equals 1
       

and run the script again. You should get this:

[me@linuxbox me]$ ./trouble.bash
./trouble.bash: line 8: unexpected EOF while looking for matching "
./trouble.bash: line 10 systax error: unexpected end of file

Here we have another case of a mistake in one line causing a problem later in the script. What happens is the shell keeps looking for the closing quotation mark to tell it where the end of the string is, but runs into the end of the file before it finds it.

These errors can be a real pain to find in a long script. This is one reason you should test your scripts frequently when you are writing them so there is less new code to test. I also find that text editors with syntax highlighting (like nedit or kate) make these kinds of bugs easier to find.

Isolating problems

Finding bugs in your programs can sometimes be very difficult and frustrating. Here are a couple of techniques that you will find useful:

Isolate blocks of code by "commenting them out." This trick involves putting comment characters at the beginning of lines of code to stop the shell from reading them. Frequently, you will do this to a block of code to see if a particular problem goes away. By doing this, you can isolate which part of a program is causing (or not causing) a problem.

For example, when we were looking for our missing quotation we could have done this:

#!/bin/bash

number=1

if [ $number = "1" ]; then
    echo "Number equals 1
#else
#   echo "Number does not equal 1"
fi
       

By commenting out the else clause and running the script, we could show that the problem was not in the else clause even though the error message suggested that it was.

Use echo commands to verify your assumptions. As you gain experience tracking down bugs, you will discover that bugs are often not where you first expect to find them. A common problem will be that you will make a false assumption about the performance of your program. You will see a problem develop at a certain point in your program and assume that the problem is there. This is often incorrect, as we have seen. To combat this, you should place echo commands in your code while you are debugging, to produce messages that confirm the program is doing what is expected. There are two kinds of messages that you should insert.

The first type simply announces that you have reached a certain point in the program. We saw this in our earlier discussion on stubbing. It is useful to know that program flow is happening the way we expect.

The second type displays the value of a variable (or variables) used in a calculation or test. You will often find that a portion of your program will fail because something that you assumed was correct earlier in your program is, in fact, incorrect and is causing your program to fail later on.

Watching your script run

It is possible to have bash show you what it is doing when you run your script. To do this, add a "-x" to the first line of your script, like this:

#!/bin/bash -x
       

Now, when you run your script, bash will display each line (with substitutions performed) as it executes it. This technique is called tracing. Here is what it looks like:

[me@linuxbox me]$ ./trouble.bash
+ number=1
+ '[' 1 = 1 ']'
+ echo 'Number equals 1'
Number equals 1

Alternately, you can use the set command within your script to turn tracing on and off. Use set -x to turn tracing on and set +x to turn tracing off. For example.:

#!/bin/bash

number=1

set -x
if [ $number = "1" ]; then
    echo "Number equals 1"
else
    echo "Number does not equal 1"
fi
set +x
       
Posted by '김용환'
,

 

로깅 시간 출력

 

 #!/bin/bash
cd /data/env/project/log
DATE=$(date '+%y/%m/%d %H:%M:%S')
echo $DATE >  /data/env/project/log/logIDS.txt
eval 'exec getLog.pl -p ids >> /data/env/project/log/logIDS.txt'

 

결과

 

[a50236:/data/env/project/log]# cat logIDS.txt
07/11/13 20:31:45
host : aaaa 10%  20%  40%  50%  60%  100%

'unix and linux' 카테고리의 다른 글

grep을 이용하여 여러개의 패턴으로 먼가를 찾기  (0) 2007.12.28
bash if 문 비교  (0) 2007.11.30
netstat 과 tcp 상태  (0) 2007.10.31
grep -c 와 wc -l은 똑같은 명령어이다.  (0) 2007.10.18
crond 문제  (0) 2007.10.17
Posted by '김용환'
,

 

 

출처 : http://cafe.naver.com/ArticleRead.nhn?articleid=100&sc=e0d5351d01452b9a12&clubid=11678574

 

netstat의 State 필드에 표시되는 TCP 상태표시가 갖는 의미.
RFC 793 문서에 있는 TCP 기본 연결, 종료 과정 참고.
 
-----------------------------------------------------------

# netstat -atn
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address     Foreign Address    State
... 생략 ...
tcp  0  0 0.0.0.0:25       0.0.0.0:*       LISTEN   <-- 포트가 열렸음
tcp  0  0 192.168.123.10:32799  207.46.106.141:1863  ESTABLISHED <-- 서로 연결중
tcp  0  0 192.168.123.10:32794  218.xxx.xx.xx:22   ESTABLISHED
tcp  0  0 192.168.123.10:32802  207.46.108.46:1863  CLOSE_WAIT <-- 종료 대기중
tcp  0  0 192.168.123.10:33244  211.xxx.xx.x:80    ESTABLISHED
... 생략 ...
-----------------------------------------------------------
 
1) TCP 연결관련 상태
 
* RFC 793문서에 나온 기본적인 TCP 연결 과정

   TCP A                           TCP B

 1. CLOSED                          LISTEN
 2. SYN-SENT  --> < SEQ=100>< CTL=SYN>         --> SYN-RECEIVED
 3. ESTABLISHED <-- < SEQ=300>< ACK=101>< CTL=SYN,ACK> <-- SYN-RECEIVED
 4. ESTABLISHED --> < SEQ=101>< ACK=301>< CTL=ACK>    --> ESTABLISHED
 5. ESTABLISHED --> < SEQ=101>< ACK=301>< CTL=ACK>< DATA> --> ESTABLISHED

LISTEN   : 데몬이 요청을 발을 수 있도록 연결 요구를 기다리는 상태
 즉, 포트가 열려있음을 의미. http(80), mail(25), ftp(21), telnet(23) 등
 위에서 포트 25(mail)이 메일을 받을 수 있도록 열려 있는 상태
 윈도우즈에서는 LISTENING으로 표시
SYN_SENT  : 로컬에서 원격으로 연결 요청(SYN 신호를 보냄)을 시도한 상태
SYN_RECV  : 원격으로 부터 연결 요청을 받은 상태
 요청을 받아 SYN+ACK 신호로 응답은 한 상태이지만 ACK는 받지 못했다.
 netstat로 확인할 때 SYN_RECV가 상당히 많다면 TCP SYN 플러딩(Flooding) 공격일
 가능성이 있다.
 윈도우즈와 솔라리스에서는 SYN_RECEIVED으로, FreeBSD는 SYN_RCVD으로 표시
ESTABLISHED : 서로 연결이 되어 있는 상태
 위에서 192.168.123.10의 포트 32794과 218.xxx.xx.xx의 포트 22(ssh)이 서로
 연결되어 있는 상태

2) TCP 종료관련 상태

* 정상적인 연결 종료 과정

   TCP A                          TCP B

 1. ESTABLISHED                       ESTABLISHED
 2. (Close)
   FIN-WAIT-1 --> < SEQ=100>< ACK=300>< CTL=FIN,ACK> --> CLOSE-WAIT
 3. FIN-WAIT-2 <-- < SEQ=300>< ACK=101>< CTL=ACK>   <-- CLOSE-WAIT
 4.                    (Close)
   TIME-WAIT  <-- < SEQ=300>< ACK=101>< CTL=FIN,ACK> <-- LAST-ACK
 5. TIME-WAIT  --> < SEQ=101>< ACK=301>< CTL=ACK>   --> CLOSED
 6. (2 MSL)
   CLOSED                           

FIN_WAIT1  : 소켓이 닫히고 연결이 종료되고 있는 상태. 원격의 응답은 받을 수 있다.
 솔라리스에서는 FIN_WAIT_1로 표시
FIN_WAIT2  : 로컬이 원격으로 부터 연결 종료 요구를 기다리는 상태
 솔라리스에서는 FIN_WAIT_2로 표시
CLOSE_WAIT : 원격의 연결 요청을 받고 연결이 종료되기를 기다리는 상태
 원격으로 부터 FIN+ACK 신호를 받고 ACK 신호를 원격에 보냈다.
TIME_WAIT  : 연결은 종료되었으나 원격의 수신 보장을 위해 기다리고 있는 상태
 이 상태를 특히 자주 보게되는 Apache에서 KeepAlive를 OFF로 해둔 경우,
 Tomcat 서버를 쓰는 경우 등
LAST_ACK  : 연결은 종료되었고 승인을 기다리는 상태
CLOSED   : 완전히 연결이 종료된 상태

※ 위의 FIN_WAIT1, FIN_WAIT2, CLOSE_WAIT 3개 상태는 연결 종료를 위해 서로간에
  신호를 주고받는 과정에 나타나는 상태로 이해하면 된다.
  종료 요청을 한 곳에서는 FIN_WAIT1, FIN_WAIT2, TIME_WAIT 상태가
  종료 요청을 받는 곳에서는 CLOSE_WAIT, LAST_ACK 상태가 표시된다.

3) 기타

CLOSING   : 연결은 종료되었으나 전송도중 데이타가 분실된 상태
UNKNOWN   : 소켓의 상태를 알 수 없음

솔라리스의 netstat 명령에서는 다음 2개의 상태를 더 표시한다.

IDLE    : 소켓이 열렸지만 binding 되지 않은 상태
BOUND    : listen이나 연결을 위한 준비 상태

 

추가) Time-Wait

먼저 종료를 시킨경우는 Time-Wait 과정을 거치게 된다

종료요청을 하게되변 FIN 을 전송하게 되며

 

Time-Wait 상태

** A가 먼저 종료하는 경우

< four-way handshaking >

   A                                  B

 FIN  ------------------>

       <-----------------   ACK

       <-----------------   FIN

ACK  ------------------>

Time-Wait                      소켓소멸

      ~

소켓소멸

 

 

결론> 발생이유: 마지막 ACK가 소멸 되었을 경우 재전송을 하기 위함

         따라서 재시작시 Bind 에러가 발생하며 이는 적정시간이 흐르면 해제가 된다

        이때 접속되어있는 클라이언트가 패킷을 송신을 하면 Time-Wait 상태를 유지하는 타이머는 재시작된다

       이는 Time-Wait상태가 길어질 수 있는 결과를 초래한다

해결방안 : 소켓옵션중 SO_REUSEADDR의 상태를 1(TRUE)로 설정한다

                물론, 접속자가 없는 상태에선 Fin메세지를 시작으로 four-way handshaking 과정을 거치지 않는다

 

 

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

 

LISTEN : 서버의 데몬이 떠서 접속 요청을 기다리는 상태

SYS-SENT : 로컬의 클라이언트 애플리케이션이 원격 호스트에 연결을 요청한 상태

SYS-RECEIVED : 서버가 클라이언트로 부터 접속 요구를 받아 클라이언트에게 응답을 했지만 아직 클라이언트에게 확인 메세지는 받지 않은 상태

ESTALISHED : 3Way Handshaking 완료된후 서로 연결된 상태

FIN-WAIT, CLOSE-WAIT, FIN-WAIT2 : 서버에서 연결을 종료하기 위해 클라이언트에게 종결을 요청하고 회신을 받아 종료하는 과정의 상태

CLOSING : 흔하지 않지만 주로 확인 메세지가 존송 도중 분실된 상태

TIME-WAIT : 연결은 종료 되었지만 분실되었을지 모를 느린 세그먼트를 위해 당분간 소켓을 열어 놓은 상태

CLOSED : 완전히 종료

'unix and linux' 카테고리의 다른 글

bash if 문 비교  (0) 2007.11.30
[bash] 로깅 시간 출력  (0) 2007.11.14
grep -c 와 wc -l은 똑같은 명령어이다.  (0) 2007.10.18
crond 문제  (0) 2007.10.17
bash 배열 선언 및 처리하기  (0) 2007.10.16
Posted by '김용환'
,

 둘이 똑같은 명령어이다.


:/home/www/backup/apachelog/a]# grep -c \"-\" access_https.071016
21109
:/home/www/backup/apachelog/a]# grep  \"-\" access_https.071016 | wc -l
21109

'unix and linux' 카테고리의 다른 글

[bash] 로깅 시간 출력  (0) 2007.11.14
netstat 과 tcp 상태  (0) 2007.10.31
crond 문제  (0) 2007.10.17
bash 배열 선언 및 처리하기  (0) 2007.10.16
DNS 서버 보기  (0) 2007.10.10
Posted by '김용환'
,

crond 문제

unix and linux 2007. 10. 17. 02:43

 

 crontab이 안돌아가는 문제가 있었다.

 

/var/log/cron 파일을 열어보니..

 

10월 9일부터 crond 데몬이 동작되지 않았다.

 

 

 Oct  9 07:57:01 nhn346 crond[28706]: (root) CMD (/usr/lib/sa/sa1 1 1)
Oct 12 18:10:22 nhn346 crontab[10389]: (root) BEGIN EDIT (root)
Oct 12 18:10:36 nhn346 crontab[10389]: (root) END EDIT (root)

 

 

아무리 /etc/rc.d/init.d/crond restart를 해도 재시작이 안되고, kill -9 crond 을 해도 죽지 않아.

리눅스 재부팅 시작~~

'unix and linux' 카테고리의 다른 글

netstat 과 tcp 상태  (0) 2007.10.31
grep -c 와 wc -l은 똑같은 명령어이다.  (0) 2007.10.18
bash 배열 선언 및 처리하기  (0) 2007.10.16
DNS 서버 보기  (0) 2007.10.10
crontab 이야기  (0) 2007.10.10
Posted by '김용환'
,

 #!/bin/bash

files[1]="/etc/rc.local"
files[2]="/etc/rsyncd.conf"
files[3]="/etc/xinetd.d/rsync"

element_count=${#files[@]}

index=0

while [ "$index" -lt "$element_count" ]
do
    let "index = $index + 1"
    if [ -f "${files[index]}" ]; then
        size=`ls -nl ${files[index]} | awk ' {print $5 }'`
        if [ $size = "0" ] ; then
            echo "${files[index]}" is broken
        fi

    else
        echo "${files[index]}" is broken
    fi

done

 

 

참고하세용

'unix and linux' 카테고리의 다른 글

grep -c 와 wc -l은 똑같은 명령어이다.  (0) 2007.10.18
crond 문제  (0) 2007.10.17
DNS 서버 보기  (0) 2007.10.10
crontab 이야기  (0) 2007.10.10
bash shell script substitution  (0) 2007.10.09
Posted by '김용환'
,

DNS 서버 보기

unix and linux 2007. 10. 10. 02:00

리눅스에서는 다음의 명령을 쓰면 됩니다.

 

 vi /etc/resolv.conf

 

<결과>

nameserver 203.54.1.20
nameserver 203.54.1.21

 

 

 

윈도우는 다음의 명령을 사용하면 된다.

 ipconfig /all

 

 

'unix and linux' 카테고리의 다른 글

crond 문제  (0) 2007.10.17
bash 배열 선언 및 처리하기  (0) 2007.10.16
crontab 이야기  (0) 2007.10.10
bash shell script substitution  (0) 2007.10.09
특정 시간마다 로그 파일 지우기.  (0) 2007.10.09
Posted by '김용환'
,

crontab 이야기

unix and linux 2007. 10. 10. 01:09

crontab을 쓰면 자동적으로 해당 계정의 .shrc 파일을 읽는 줄 (환경설정 파일) 알았다.

하지만 아니었다.

 

 #!/bin/bash
echo `date` >> /home/www/script/test.log
source /home/www/.bashrc
/home/www/script/restart-service.sh >> /home/www/script/test.log
echo "end"
~

 

 

만약 당신이 crontab을 이용하여 환경설정 변수를 사용하려면 반드시

source 명령어를 사용해야 할 것 이다.

 

 

'unix and linux' 카테고리의 다른 글

bash 배열 선언 및 처리하기  (0) 2007.10.16
DNS 서버 보기  (0) 2007.10.10
bash shell script substitution  (0) 2007.10.09
특정 시간마다 로그 파일 지우기.  (0) 2007.10.09
shell에서 하루 전 날짜 구하기  (0) 2007.10.09
Posted by '김용환'
,