Работа с Yota под Ubuntu 8.04

Работа с Yota под Ubuntu 8.04

Качаем и ставим зависимости:

http://packages.ubuntu.com/jaunty/i386/libusb-1.0-0-dev/download
http://packages.ubuntu.com/jaunty/i386/libusb-1.0-0/download

Качаем драйвер:

cd ~/
wget http://madwimax.googlecode.com/files/madwimax-0.0.2.tar.gz

Распаковываем:

tar -xvzf madwimax-0.0.2.tar.gz
madwimax-0.0.2/
madwimax-0.0.2/src/
madwimax-0.0.2/src/protocol.c
madwimax-0.0.2/src/protocol.h
madwimax-0.0.2/src/tap_dev.c
madwimax-0.0.2/src/tap_dev.h
madwimax-0.0.2/src/wimax.c
madwimax-0.0.2/src/wimax.h
madwimax-0.0.2/NEWS
madwimax-0.0.2/TODO
madwimax-0.0.2/Makefile
madwimax-0.0.2/README
madwimax-0.0.2/scripts/
madwimax-0.0.2/scripts/udev/
madwimax-0.0.2/scripts/udev/z60_madwimax.rules
madwimax-0.0.2/INSTALL
madwimax-0.0.2/COPYING

Собираем:

cd madwimax-0.0.2
ls
COPYING INSTALL Makefile NEWS README scripts src TODO

make
gcc -c -g -Wall src/protocol.c -o src/protocol.o
gcc -c -g -Wall src/tap_dev.c -o src/tap_dev.o
src/tap_dev.c:213: предупреждение: ‘tap_test_flag’ defined but not used
gcc -c -g -Wall src/wimax.c -o src/wimax.o
gcc -o wimax src/protocol.o src/tap_dev.o src/wimax.o -lusb-1.0

Запускаем:

sudo ./wimax
[sudo] password for ХХХХХ:
Could not find/open device

Подключаем железку и запускаем ещё раз:)

sudo ./wimax
claimed interface
Continuous async read start...
Chip info: cmc730_v2.1
Firmware info: u200_rev1-2.2.50-BK15
MAC: 00:21:d2:1e:62:b1
Allocated tap interface: tap0
Network found.
RSSI: -60 CINR: 18.750000 TX Power: 57344 Frequency: 2525000
BSID: 00:00:15:01:22:c6
State: NEGO Number: 2 Response: 1
RSSI: -59 CINR: 21.000000 TX Power: 65523 Frequency: 2525000
BSID: 00:00:15:01:22:c6
State: NORMAL Number: 3 Response: 2
RSSI: -59 CINR: 21.500000 TX Power: 65524 Frequency: 2525000
BSID: 00:00:15:01:22:c6
State: NORMAL Number: 3 Response: 2
RSSI: -59 CINR: 21.750000 TX Power: 65524 Frequency: 2525000
BSID: 00:00:15:01:22:c6

Теперь в другом терминале запускаем DHCP-Client:

ifconfig

lo Link encap:Локальная петля (Loopback)
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Диапазон:Узел
ВВЕРХ LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:1276 errors:0 dropped:0 overruns:0 frame:0
TX packets:1276 errors:0 dropped:0 overruns:0 carrier:0
коллизии:0 txqueuelen:0
RX bytes:65836 (64.2 KB) TX bytes:65836 (64.2 KB)

tap0 Link encap:Ethernet HWaddr 00:21:d2:1e:62:b1
inet6 addr: fe80::221:d2ff:fe1e:62b1/64 Диапазон:Ссылка
ВВЕРХ BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
коллизии:0 txqueuelen:500
RX bytes:0 (0.0 B) TX bytes:468 (468.0 B)

sudo dhclient tap0
[sudo] password for XXXX:
There is already a pid file /var/run/dhclient.pid with pid 11013
killed old client process, removed PID file
Internet Systems Consortium DHCP Client V3.0.6
Copyright 2004-2007 Internet Systems Consortium.
All rights reserved.
For info, please visit http://www.isc.org/sw/dhcp/

Listening on LPF/tap0/00:21:d2:1e:62:b1
Sending on LPF/tap0/00:21:d2:1e:62:b1
Sending on Socket/fallback
DHCPDISCOVER on tap0 to 255.255.255.255 port 67 interval 5
DHCPOFFER of 94.25.137.241 from 94.25.136.1
DHCPREQUEST of 94.25.137.241 on tap0 to 255.255.255.255 port 67
DHCPACK of 94.25.137.241 from 94.25.136.1
bound to 94.25.137.241 -- renewal in 5071 seconds.

route -n
Таблица маршутизации ядра протокола IP
Destination Gateway Genmask Flags Metric Ref Use Iface
94.25.136.0 0.0.0.0 255.255.254.0 U 0 0 0 tap0
0.0.0.0 94.25.136.1 0.0.0.0 UG 0 0 0 tap0

ping ya.ru
PING ya.ru (213.180.204.8) 56(84) bytes of data.
64 bytes from ya.ru (213.180.204.8): icmp_seq=1 ttl=56 time=124 ms
64 bytes from ya.ru (213.180.204.8): icmp_seq=2 ttl=56 time=575 ms
64 bytes from ya.ru (213.180.204.8): icmp_seq=3 ttl=56 time=100 ms
64 bytes from ya.ru (213.180.204.8): icmp_seq=4 ttl=56 time=105 ms

--- ya.ru ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2998ms


Наслаждаемся ваймаксом:))))))

Огромный респект автору драйвера:
http://community.livejournal.com/yota_ru/126960.html

ПЫ.СЫ.: Выход по Ctrl-C , в том терминале где запущен драйвер.

Клонирование системы (debian)

Для установки того же набора пакетов для Debian на новом сервере:

На исходной системе:
dpkg --get-selections > installed-software.log

На новой системе:
sudo dpkg --set-selections < installed-software.log && apt-get dselect-upgrade

Осталось только скопировать конфигурационные файлы и отредактировать их.

Изменение размера образа XEN DomU

xm shutdown billing1

cd /home/xen
root@node0001:/home/xen# ls
billing1-disk.img

dd if=/dev/zero bs=1024 count=8000000 >> billing1-disk.img
8000000+0 records in
8000000+0 records out
8192000000 bytes (8.2 GB) copied, 153.065 s, 53.5 MB/s

e2fsck -f billing1-disk.img
e2fsck 1.40.8 (13-Mar-2008)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
billing1-disk.img: 48913/1048576 files (13.5% non-contiguous), 1590869/2097152 blocks

resize2fs billing1-disk.img
resize2fs 1.40.8 (13-Mar-2008)
Resizing the filesystem on billing1-disk.img to 4097152 (4k) blocks.
The filesystem on billing1-disk.img is now 4097152 blocks long.

ls -l
total 54905548
-rw-r--r-- 1 root root 16781934592 2008-09-10 11:05 billing1-disk.img

xm create /etc/xen/auto/billing1.cfg
Using config file "/etc/xen/auto/billing1.cfg".
Started domain billing1

xm list
Name ID Mem VCPUs State Time(s)
Domain-0 0 357 4 r----- 44359.2
billing1 109 128 1 r----- 2.4

Взято с:
http://www.tehfear.com/2007/10/08/resize-loop-disk-image/

Установка CUCM на "неправильный сервер". версия 6.0.1

update: Выяснилось, что установка производилась автором на VMWARE... На реальный сервер вероятно не получится.

Установка Cisco UCM на ПК.
версия CUCM 6.0.1-2000.4

Установка CM сервера проходит в два этапа.
1 Этап.
установка самой ОС.
ISO образ загружает RedHat Linux ES 3

2 Этап
следует при первом запуске ОС.
устанавливается CUCM

-------------------------------------------------------------------------------------------------------------------
Cisco по заботилась о безопасности CUCM закрыв доступ к загрузке меню GRUB и к консоле Linux.

Консоль доступна для администратора сервера CUСM в режиме, который предлагает сама Cisco.


Требуется всю процедуру по установки произвести до этапа 2, то есть не дать загрузится LInux серверу в рабочем режиме.


для этого требуется загрузится с любого LIVE CD
(в моем случае использовалась UBUNTU)
1- Загрузка LiveCD
2- смонтировать раздел жеского диска на котором находится корневой диск установленной ранее OS Linux с CUCM

mount /dev/sda1 /mnt/disk

(установка была произведена на диск sda1)

3 - Сделать CHROOT на тот раздел
chroot /mnt/disk /bin/bash

теперь мы находимся в режиме chroot на требуемом нам разделе.

4 - исправление GRUB
vi /etc/grub.conf
разкоментируем строку в конфиге
было
#/dev/sda
стало
/dev/sda

Сохраняем файл.

5 - переинсталируем grub

grub-install /dev/sda

Searching for GRUB installation directory ... found: /boot/grub
Installation finished. No error reported.
This is the contents of the device map /boot/grub/device.map.
Check if this is correct or not. If any of the lines is incorrect,
fix it and re-run the script `grub-install'.

(hd0) /dev/sda

6 - теперь мы готовы перегрузится на предустановленй Linux с CUCM
exit
reboot
-------------------------------------------------------------------------------------------------

Важно чтобы появлось меню GRUB
по ESC остановите счетчик, и входите в редактирвание меню.

Загрузчки GRUB предлагает выбрать два пункта из меню.
выбирети любой

в режиме редактирования меню загрузки требуется загрузится в Single mode
то есть прописать в уже готовом меня ключ "-s"

как только редактирование закончили жмем "b"
для загрузки ОС в режиме SINGLE MODE


если все прошло удачно при загрузке и режим Сингл Моде сработал, то вы попадаете сразу в корневой раздел установленной ОС.


Cisco также по заботилась о безопасности файлов

/etc/passwd
/etc/shadow
/etc/group
/etc/gshadow

Снять эту безопасность можно с помощью команды

chattr -i /etc/passwd
chattr -i /etc/shadow
chattr -i /etc/group
chattr -i /etc/gshadow


или зайдя в директорию

/root/.security/
и запустить скрипт
unminimize.sh

этот скрипт и содержит выше перечисленные команды

теперь мы можем добавлять пользователей, менять пароли.

adduser admin
>OK
passwd admin
>OK
visudo
добавим запись для доступа пользователю admin с режим рута.
admin ALL=(ALL) ALL

после этих манипуляция, вы всегда можете зайти с консоли или по SSH на консоль сервера.

теперь приступим к самому главному.
как научить CUCM понимать что это не простой UNKNOWN HARDWARE
а HP или IBM

INFO - первая инсталяция CUCM производится из файла /etc/rc.local
в нем и обнуриживается вся последовательность установки сервера.


для нас нам важен вот этот файл
/usr/local/bin/vendor/misc/bin/hwdetect

с помощью редактора VI

исправляем некоторые переменные.
---Привожу полный список того что находися в ECHO -

echo "
Machine_Type = $machine_type
Model_Number = $model_number
Serial_Number = $serial_number
Product_Name = ProLiant DL320 G2
BIOS_Version = $bios_version
BIOS_Build_Level = $bios_build_level
BIOS_Date = $bios_date
BIOS_Manufacturer = HP
BIOS_Language =
Number_Of_Enclosures =
Enclosure_Type.0 =
Processor_Slots = $processor_slots
Active_Processors = 1
Processor_Family.0 = $processor_family
Processor_Speed_MHz.0 = 2266
Total_Enabled_Memory_Mb = 2048
ROM_Diagnostics_Build_Level =
"
Это нам позволит сказать инсталятору CUCM о железе HP

далее ищем запись в пункте main

bios_manufacturer=....
ее можно закоментировать и вписать новую
bios_manufacturer="HP"


====================================
сохраняемся.

теперь мы готовы перегрузится и запустить загрузку в штатном режиме. проходя этап 2

reboot


Система стартанула, и используя исправления будет инсталировать CUCM и работать на сервере HP.








Подключение к CUCM софтофона EyeBeam
https://support.counterpath.com/default.asp?W91

P.S. Спасибо Дмитрию В.Гнидченко за этот материал

P.P.S Выяснилось, что установка производилась автором на VMWARE... На реальный сервер вероятно не получится.

XEN и W2K3

Возникла нужда сделать виртуальную машинку с виндой... Дабы не плодить сущностей, решили сделать её под XENом.

Создаём конфиг:

root@node0001:/home# ee /etc/xen/1win2k3.cfg
kernel = "/usr/lib/xen/boot/hvmloader"
builder='hvm'
memory = 128
name = "test-win01"
vcpus=1
pae=0
acpi=0
apic=0
vif = [ 'bridge=xenbr0', 'mac=00:16:3E:a8:73:d2' ]
disk = [ 'tap:aio:/home/xen/node001-win2k3-disk.img,xvda,w', 'phy:/dev/loop0,xvdb:cdrom,r' ]
on_poweroff = 'destroy'
on_reboot = 'restart'
on_crash = 'restart'
device_model = '/usr/lib/xen/bin/qemu-dm'
boot='d'
sdl=0
vnc=1
vncconsole=0
stdvga=0
serial='pty'


Монтируем образ установочного диска:

root@node0001:/etc/xen# losetup /dev/loop0 /home/xen/w2k3r.iso
root@node0001:/etc/xen# losetup -a
/dev/loop0: [0801]:245781 (/home/xen/w2k3r.iso)


Создаём образ диска для Вирт.машины:

root@node0001:/etc/xen# dd if=/dev/zero of=/home/xen/node001-win2k3-disk.img bs=1M count=4096
4096+0 records in
4096+0 records out
4294967296 bytes (4.3 GB) copied, 63.3392 s, 67.8 MB/s


Запускаем:

root@node0001:/etc/xen# xm create /etc/xen/1win2k3.cfg
Using config file "/etc/xen/1win2k3.cfg".
Started domain node001-win2k3


Проверяем на каком порту слушает VNC (встроенный в xen):

root@node0001:/etc/xen# netstat -nlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 20071/qemu-dm


Соединяемся по VNC к dom0 на соотв. порт и "наслаждаемся" установкой Windows ;)

P.S. В /etc/xen/xend-config.sxp надо поменять
(vnc-listen '127.0.0.1') на (vnc-listen '0.0.0.0') , а то по VNC не пустит. Также ходят слухи о плохой производительность IO-операций в WIN под XEN, говорят лечится установкой паравиртуальных драйверов. Подробнее тут:
http://xgu.ru/wiki/Xen/winpvdrivers

Cisco Easy VPN без cryptomap

Возникла необходимость организовать удалённый доступ в сеть конторы, через PPTP и CiscoVPN-Client.
Для чего развернули RADIUS-сервер на базе FreeRadius+Abills и настроили циску.
Конфиг:

!
aaa new-model
!
!
aaa authentication login default local
aaa authentication login user_auth group radius local
aaa authentication ppp default group radius
aaa authorization exec default local none
aaa authorization network default group radius local
aaa authorization network group_author local
aaa accounting delay-start
aaa accounting update periodic 1
aaa accounting network default start-stop group radius
!
aaa server radius dynamic-author
client 192.168.100.242 server-key TESTKEY
auth-type any
!
aaa session-id unique
clock timezone MSK 3
clock summer-time MSD recurring last Sun Mar 2:00 last Sun Oct 2:00
!
vpdn enable
!
vpdn-group 1
! Default PPTP VPDN group
accept-dialin
protocol pptp
virtual-template 1
local name Cisco_VPN_PPTP_server
l2tp tunnel receive-window 1024
ip mtu adjust
!
!
crypto isakmp policy 1
encr 3des
authentication pre-share
group 2
crypto isakmp key ******** address *.*.*.26 no-xauth
crypto isakmp key ******** address *.*.*.137 no-xauth
crypto isakmp invalid-spi-recovery
crypto isakmp keepalive 10 periodic
crypto isakmp xauth timeout 90

!
crypto isakmp client configuration group mobile
key *******
dns 192.168.100.254 *.*.*.18
max-users 250
netmask 255.255.255.0
crypto isakmp profile mobile_users
match identity group mobile
client authentication list user_auth
isakmp authorization list group_author
client configuration address respond
client configuration group mobile
accounting default
virtual-template 2
!
!
crypto ipsec transform-set ESP-3DES-SHA0 esp-3des esp-sha-hmac
crypto ipsec transform-set T2 esp-3des esp-sha-hmac
mode transport
!
crypto ipsec profile P2
set transform-set T2
!
crypto ipsec profile mobile_users_ipsec
set transform-set ESP-3DES-SHA0
set isakmp-profile mobile_users
!
!
crypto map temp local-address Vlan60
crypto map temp client configuration address respond
crypto map temp 1 ipsec-isakmp
description to_Archangelsk
set peer *.*.*.137
set transform-set ESP-3DES-SHA0
match address 101
!
!
interface Loopback10
ip address 192.168.111.1 255.255.255.255
!
interface Tunnel0
ip address 192.168.7.1 255.255.255.0
ip mtu 1250
ip tcp adjust-mss 1100
tunnel source *.*.*.190
tunnel destination *.*.*.26
tunnel protection ipsec profile P2
!
interface GigabitEthernet0/0
description LAN
no ip address
duplex auto
speed auto
!
!
interface GigabitEthernet0/0.40
description Data_LAN
encapsulation dot1Q 40
ip address 192.168.40.1 255.255.255.0
ip helper-address 192.168.100.254
ip wccp web-cache redirect in
ip nat inside
ip virtual-reassembly
!
interface GigabitEthernet0/0.100
description Servers
encapsulation dot1Q 100
ip address 192.168.100.1 255.255.255.0
ip nat inside
ip virtual-reassembly
!
!
interface Virtual-Template1
ip unnumbered Loopback10
ip verify unicast reverse-path
no ip unreachables
no ip proxy-arp
ip nat inside
ip virtual-reassembly
autodetect encapsulation ppp
no snmp trap link-status
no peer default ip address
compress mppc
ppp mtu adaptive
ppp encrypt mppe 128 required
ppp authentication ms-chap-v2
ppp ipcp dns 192.168.100.254 *.*.*.18
ppp ipcp wins 192.168.100.254
!
interface Virtual-Template2 type tunnel
ip unnumbered Loopback10
ip nat inside
ip virtual-reassembly
load-interval 30
tunnel mode ipsec ipv4
tunnel protection ipsec profile mobile_users_ipsec
!
interface Vlan1
no ip address
!
interface Vlan50
description ISP2
ip address *.*.*.190 255.255.255.252
ip access-group From-INTERNET in
ip mtu 1490
ip flow ingress
ip flow egress
ip nat outside
ip virtual-reassembly
ip route-cache flow
!
interface Vlan60
description ISP1
ip address *.*.*.13 255.255.255.248
ip access-group From-INTERNET in
ip flow ingress
ip flow egress
ip nat outside
ip virtual-reassembly
ip route-cache flow
crypto map temp
!
!
ip local pool PPTP_VPN 192.168.111.100 192.168.111.254
!
ip radius source-interface GigabitEthernet0/0.100
!
!
radius-server attribute 44 include-in-access-req
radius-server attribute 32 include-in-access-req
radius-server configure-nas
radius-server host 192.168.100.242 auth-port 1812 acct-port 1813
radius-server timeout 30
radius-server key *********
!


P.S. Есть небольшая проблема - POD на Cisco-VPN клиентах не работает... Х.З. почему... А в остальном всё замечательно.

Еще раз об ID3 тегах в mp3

Перекодировка тегов mp3 в UTF:

$ find -iname '*.mp3' -print0 | xargs -0 mid3iconv -eCP1251 --remove-v1

Взято с:
http://www.ugolnik.info/?p=439

P/S: mid3iconv живёт в пакете python-mutagen.

PPTP в Ubuntu 8.04

В Ubuntu 8.04 перестал работать GUI для pptp-vpn, однако по прежнему можно его использовать через консоль. Я использую для этого следующие скрипты:

/home/user/vpn-on

#!/bin/bash
#vpn-on
#
sudo route add -host x.x.191.13 gw 10.10.32.1
sudo route del default
sudo pon vpn
sleep 10
sudo route add default dev ppp0
echo "VPN is UP !"
sleep 5


/home/user/vpn-off

#!/bin/bash
#vpn-off
#
ifconfig eth0 | grep "RX bytes"
sudo poff vpn
sleep 10
sudo route del -host x.x.191.13 gw 10.10.32.1
sudo route add default gw 10.10.32.1
echo "VPN is DOWN !"
sleep 2


/etc/ppp/peers/vpn

maxfail 0
lcp-echo-interval 60
lcp-echo-failure 4
pty "pptp x.x.191.13 --nolaunchpppd"
name testuser1
remotename Cisco_VPN_PPTP_server
usepeerdns
+chap
file /etc/ppp/options.pptp
ipparam vpn


/etc/ppp/options.pptp

###############################################################################
# $Id: options.pptp,v 1.1 2005/02/18 01:40:23 quozl Exp $
#
# Sample PPTP PPP options file /etc/ppp/options.pptp
# Options used by PPP when a connection is made by a PPTP client.
# This file can be referred to by an /etc/ppp/peers file for the tunnel.
# Changes are effective on the next connection. See "man pppd".
#
# You are expected to change this file to suit your system. As
# packaged, it requires PPP 2.4.2 or later from http://ppp.samba.org/
# and the kernel MPPE module available from the CVS repository also on
# http://ppp.samba.org/, which is packaged for DKMS as kernel_ppp_mppe.
###############################################################################

# Lock the port
lock

# Authentication
# We don't need the tunnel server to authenticate itself
noauth

# We won't do EAP, CHAP, or MSCHAP, but we will accept MSCHAP-V2
refuse-eap
refuse-chap
refuse-mschap

# Compression
# Turn off compression protocols we know won't be used
nobsdcomp
nodeflate

persist
# Encryption
# (There have been multiple versions of PPP with encryption support,
# choose with of the following sections you will use. Note that MPPE
# requires the use of MSCHAP-V2 during authentication)

# http://ppp.samba.org/ the PPP project version of PPP by Paul Mackarras
# ppp-2.4.2 or later with MPPE only, kernel module ppp_mppe.o
# {{{
# Require MPPE 128-bit encryption
require-mppe-128
# }}}

# http://polbox.com/h/hs001/ fork from PPP project by Jan Dubiec
# ppp-2.4.2 or later with MPPE and MPPC, kernel module ppp_mppe_mppc.o
# {{{
# Require MPPE 128-bit encryption
#mppe required,stateless
# }}}


/etc/ppp/chap-secrets

# Secrets for authentication using CHAP
# client server secret IP addresses

testuser1 * 1234 *


/etc/ppp/resolv.conf

nameserver 192.168.100.254
nameserver x.x.191.18


P.S. для того, чтобы pptp работал в Ubuntu 8.04 нужно поставить пакет pptp-linux.

sudo apt-get install pptp-linux

IE под Linux

К несчастью, все же приходится иногда пользоваться этим поделием - IE, т.к. некоторые сайты работают только под ним... В частности, те, что требуют ActiveX или Adobe SVG. Самый простой путь получить IE под Linux:

wget http://www.tatanka.com.br/ies4linux/downloads/ies4linux-latest.tar.gz
tar zxvf ies4linux-latest.tar.gz
cd ies4linux-*
./ies4linux

Взято c :
http://www.tatanka.com.br/ies4linux/page/Main_Page

Установка XEN на Debian Etch (4.0)

Обновляем списки пакетов:

apt-get update

Обновляемся:

apt-get upgrade

Ставим необходимые пакеты из репозитория (для xen и дополнительно mc и ee):

apt-get install xen-linux-system-2.6.18-6-xen-686 xen-linux-system-2.6.18-6-xen-vserver-686 xen-hypervisor-3.0.3-1-i386 xen-tools xen-utils-3.0.3-1 xen-ioemu-3.0.3-1 bridge-utils ee mc locales

Меняем локаль по умолчанию на UTF-8:

dpkg-reconfigure locales

Generating locales (this might take a while)...
en_US.UTF-8... done
Generation complete.

Перелогиниваемся и проверяем локаль:

test-vm:~# locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

Теперь перезагружаемся с новым ядром (с поддержкой виртуализации).
Убедимся в наличии интерфейса xenbr:

xen1:/home/mavrichev# ifconfig
eth0 Link encap:Ethernet HWaddr 00:14:5E:2E:28:2C
inet addr:192.168.100.240 Bcast:192.168.100.255 Mask:255.255.255.0
inet6 addr: fe80::214:5eff:fe2e:282c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3301 errors:0 dropped:0 overruns:0 frame:0
TX packets:15 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:2443894 (2.3 MiB) TX bytes:1550 (1.5 KiB)

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:8 errors:0 dropped:0 overruns:0 frame:0
TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:560 (560.0 b) TX bytes:560 (560.0 b)

peth0 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF
inet6 addr: fe80::fcff:ffff:feff:ffff/64 Scope:Link
UP BROADCAST RUNNING NOARP MTU:1500 Metric:1
RX packets:2699 errors:0 dropped:0 overruns:0 frame:0
TX packets:13 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1969060 (1.8 MiB) TX bytes:1416 (1.3 KiB)
Interrupt:18

vif0.0 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF
inet6 addr: fe80::fcff:ffff:feff:ffff/64 Scope:Link
UP BROADCAST RUNNING NOARP MTU:1500 Metric:1
RX packets:15 errors:0 dropped:0 overruns:0 frame:0
TX packets:3301 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1550 (1.5 KiB) TX bytes:2443894 (2.3 MiB)

xenbr0 Link encap:Ethernet HWaddr FE:FF:FF:FF:FF:FF
inet6 addr: fe80::200:ff:fe00:0/64 Scope:Link
UP BROADCAST RUNNING NOARP MTU:1500 Metric:1
RX packets:15 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:12376 (12.0 KiB) TX bytes:0 (0.0 b)

Готовим шаблон конфига для виртуальных машин и создаём каталог для них:

mkdir /home/xen


ee /etc/xen-tools/xen-tools.conf


dir = /home/xen
debootstrap = 1
gateway = 192.168.100.1
netmask = 255.255.255.0
kernel = /boot/vmlinuz-2.6.18-6-xen-vserver-686
initrd = /boot/initrd.img-2.6.18-6-xen-vserver-686
mirror = http://ftp.ru.debian.org/debian/

Создаём первую вирт.машину:

xen-create-image --debootstrap --hostname test1 --ip=192.168.100.243 --dist=etch

После успешной установки увидим сообщение:

Creating Xen configuration file
Done
All done

При необходимости ,редактируем конф.файл вирт.машины:

ee /etc/xen/test1.cfg


#
# Configuration file for the Xen instance test1, created on
# Fri Apr 18 09:56:07 2008.
#
#
# Kernel + memory size
#
kernel = '/boot/vmlinuz-2.6.18-6-xen-vserver-686'
ramdisk = '/boot/initrd.img-2.6.18-6-xen-vserver-686'
memory = '256'
#
# Disk device(s).
#
root = '/dev/sda1 ro'
disk = [ 'file:/home/xen/domains/test1/disk.img,sda1,w', 'file:/home/xen/domains/test1/swap.img,sda2,w' ]
#
# Hostname
#
name = 'test1'
#
# Networking
#
vif = [ 'mac=00:16:3E:2A:E3:89' ]
#
# Behaviour
#
on_poweroff = 'destroy'
on_reboot = 'restart'
on_crash = 'restart'

Как показала практика, MAC-адрес лучше задать в конфигурации статически, до первого запуска вирт.машины. В противном случае, если MAC не задан, сервер XEN при каждом отключении Вирт.машины будет увеличивать номер интерфейса (eth0->eth1->eth2...), что не приемлемо.

После этого, запускаем созданную ВМ:

xm create -c /etc/xen/test1.cfg


Using config file "/etc/xen/test1.cfg".
Started domain proxy1
Linux version 2.6.18-6-xen-vserver-686 (Debian 2.6.18.dfsg.1-18etch1) (waldi@debian.org) (gcc version 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)) #1 SMP Sun Feb 10 22:52:33 UTC 2008
BIOS-provided physical RAM map:
Xen: 0000000000000000 - 0000000010800000 (usable)
0MB HIGHMEM available.
264MB LOWMEM available.
ACPI in unprivileged domain disabled
Built 1 zonelists. Total pages: 67584
Kernel command line: root=/dev/sda1 ro
Enabling fast FPU save and restore... done.
Enabling unmasked SIMD FPU exception support... done.
Initializing CPU#0
PID hash table entries: 2048 (order: 11, 8192 bytes)
Xen reported: 1666.784 MHz processor.
Dentry cache hash table entries: 65536 (order: 6, 262144 bytes)
Inode-cache hash table entries: 32768 (order: 5, 131072 bytes)
Software IO TLB disabled
vmalloc area: d1000000-f51fe000, maxmem 2d7fe000
Memory: 245180k/270336k available (1623k kernel code, 16608k reserved, 593k data, 148k init, 0k highmem)
Checking if this processor honours the WP bit even in supervisor mode... Ok.
Calibrating delay using timer specific routine.. 4168.85 BogoMIPS (lpj=8337707)
Security Framework v1.0.0 initialized
SELinux: Disabled at boot.
Capability LSM initialized
Mount-cache hash table entries: 512
CPU: L1 I cache: 32K, L1 D cache: 32K
CPU: L2 cache: 2048K
Checking 'hlt' instruction... OK.
SMP alternatives: switching to UP code
Freeing SMP alternatives: 16k freed
Brought up 1 CPUs
migration_cost=0
checking if image is initramfs... it is
Freeing initrd memory: 10472k freed
Grant table initialized
NET: Registered protocol family 16
Brought up 1 CPUs
PCI: setting up Xen PCI frontend stub
ACPI: Interpreter disabled.
Linux Plug and Play Support v0.97 (c) Adam Belay
pnp: PnP ACPI: disabled
xen_mem: Initialising balloon driver.
PCI: System does not support PCI
PCI: System does not support PCI
NET: Registered protocol family 2
IP route cache hash table entries: 4096 (order: 2, 16384 bytes)
TCP established hash table entries: 16384 (order: 5, 131072 bytes)
TCP bind hash table entries: 8192 (order: 4, 65536 bytes)
TCP: Hash tables configured (established 16384 bind 8192)
TCP reno registered
audit: initializing netlink socket (disabled)
audit(1208525483.574:1): initialized
VFS: Disk quotas dquot_6.5.1
Dquot-cache hash table entries: 1024 (order 0, 4096 bytes)
Initializing Cryptographic API
io scheduler noop registered
io scheduler anticipatory registered
io scheduler deadline registered
io scheduler cfq registered (default)
RAMDISK driver initialized: 16 RAM disks of 8192K size 1024 blocksize
Xen virtual console successfully installed as tty1
Event-channel device installed.
netfront: Initialising virtual ethernet driver.
PNP: No PS/2 controller found. Probing ports directly.
i8042.c: No controller found.
mice: PS/2 mouse device common for all mice
TCP bic registered
NET: Registered protocol family 1
NET: Registered protocol family 17
NET: Registered protocol family 8
NET: Registered protocol family 20
Using IPI No-Shortcut mode
Registering block device major 8
netfront: device eth0 has flipping receive path.
Freeing unused kernel memory: 148k freed
Loading, please wait...
Begin: Loading essential drivers... ...
Done.
Begin: Running /scripts/init-premount ...
FATAL: Error inserting fan (/lib/modules/2.6.18-6-xen-vserver-686/kernel/drivers/acpi/fan.ko): No such device
FATAL: Error inserting thermal (/lib/modules/2.6.18-6-xen-vserver-686/kernel/drivers/acpi/thermal.ko): No such device
Done.
Begin: Mounting root file system... ...
Begin: Running /scripts/local-top ...
Done.
Begin: Running /scripts/local-premount ...
Done.
kjournald starting. Commit interval 5 seconds
EXT3-fs: mounted filesystem with ordered data mode.
Begin: Running /scripts/local-bottom ...
Done.
Done.
Begin: Running /scripts/init-bottom ...
Done.
Serial: 8250/16550 driver $Revision: 1.90 $ 4 ports, IRQ sharing enabled
INIT: version 2.86 booting
* Mount point '/dev/shm' does not exist. Skipping mount.
Activating swap...Adding 262136k swap on /dev/sda2. Priority:-1 extents:1 across:262136k
done.
Checking root file system...fsck 1.40-WIP (14-Nov-2006)
/dev/sda1: clean, 19280/1048576 files, 144102/2097152 blocks
done.
EXT3 FS on sda1, internal journal
Setting the system clock..
Cleaning up ifupdown....
Loading kernel modules...done.
Loading device-mapper supportdevice-mapper: ioctl: 4.7.0-ioctl (2006-06-24) initialised: dm-devel@redhat.com
.
Checking file systems...fsck 1.40-WIP (14-Nov-2006)
done.
Setting kernel variables...done.
Mounting local filesystems...done.
Activating swapfile swap...done.
Setting up networking....
Configuring network interfaces...done.
INIT: Entering runlevel: 2
Starting system log daemon: syslogd.
Starting kernel log daemon: klogd.
* Not starting internet superserver: no services enabled.
Starting OpenBSD Secure Shell server: sshdNET: Registered protocol family 10
lo: Disabled Privacy Extensions
IPv6 over IPv4 tunneling driver
.
Starting periodic command scheduler: crond.

Debian GNU/Linux 4.0 test1 tty1

test1 login: root
Linux test1 2.6.18-6-xen-vserver-686 #1 SMP Sun Feb 10 22:52:33 UTC 2008 i686

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
test1:~#

Всё, на этом закончили. Несколько команд для управления ВМ:

sm list
xm console test1
xm restart test1
xm pause test1
xm unpause test1

Также желательно сконфигурировать локаль внутри ВМ, аналогично вышеописанному.

Дополнение:
Через некоторое время на одной из виртуалок domU проявилась проблема:

May 14 19:45:51 mx2 kernel: Buffer I/O error on device sda1, logical block 1844844
May 14 19:45:51 mx2 kernel: lost page write due to I/O error on sda1

Удалось решить обновлением XEN на версию 3.2.1 из backports:

cat /etc/apt/sources.list
#
#
deb http://ftp.us.debian.org/debian/ etch main
deb-src http://ftp.us.debian.org/debian/ etch main
deb http://security.debian.org/ etch/updates main contrib
deb-src http://security.debian.org/ etch/updates main contrib
#For XEN 3.2.1
deb http://www.backports.org/debian/ etch-backports main contrib non-free


dpkg -l | grep xen
ii dtc-xen 0.3.18-1 SOAP daemon and scripts to allow control pan
ii libc6-xen 2.3.6.ds1-13etch5 GNU C Library: Shared libraries [Xen version
ii libxenstore3.0 3.2.0-3~bpo4+2 Xenstore communications library for Xen
ii linux-image-2.6.18-6-xen-686 2.6.18.dfsg.1-18etch4 Linux 2.6.18 image on i686
ii linux-image-2.6.18-6-xen-vserver-686 2.6.18.dfsg.1-18etch4 Linux 2.6.18 image on i686
ii linux-modules-2.6.18-6-xen-686 2.6.18.dfsg.1-18etch4 Linux 2.6.18 modules on i686
ii linux-modules-2.6.18-6-xen-vserver-686 2.6.18.dfsg.1-18etch4 Linux 2.6.18 modules on i686
rc xen-hypervisor-3.0.3-1-i386 3.0.3-0-4 The Xen Hypervisor on i386
rc xen-hypervisor-3.0.3-1-i386-pae 3.0.3-0-4 The Xen Hypervisor on i386 with pae
ii xen-hypervisor-3.2-1-i386 3.2.0-3~bpo4+2 The Xen Hypervisor on i386
ii xen-tools 3.9-2~bpo40+1 Tools to manage Debian XEN virtual servers
ii xen-utils-3.2-1 3.2.0-3~bpo4+2 XEN administrative tools
ii xen-utils-common 3.2.0-1~bpo4+1 XEN administrative tools - common files
ii xenstore-utils 3.2.0-3~bpo4+2 Xenstore utilities for Xen

Установка из backports: http://www.backports.org/dokuwiki/doku.php?id=instructions

Шпаргалка по Linux

Просмотр файлов без комментариев и пустых строк:

cat squid.conf |grep -v "#"|grep -v "^$"

Или например , так:

cat squid.conf | grep -v "#" | sed '/./,/^$/!d'

Как подружить Cisco и Squid по wccp

Предупреждение: Любые сведения представленные ниже, предоставляются "как есть" без какой-либо поддержки или гарантий.

На написание этой статьи подвигло изучение этого ресурса и обобщение полученного опыта.

Задача: обеспечить прозрачное проксирование http траффика. Используется маршрутизатор Cisco2821 и Debian Etch (4.0).

Схема сети:



Ставим squid из репозитория:

sudo apt-get install squid


Ставим iproute из репозитория:

sudo apt-get install iproute


После того, как все успешно поставилось, редактируем конфигурационный файл /etc/squid/squid.conf:

sudo nano /etc/squid/squid.conf


Меняем значения по умолчанию:

http_port 192.168.100.243:3128 transparent
icp_port 0
hierarchy_stoplist cgi-bin ?
acl QUERY urlpath_regex cgi-bin \?
cache deny QUERY
acl apache rep_header Server ^Apache
broken_vary_encoding allow apache
cache_mem 100 MB
cache_swap_low 90
cache_swap_high 95
maximum_object_size 50 MB
maximum_object_size_in_memory 50 KB
cache_replacement_policy heap LFUDA
cache_dir aufs /var/spool/squid 6000 16 256
access_log /var/log/squid/access.log squid
dns_nameservers *.*.*.*
*.*.*.*
hosts_file /etc/hosts
refresh_pattern ^ftp: 1440 20% 10080
refresh_pattern ^gopher: 1440 0% 1440
refresh_pattern . 0 20% 4320
quick_abort_min 0 KB
quick_abort_max 0 KB
half_closed_clients off
acl all src 0.0.0.0/0.0.0.0
acl manager proto cache_object
acl localhost src 127.0.0.1/255.255.255.255
acl to_localhost dst 127.0.0.0/8
acl purge method PURGE
acl CONNECT method CONNECT
http_access allow manager localhost
http_access deny manager
http_access allow purge localhost
http_access deny purge
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost
acl our_networks src 192.168.40.0/24
http_access allow our_networks
http_access deny all
http_reply_access allow all
icp_access allow all
cache_mgr admin@example.com
cache_effective_group proxy
memory_pools off
log_icp_queries off
cachemgr_passwd secret12345wdsfs all
client_db off
buffered_logs on
wccp2_router 192.168.100.1
wccp_version 4
wccp2_forwarding_method 1
wccp2_return_method 1
wccp2_service standard 0 password=******
wccp_address 192.168.100.243
coredump_dir /var/spool/squid




Редактируем /etc/network/interfaces:

sudo nano /etc/network/interfaces

Добавляем в /etc/network/interfaces запуск скриптов для создания GRE тоннеля для WCCP:

auto eth0
iface eth0 inet static
address 192.168.100.253
netmask 255.255.255.0
gateway 192.168.100.1

post-up /etc/network/wccp.up
pre-down /etc/network/wccp.down


Создаем эти скрипты:

Создаём /etc/network/wccp.up:

sudo nano /etc/network/wccp.up


#!/bin/bash
iptunnel add gre1 mode gre remote 192.168.100.1 local 192.168.100.253 dev eth0
ifconfig gre1 127.0.0.2 up
iptables -t nat -I PREROUTING -i gre1 -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.100.253:3128
#end

Создаём /etc/network/wccp.down:

sudo nano /etc/network/wccp.down


#!/bin/bash
iptables -t nat -F
iptunnel del gre1
#end

Рестартуем сеть:

sudo /etc/init.d/networking restart

Рестартуем squd:

sudo /etc/init.d/squid restart

Все, на этом с конфигурацией Squid закончили.

Настраиваем роутер Cisco (приведена только часть конфига, относящаяся к WCCP):

!
ip wccp version 2
ip wccp web-cache redirect-list REDIRECT_HTTP password TESTPASS
!
!
interface Vlan60
description To-INTERNET
ip address х.х.х.13 255.255.255.248
ip nat outside
ip virtual-reassembly
!
interface GigabitEthernet0/0.40
description Clients_LAN
encapsulation dot1Q 40
ip address 192.168.40.1 255.255.255.0
ip helper-address 192.168.100.254
ip wccp web-cache redirect in
ip nat inside
ip virtual-reassembly
!
interface GigabitEthernet0/0.100
description Servers_LAN
encapsulation dot1Q 100
ip address 192.168.100.1 255.255.255.0
ip nat inside
ip virtual-reassembly
!
ip access-list extended REDIRECT_HTTP
deny tcp 192.168.40.0 0.0.0.255 192.168.100.0 0.0.0.255 eq www
permit tcp 192.168.40.0 0.0.0.255 any eq www
!


Все, с этого момента www траффик из локалки должен перенаправляться на Squid.


Проверяем , всё ли работает:

c2821#sh ip wccp web-cache detail
WCCP Client information:
WCCP Client ID: 192.168.100.253
Protocol Version: 2.0
State: Usable
Initial Hash Info: 00000000000000000000000000000000
00000000000000000000000000000000
Assigned Hash Info: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
Hash Allotment: 256 (100.00%)
Packets s/w Redirected: 1524622
Connect Time: 1d02h
Bypassed Packets
Process: 0
Fast: 0
CEF: 0
Errors: 0


c2821#sh ip wccp
Global WCCP information:
Router information:
Router Identifier: 192.168.100.1
Protocol Version: 2.0

Service Identifier: web-cache
Number of Service Group Clients: 1
Number of Service Group Routers: 1
Total Packets s/w Redirected: 1568775
Process: 30
Fast: 0
CEF: 1568745
Service mode: Open
Service access-list: -none-
Total Packets Dropped Closed: 0
Redirect access-list: REDIRECT_HTTP
Total Packets Denied Redirect: 336896
Total Packets Unassigned: 1068
Group access-list: -none-
Total Messages Denied to Group: 0
Total Authentication failures: 13
Total Bypassed Packets Received: 0


mx2:~# tail -f /var/log/squid/access.log
1207822507.107 169 192.168.40.63 TCP_MISS/200 403 GET http://counter.yadro.ru/hit;HeadHunter? - DIRECT/88.212.196.78 image/gif
1207822507.210 48 192.168.40.63 TCP_MISS/301 524 GET http://hh.ru/images/dot.gif - DIRECT/77.95.131.6 text/html
1207822507.292 133 192.168.40.63 TCP_MISS/200 15436 GET http://hh.ru/poster/file/735976.gif - DIRECT/77.95.131.6 image/gif