Linux: How to get an external IP address from the command line
curl smart-ip.net/myip
or
dig +short myip.opendns.com @resolver1.opendns.com
or
#!/bin/bash
MYIP=$(wget -O - -q icanhazip.com);
echo $MYIP;
curl smart-ip.net/myip
or
dig +short myip.opendns.com @resolver1.opendns.com
or
#!/bin/bash
MYIP=$(wget -O - -q icanhazip.com);
echo $MYIP;
Domain is : domain.local
windows 2008R2 hostname : srv-dc-01
omv hostname : omv
Openmediavault has a DHCP assigned IP address. You should check its hostname and name resolution
omv:/# host domain.local
domain.local has address 192.168.0.10
omv:/# hostname -f
omv.domain.local
The LAB environment runs ESXi : time is synced on each VM boot and is sufficient for testing purpose. In production environment use VMware Tools and time sync agains the ESXi host or use NTP.
apt-get update
apt-get install krb5-user krb5-clients libpam-krb5 winbind libnss-winbind
You will asked for kerberos default domain : DOMAIN.LOCAL
Runs out of the box with default configuration. However you may edit /etc/krb5.conf as the following
[libdefaults]
default_realm = DOMAIN.LOCAL
ticket_lifetime = 600
dns_lookup_realm = yes
dns_lookup_kdc = yes
renew_lifetime = 7d
; allow_weak_crypto = true
# The following krb5.conf variables are only for MIT Kerberos.
; krb4_config = /etc/krb.conf
; krb4_realms = /etc/krb.realms
; kdc_timesync = 1
; ccache_type = 4
; forwardable = true
; proxiable = true
# The following encryption type specification will be used by MIT Kerberos
# if uncommented. In general, the defaults in the MIT Kerberos code are
# correct and overriding these specifications only serves to disable new
# encryption types as they are added, creating interoperability problems.
#
# Thie only time when you might need to uncomment these lines and change
# the enctypes is if you have local software that will break on ticket
# caches containing ticket encryption types it doesn't know about (such as
# old versions of Sun Java).
# Pour Windows Server 2008 R2 (seems not required)
; default_tgs_enctypes = aes256-cts-hmac-sha1-96 rc4-hmac des-cbc-crc des-cbc-md5
; default_tkt_enctypes = aes256-cts-hmac-sha1-96 rc4-hmac des-cbc-crc des-cbc-md5
; permitted_enctypes = aes256-cts-hmac-sha1-96 rc4-hmac des-cbc-crc des-cbc-md5
# Pour Windows Server 2003 (not tested agains windows 2003 server yet, and this server is deprecated)
; default_tgs_enctypes = rc4-hmac des-cbc-crc des-cbc-md5
; default_tkt_enctypes = rc4-hmac des-cbc-crc des-cbc-md5
; permitted_enctypes = rc4-hmac des-cbc-crc des-cbc-md5
[kdc]
profile = /etc/krb5kdc/kdc.conf
[logging]
kdc = FILE:/var/log/krb5kdc.log
admin_server = FILE:/var/log/kadmin.log
default = FILE:/var/log/krb5lib.log
kinit -V administrator (at) DOMAIN.LOCAL
Give administrator password
Test you got a ticket: klist
(Sample-)Output:
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: administrator (at) DOMAIN.LOCAL
Valid starting Expires Service principal
01/28/13 13:28:58 01/28/13 13:38:58 krbtgt/DOMAIN.LOCAL (at) DOMAIN.LOCAL
Destroy all tickets (and check with klist): kdestroy
In OMV webGUI :
enable SAMBA
set Workgroup : DOMAIN
tick “Enable user home directories”. You may also tick “Set browseable”.
add extra options :
password server = *
realm = DOMAIN.LOCAL
security = ads
allow trusted domains = no
idmap config * : range = 9400-59999
winbind use default domain = true
winbind offline logon = false
winbind enum users = yes
winbind enum groups = yes
winbind separator = /
winbind nested groups = yes
;winbind normalize names = yes
winbind refresh tickets = yes
template shell = /bin/bash
template homedir = /home/%U
# Performance improvements
socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192
client ntlmv2 auth = yes
client use spnego = yes
Test samba configuration: testparm
If you wish to view your AD users and groups in OMV webinterface include UIDs and GIDs into non-system users and groups in /etc/login.defs. Find UID_MAX and change UID_MAX and GID_MAX as the following
UID_MAX 60000
GID_MAX 60000
Editing AD users and groups using the OMV webinterface will fail because they are not stored in /etc/passwd and /etc/group.
Argument createcomputer allows you to create the computer’s account in an organisational unit (OU) and is not required.
omv:/# net ads join -U administrator createcomputer=servers/linux
Enter administrator's password:
Using short domain name -- DOMAIN
Joined 'OMV' to realm 'domain.local'
edit /etc/nsswitch.conf
passwd: compat winbind
shadow: compat
group: compat winbind
edit /etc/nsswitch.conf
passwd: compat winbind
shadow: compat
group: compat winbind
ldconfig
getent passwd (you get local and AD users lists)
getent group (you get local and AD groups lists)
create the file /usr/share/pam-configs/my_mkhomedir with the following content
Name: Activate mkhomedir
Default: yes
Priority: 900
Session-Type: Additional
Session:
required pam_mkhomedir.so umask=0077 skel=/etc/skel
umask argument for mkhomedir didn’t worked for me. pam_umask.so seems be a better option. Create the file /usr/share/pam-configs/umask with the following
Name: Activate umask
Default: yes
Priority: 800
Session-Type: Additional
Session:
optional pam_umask.so umask=0077
In SMB/CIFS, extra confguration the special variable %D is used to distinguish domain users from OMV’s local users. A folder will becreated upon first domain user connexion. However the folder will not allow domain users to traverse the folder and access their home directory. This need a fix. Create the folder where template homedir expects to find it, and adjust the owners and permissions. If your active directory contains a white space, ensure to escape it with a backslash.
mkdir /home/DOMAIN
chmod 0755 /home/DOMAIN
chown root:domain\ users DOMAIN
In OMV webGUI enable SSH, disable root login (prefer su and sudo) and add this in Extra Options :
AllowGroups root ssh "domain users"
Please check “domain users is enclosed by double quotes and check this is the group name available in windows 2008 R2 (I’m french and I’m using a french windows 2008R2 : groups and users names are localized)
don’t prefix username with domain. (eg: not DOMAIN.LOCAL/administrator; use administrator only)
Собственно, хочется просто и доступно рассказать про такую замечательную вещь как Logical Volume Management или Управление Логическими Томами.
Поскольку уже давно пользуюсь LVM-ом, расскажу что он значит именно для меня, не подглядывая в мануалы и не выдёргивая цитаты из wiki, своими словами, чтобы было понятно именно тем кто ничего о нем не знает. Постараюсь сразу не рассказывать о всяческих «продвинутых» функциях типа страйпов, снапшотов и т.п.
LVM — это дополнительный слой абстракции от железа, позволяющий собрать кучи разнородных дисков в один, и затем снова разбить этот один именно так как нам хочется.
есть 3 уровня абстракции:
допустим у нас в компе есть жёсткий диск на 40Гб и нам удалось наскрести немного денег и наконец-то купить себе ТЕРАБАЙТНИК! :))) Система уже стоит и работает, и первый диск разбит одним разделом (/dev/sda1 как / ), второй — самый большой, который мы только подключили — вообще не разбит /dev/sdb…
Предлагаю немножко разгрузить корневой диск, а заодно ускорить (новый диск работает быстрее старого) и «обезопасить» систему с помощью lvm.
Можно делать на втором диске разделы и добавлять их в группы томов (если нам нужно несколько групп томов),
а можно вообще не делать на диске разделы и всё устройство сделать физическим разделом (PV)
[email protected]:~# pvcreate /dev/sdb
Physical volume “/dev/sdb” successfully created
Создаём группу томов с говорящим названием, например по имени машины «ws», чтобы когда мы перетащим данный диск на другую машину небыло конфликтов с именами групп томов:
[email protected]:~# vgcreate ws /dev/sdb
Volume group «vg0» successfully created
желательно внести с корневого раздела такие папки как /usr /var /tmp /home, чтобы не дефрагментировать лишний раз корневой раздел и ни в коем случае его не переполнить, поэтому создаём разделы:
[email protected]:~# lvcreate -n usr -L10G ws # здесь мы создаём раздел с именем «usr», размером 10Gb
Logical volume «usr» created
по аналогии делаем то же для /var, /tmp, /home:
[email protected]:~# lvcreate -n var -L10G ws
[email protected]:~# lvcreate -n tmp -L2G ws
[email protected]:~# lvcreate -n home -L500G ws
у нас ещё осталось немного свободного места в группе томов (например для будущего раздела под бэкап)
посмотреть сколько именно можно командой:
[email protected]:~# vgdisplay
информацию по созданным логическим томам
[email protected]:~# lvdisplay
информацию по физическим томам
[email protected]:~# pvdisplay
разделы что мы создали появятся в папке /dev/[имя_vg]/, точнее там будут ссылки на файлы,
lrwxrwxrwx 1 root root 22 2009-08-10 18:35 swap -> /dev/mapper/ws-swap
lrwxrwxrwx 1 root root 21 2009-08-10 18:35 tmp -> /dev/mapper/ws-tmp
lrwxrwxrwx 1 root root 21 2009-08-10 18:35 usr -> /dev/mapper/ws-usr
lrwxrwxrwx 1 root root 21 2009-08-10 18:35 var -> /dev/mapper/ws-var
и т.д…
дальше lvm уже почти кончается… форматируем наши разделы в любимые файловые системы:
[email protected]:~# mkfs.ext2 -L tmp /dev/ws/tmp
[email protected]:~# mkfs.ext4 -L usr /dev/ws/usr
[email protected]:~# mkfs.ext4 -L var /dev/ws/var
[email protected]:~# mkfs.ext4 -L home /dev/ws/home
кстати, не плохо было бы сделать раздел подкачки:
[email protected]:~# lvcreate -n swap -L2G ws
[email protected]:~# mkswap -L swap /dev/ws/swap
[email protected]:~# swapon /dev/ws/swap
создаём папку и подключая по очереди новообразовавшиеся тома, копируем в них нужное содержимое:
[email protected]:~# mkdir /mnt/target
[email protected]:~# mount /dev/ws/home /mnt/target
копируем туда всё из папки /home своим любимым файловым менеджером (с сохранением прав доступа), например так ;):
[email protected]:~# cp -a /home/* /mnt/target/
[email protected]:~# umount /mnt/target/
кстати, для папки temp необходимо только поправить права, копировать туда что-либо необязательно:
[email protected]:~# mount /dev/ws/tmp /mnt/target && chmod -R a+rwx /mnt/target && umount /mnt/target/
добавляем нужные строчки в /etc/fstab, например такие:
/dev/mapper/ws-home /home ext4 relatime 0 2
/dev/mapper/ws-tmp /tmp ext2 noatime 0 2
/dev/mapper/ws-swap none swap sw 0 0
и перезагружаемся… (продвинутые господа могут обойтись без перезагрузки ;))
На вкусное, хочу предложить более продвинутую штуку:
допустим у нас есть система с разделом на LVM, а жёсткий диск начал сбоить, тогда мы можем без перезагрузки переместить всю систему на другой жёсткий диск/раздел:
[email protected]:~# pvcreate /dev/sda1 # наш эмулятор сбойного диска
Physical volume “/dev/sda1” successfully created
[email protected]:~# pvcreate /dev/sdb1 # наш эмулятор спасательного диска
Physical volume “/dev/sdb1” successfully created
[email protected]:~# vgcreate vg0 /dev/sda1 # создаю группу томов vg0
Volume group «vg0» successfully created
[email protected]:~# lvcreate -n test -L10G vg0 #создаю раздел для «важной» инфы
Logical volume «test» created
[email protected]:~# mkfs.ext2 /dev/vg0/test # создаю файловую систему на разделе
[email protected]:~# mount /dev/mapper/vg0-test /mnt/tmp/ #монтирую раздел
… # заполняю его информацией, открываю на нем несколько файлов и т.п.
[email protected]:~# vgextend vg0 /dev/sdb1 # расширяю нашу групу томов на «спасательный» диск
Volume group «vg0» successfully extended
[email protected]:~# pvmove /dev/sda1 /dev/sdb1 #передвигаю содержимое с «умирающего» диска на «спасательный»
/dev/sda1: Moved: 0.9%
/dev/sda1: Moved: 1.8%
…
/dev/sda1: Moved: 99.7%
/dev/sda1: Moved: 100.0%
[email protected]:~# vgreduce vg0 /dev/sda1 # убираю «умирающий» диск из группы томов.
Removed “/dev/sda1” from volume group «vg0»
Итого:
Я создал логический раздел, отформатировал его, примонтировал и заполнил нужными данными, затем переместил его с одного устройства на другое, при этом раздел остался примонтирован и данные всё время оставались доступны!
Подобным образом мне удавалось без перезагрузки перенести всю систему с умирающего диска на рэид-массив. :)
А это моя любимая ссылка по LVM: xgu.ru/wiki/LVM
P.S. Прошу простить за опечатки, меня постоянно отвлекали =))
P.P.S. Ах, да!!! Самое главное и самый большой минус LVM — он не читается grub’ом
поэтому раздел /boot должен находиться вне LVM на отдельном разделе жёсткого диска,
иначе система не загрузится.