Archive for the ‘linux’ Category

netcat으로 원격 실행

목요일, 3월 19th, 2009

신뢰하는 시스템간에서 간단하게 원격 명령을 시키고 싶을 때

(저는 임베디드 보드랑 호스트의 경우였습니다)

호스트에서 스크립트로 명령어를 전송하면 타겟에서 실행하게 하고 싶었어요

 

nc를 사용했습니다.

타겟은 서버가 되고 호스트는 클라이언트가 됩니다.

서버(타겟)

서버 스크립트 (/root/ncsrv_daniel.sh)

#!/bin/sh
while true
do
echo starting new nc session
nc -v -l -p 1234 -e /bin/sh
done

shell 을 띄우도록 설정.

타겟의 프롬프트에서 해당 스크립트 실행

 

클라이언트(호스트)

호스트 스크립트

echo ./remCmd.sh\;exit | nc 192.168.1.111 1234[1]

nc로 접속한다음 ./remCmd.sh;exit를 입력하도록 함.

remCmd.sh가 원격으로 타겟에서 실행하고자 하는 프로그램. 타겟의 /root/에 있음.

 

테스트 스크립트 (nctest.sh)

#!/bin/bash

ok_count=0
fail_count=0

for i in `seq 1 100`;     100번 반복 테스트.
do
echo ${i}th run…
echo ./remCmd.sh\;exit | nc 192.168.1.111 1234
result=$?
echo done ${i}th run. return $result
if [ $result -eq 0 ] ;
then
((ok_count++))
else
((fail_count++))
fi
sleep 1      종료후 nc 서버가 다시 뜨는 데 시간이 걸려서 기다려줌.
done
echo OK: $ok_count
echo FAIL: $fail_count


[1] 또는

nc 192.168.1.111 1234 –c “echo ./remCmd.sh\;exit” (또는 적절한 스크립트)

를 실행해도 될 것임. (테스트해보진 않았음)

Ubuntu에서 하드디스크 사양 보기

화요일, 2월 3rd, 2009

그 용도로만 쓰는 건 아니지만 smartmon이 있습니다. (hdparm으로 못보는 LVM 으로 설정된 디스크도 잘 보이네요)

# apt-get smartmontools

# smartctl -a /dev/sda

하면 됩니다.

=== START OF INFORMATION SECTION ===
Model Family:     Western Digital Caviar RE Serial ATA series
Device Model:     WDC WD5000YS-70VJB1
Serial Number:    ……………………
Firmware Version: 00.0HPG0
User Capacity:    500,107,862,016 bytes
Device is:        In smartctl database [for details use: -P show]
ATA Version is:   7
ATA Standard is:  Exact ATA specification draft version not indicated
Local Time is:    Tue Feb  3 12:24:00 2009 KST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

 

http://www.howtoforge.com/checking-hard-disk-sanity-with-smartmontools-debian-ubuntu

scponly를 이용해서 sftp만 제공하고 chroot로 다른 디렉토리 접근 막기

목요일, 1월 22nd, 2009

http://ubuntuforums.org/showthread.php?t=451510 (원래 포스트)

http://geekzine.org/2007/09/28/easy-sftp-and-chroot-sftp-with-scponly/

항상 실패했었는데 좋은 패키지가 있군요

외부 사용자에게 셸은 안주고 sftp만 제공해서 다운로드/업로드만 되게 하고 싶을 때가 있습니다. ftp는 보안상 피하고 싶구요.

그때 잘 쓸 수 있겠네요.

간단하게 설명하면 (데비안/우분투 기준입니다)

1. scponly 패키지를 설치한다.

2. 거기서 제공하는 스크립트로 chroot jail을 만들고 사용자를 추가한다.

끝.

입니다.

자세한 설명은 위 링크에 돼 있구요

제가 한 스샷과 함께 보면,

1. scponly 패키지 설치

$ sudo apt-get install scponly

이러면 됩니다.

테스트로 일단 테스트할 사용자를 만들었다 치고

그 사용자의 shell을 scponly로 바꿔줍니다.

$ sudo chsh -s /usr/bin/scponly username

그리고 sftp 해보기

$ sftp username@서버

image

2. Chroot로 경로 제한해주기

chroot로 안해주면 sftp로 서버의 모든 경로를 다 이동해다닐 수 있습니다.

꼭 해줘야겠죠.

$ sudo dpkg-reconfigure -plow scponly

해줍니다. 그러면 뭐라뭐라 경고가 뜰텐데. chroot쓸라면 꼭 suid를 세팅 해야 하기 때문입니다. yes를 선택

image

그리고 제공된 스크립트를 압축 풀어서 실행해줍니다.

$ cd /usr/share/doc/scponly/setup_chroot
$ sudo gunzip setup_chroot.sh.gz
$ sudo chmod +x setup_chroot.sh
$ sudo ./setup_chroot.sh

실행하면 새로 추가할 사용자 이름, chroot 경로등을 물어보고 셋업해줍니다.

image

암호까지 입력했으면 이제 셋업 된 겁니다.

접속해봅시다 ^^

우분투에선(저는 8.04) 잘 되는데 제 VM(데비안) 오류가 나네요

아항~ 보니깐 dev/null이 없어요. 아마 데비안의 버전에서 스크립트 버그인 듯.

$ mkdir /home/scponly/dev
$ mknod -m 666 /home/scponly/dev/null c 1 3

이렇게 하니 접속 되네요.

image

그리고 유저 이름이 긴 경우인 것 같은데 winscp에서 에러메시지 같은게 납니다.(제가 테스트한 데비안 버전의 경우)

이 때는 제공된(/usr/share/doc/scponly/group.c)를 빌드해서 카피해주면 되나봐요. 그러나 쓰는 데 문제 없는 거 같아서 놔뒀습니다.

/proc/meminfo 내용 [Red Hat] 자료

화요일, 1월 20th, 2009

출처 : http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/en-US/Reference_Guide/s2-proc-meminfo.html

/proc/meminfo 내용

This is one of the more commonly used files in the /proc/ directory, as it reports a large amount of valuable information about the systems RAM usage.

The following sample /proc/meminfo virtual file is from a system with 256 MB of RAM and 512 MB of swap space:

         MemTotal: 255908 kB MemFree: 69936 kB Buffers: 15812 kB Cached: 115124 kB SwapCached: 0 kB Active: 92700 kB Inactive: 63792 kB HighTotal: 0 kB HighFree: 0 kB LowTotal: 255908 kB LowFree: 69936 kB SwapTotal: 524280 kB SwapFree: 524280 kB Dirty: 4 kB Writeback: 0 kB Mapped: 42236 kB Slab: 25912 kB Committed_AS: 118680 kB PageTables: 1236 kB VmallocTotal: 3874808 kB VmallocUsed: 1416 kB VmallocChunk: 3872908 kB HugePages_Total: 0 HugePages_Free: 0 Hugepagesize: 4096 kB       

Much of the information here is used by the free, top, and ps commands. In fact, the output of the free command is similar in appearance to the contents and structure of /proc/meminfo. But by looking directly at /proc/meminfo, more details are revealed:

  • MemTotal — Total amount of physical RAM, in kilobytes.

  • MemFree — The amount of physical RAM, in kilobytes, left unused by the system.

  • Buffers — The amount of physical RAM, in kilobytes, used for file buffers.

  • Cached — The amount of physical RAM, in kilobytes, used as cache memory.

  • SwapCached — The amount of swap, in kilobytes, used as cache memory.

  • Active — The total amount of buffer or page cache memory, in kilobytes, that is in active use. This is memory that has been recently used and is usually not reclaimed for other purposes.

  • Inactive — The total amount of buffer or page cache memory, in kilobytes, that are free and available. This is memory that has not been recently used and can be reclaimed for other purposes.

  • HighTotal and HighFree — The total and free amount of memory, in kilobytes, that is not directly mapped into kernel space. The HighTotal value can vary based on the type of kernel used.

  • LowTotal and LowFree — The total and free amount of memory, in kilobytes, that is directly mapped into kernel space. The LowTotal value can vary based on the type of kernel used.

  • SwapTotal — The total amount of swap available, in kilobytes.

  • SwapFree — The total amount of swap free, in kilobytes.

  • Dirty — The total amount of memory, in kilobytes, waiting to be written back to the disk.

  • Writeback — The total amount of memory, in kilobytes, actively being written back to the disk.

  • Mapped — The total amount of memory, in kilobytes, which have been used to map devices, files, or libraries using the mmap command.

  • Slab — The total amount of memory, in kilobytes, used by the kernel to cache data structures for its own use.

  • Committed_AS — The total amount of memory, in kilobytes, estimated to complete the workload. This value represents the worst case scenario value, and also includes swap memory.

  • PageTables — The total amount of memory, in kilobytes, dedicated to the lowest page table level.

  • VMallocTotal — The total amount of memory, in kilobytes, of total allocated virtual address space.

  • VMallocUsed — The total amount of memory, in kilobytes, of used virtual address space.

  • VMallocChunk — The largest contiguous block of memory, in kilobytes, of available virtual address space.

  • HugePages_Total — The total number of hugepages for the system. The number is derived by dividing Hugepagesize by the megabytes set aside for hugepages specified in /proc/sys/vm/hugetlb_pool. This statistic only appears on the x86, Itanium, and AMD64 architectures.

  • HugePages_Free — The total number of hugepages available for the system. This statistic only appears on the x86, Itanium, and AMD64 architectures.

  • Hugepagesize — The size for each hugepages unit in kilobytes. By default, the value is 4096 KB on uniprocessor kernels for 32 bit architectures. For SMP, hugemem kernels, and AMD64, the default is 2048 KB. For Itanium architectures, the default is 262144 KB. This statistic only appears on the x86, Itanium, and AMD64 architectures.

Man page를 pdf로 출력

토요일, 1월 10th, 2009

man의 옵션인 -t를 사용

그리고 ps2pdf를 씁니다.

 

$ man -t ioctl > ioctl.ps  # 자기 로케일에 따른 출력. 한글이 나오면 pdf에서 깨질 수 있음.

또는

$ man -t -L C ioctl > ioctl.ps   # 영문으로

이후

$ ps2pdf ioctl.ps

만들어진 PDF파일 모습

ubuntu 리눅스 커스텀 커널 컴파일 하기

목요일, 8월 28th, 2008

사용하는 머신의 램이 8기가인데 우분트 웍스테이션의 기본 커널이 4기가까지 지원이라 커널을 새로 빌드해야 할 일이 있었습니다.

 

우분투에서 채용된 원래 커널 소스에 설정을 가지고 램 설정만 바꿔서 컴파일했습니다.

 

다음은 하는 방법입니다.

1. 커널 소스 구하기

우분투는 데비안 계열이니 바로 소스 설치 가능합니다.

그리고 커널은 특별히 소스 패키지 이름이 따로 있습니다.

$ sudo apt-get install linux-source

그러면 /usr/src 아래에 깔립니다.

image

 

2. 커널 개발용 패키지 설치

개발용 패키지를 미리 다 받아둔다기 보단 필요한 패키지가 있다고 에러 메시지가 나므로, 그 때 설치했습니다.

예를 들어,

$ sudo apt-get install kernel-package libncurses5-dev fakeroot wget bzip2 kernel-wedge xmlto

 

3. configuration 복사해오기

이제 지금 돌고 있는 커널의 소스를 받았으니 configuration을 복사해 와야겠지요

이제부턴 편의를 위해 루트로 작업하겠습니다.

$ sudo su

# cp /boot/config-2.6.24-19-generic linux-2.4.24/config_old

 

4. make menuconfig (-> configuration)

# make menuconfig

그리고 Load an Alternate Configuration File를 선택해서 config_old를 불러옵니다.

image

그리고 저 같은 경우 여기서 하나만 바꾸면 됩니다.

Processor type and features -> High Memory Support (4GB)

이렇게 돼 있는 걸 64GB로 바꿉니다.

image

그리고 추가로 General setup 에서 Local version - append to kernel release 항목을 고쳐주면 커널의 정보에서 이름이 추가됩니다.

예를 들어 -custom-bigmem 로 써주면 되지요. (실제 제가 할 때는 -를 앞에 빼먹고 custom-bigmem으로 썼습니다. -가 자동으로 붙는 줄 알았어요…)

image

그리고 exit. 저장하고 나옵니다.

 

5. 컴파일 && deb 패키지 생성

이제 빌드해봅니다.

# make-kpkg clean

# fakeroot make-kpkg  –initrd kernel_image kernel_headers

이렇게 하면 주욱 빌드할 것이고 커널 헤더와 커널 이미지 패키지가 만들어집니다.

 

6. 새로운 커널 설치

만들어진 패키지를 설치해줍니다.

# dpkg -i linux-image-2.6.24.3custom-bigmem_2.6.24.3-custom-bigmem-10.00.Custom_i386.deb 
# dpkg -i linux-headers-2.6.24.3custom-bigmem_2.6.24.3-custom-bigmem-10.00.Custom_i386.deb

 

7. 재부팅

일단 /boot/grub/menu.lst 에 부팅 설정이 제대로 써졌는지 보고, (저의 경우 새 커널로 부팅하도록 우선순위가 자동으로 매겨져서 추가돼 있더군요.)

재부팅

# reboot

 

부팅하고나서 현재 커널이 어떤 건지 확인하려면 uname -a나 /proc/version을 보시면 됩니다.

# uname -a
Linux danwon 2.6.24.3custom-bigmem #1 SMP Tue Aug 26 16:08:04 KST 2008 i686 GNU/Linux

image

nload 콘솔에서 네트웍 부하 보기

화요일, 8월 26th, 2008

nload 라는 프로그램이 있습니다.

image

네트웍 부하를 콘솔에서 볼 수 있습니다.

원격으로 관리할 때 편리하겠네요.

 

관리하는 서버에서 누군가 네트웍을 심하게 쓰는군요. 음. 살펴봐야겠습니다.

configure에서 –host와 –build의 차이

수요일, 8월 20th, 2008

configure 스크립트에서 받는 옵션으로 –host, –build, –target이 있습니다.

만약에 빌드를 x86 리눅스 머신에서 하고 실제 실행은 리눅스이면서 eabi를 쓰고 ARM 플랫폼에서 실행하고 싶다면

./configure –target=arm-none-linux-gnueabi –host=arm-none-linux-gnueabi –build=linux

./configure –target=arm-none-linux-gnueabi –host=arm-none-linux-gnueabi –build=i486-pc-linux-gnu

이런식으로 할 겁니다.

–build : 내가 지금 작업하고 있는 컴파일 시스템 - 그러니까 코딩 작업하고 있는 호스트

–host : 빌드하고 나서 실행파일이 실행될 시스템을 명시합니다. 컴파일 결과물이 돌아갈 환경. 실제 타겟 이름. 예를 들어 arm-none-linux-

–target : (대부분 host와 같은 거이 일반적이고) 크로스 컴파일러를 빌드할 때 등에 쓰는 것으로 빌드된 파일이 실행됐을 때 내놓을 바이너리 포맷입니다.

target을 쓰는 경우는 예를 들어 x86 리눅스에서 ARM 컴파일러를 PowerPC에서 실행시킬 바이너리를 만든다면

./configure –target=arm-linux-gnu –host=powerpc-linux-gnu –build=i686-pc-linux-gnu

정도로 쓰면 됩니다.

영문으로 자세히 설명된 canadian cross http://www.airs.com/ian/configure/configure_6.html

http://kelp.or.kr/korweblog/stories.php?story=04/09/22/9919655

————-

KLDP에서 퍼온 것

http://www.belgeler.org/autobook/autobook-Building-with-a-Cross-Compiler…

즉 Linux에서 빌드를 하는데 만드는 컴파일러가 dos에서 실행되는 컴파일러이고, 이 컴파일러의 출력코드는 mips용이라면
–build : linux
–host : dos
–target : mips
가 됩니다. 이런 경우를 canadian cross라고 하죠. 캐나다에 세 민족이 살아서 그런데나… 물론 이런 canadian cross는 library 때문에 빌드가 상당히 복잡해집니다.

기본적으로는 host, target, build를 모두 적어주어야 합니다. 단, 적어주지 않는 경우 config.guess script에서 나머지를 default로 현재 platform으로 설정합니다.

그래서
canadian cross 인 경우에는 –host, –target을 정확히 적어주어야 하고,
cross인 경우에는 –target 만을 정확히 적어주면 되고,
일반적인 경우에는 아무것도 적어주지 않아도 됩니다.

예약한 시각에 명령어 실행하기 - at

금요일, 8월 15th, 2008

학교가 토요일에 정전된다길래 정전 되기 직전에 리눅스 서버를 꺼줘야겠습니다.

제가 직접 가서 꺼야되는 상황은 만들고 싶지 않기에 예약해서 꺼야겠지요

이럴 때 쓰기 쉬운 명령어, at가 있습니다.

이대로 따라 하면 됩니다.

리눅스에서 컴퓨터 끄기 예약.

지정된 시간에 자동으로 끄려면 at를 사용하면 됩니다.

0. 먼저 시스템 시간을 확인합니다. 시간과 날짜가 맞아야지요.

$ date

2008. 08. 14. (목) 21:38:27 KST

1. 루트로 변경합니다. (끄려면 권한이 있어야 하므로)

daniel@server $su

root@server #

su가 안되는 시스템에서는 sudo su로 사용자를 바꾸실 수 있을 겁니다. 안되면 루트로 로그인하시든지요.

daniel@server $ sudo su

root@server #

2. at으로 시간 입력 & 할 일 입력

root@server # at 8:30am Aug 16

warning: commands will be executed using /bin/sh

at> poweroff (혹시 poweroff가 아니고 다른 명령 – 예를 들어 shutdown –h now – 인지는 알아서 확인)

at> (Ctrl+D입력으로 종료)

job 1 at Thu Aug 16 08:30:00 2008

  • atq로 예약된 명령을 볼 수 있습니다.

root@server # atq

1       Thu Aug 16 08:30:00 2008 a danielsong

  • atrm으로 예약 명령을 취소할 수 있습니다.

root@server # atrm 1

추가 정리하자면,

1. at 명령어로 원하는 시간에 명령을 실행할 수 있다. (명령은 한줄이 아니어도 됨.)

2. 그리고 입력받는  시간 형식은 다양해서 at 4pm + 3 days , at 1am tomorrow 등으로 입력도 가능.

ubuntu에서 firewall 설정

목요일, 8월 14th, 2008

ubuntu linux에는 처음에 기본적으로 firewall을 작동시키지 않습니다.

iptables를 이용한 firewall 셋업은 원래 좀 피곤합니다. 이걸 GUI로 쉽게 해주는 툴이 있으면 좋겠는데요

찾아보면 많아서 뭘 써야할 지 모르는데, 인터넷 검색으로 추천하는 툴을 찾았습니다.

(http://linuxappfinder.com 라는 사이트에서 카테고리별로 브라우즈 할 수 있습니다. 랭크가 나와요)

기본 기능만 원한다면 firestarter를,

좀더 자세한 기능을 쓰려면 Guarddog을,

더 강력한 그리고 복잡한 기능을 쓰려면 fwbuilder를 쓰라는군요

예전에 iptables를 직접 스크립트를 작성해서 써봤지만 이번엔 간단하게 가고 싶어서 firestart를 썼습니다.

http://useopensource.blogspot.com/2007/03/how-to-setup-firewall-in-ubuntu.html 이쪽 링크에 잘 나옵니다.

설치방법은

$ sudo apt-get install firestarter

이렇게 하면 됩니다.

실행은

$ sudo firestarter

하시면 되구요

처음에 간단한 기능만 물어보는 마법사가 뜨고, Next Next로 설정하고 나면


image

이런 모양으로 나옵니다.

Policy 탭에서 열기 원하는 포트와 ip주소를 적어주고, Start Firewall 버튼을 눌러 활성화시키면 됩니다.

image

ps. 참고로 Lock Firewall 버튼은 누르지 마세요. 모든 통신을 끊어버립니다. 원격으로 실행하다가 이걸 누르면 서버 콘솔까지 달려가야 됩니다.

나머지 설명은 여기 링크에서 읽어보세요.

나머지 Guarddog, fwbuilder 도 위 링크에서 읽어보시기 바랍니다.