Автор Тема: Приёмы профессиональной работы в shell (справочник - вопросы не задавать. )  (Прочитано 174588 раз)

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
Запись в файловую систему udf файлов размером более 4Gb

# uname -rm
3.10.32-std-def-alt1 i686

Готовим образ
# dd if=/dev/zero of=./tmp/test.udf bs=1000k seek=4589 count=0 # (DVD 4.7)
# dd if=/dev/zero of=./tmp/test.udf bs=1024k seek=8152 count=0 # (DVD 8.5)

Создаём в образе файловую систему udf
# mkudffs --lvid=HD-Video --media-type=dvd -r 0x0150 /root/tmp/test.udf

Пусть для записи в образ с файловой системой udf нам нужен файл размером более 4Gb
# dd if=/dev/zero of=/root/tmp/clone.img bs=10M count=420
420+0 записей получено
420+0 записей отправлено
 скопировано 4404019200 байт (4,4 GB), 109,093 c, 40,4 MB/c
# ls -1 ./tmp/*
./tmp/clone.img
./tmp/test.udf
clone.img - что будем писать
test.udf - куда будем писать

Монтируем файловую систему udf
# mount ./tmp/test.udf /mnt/disk/ -o loop,rw
mount: /dev/loop1 is write-protected, mounting read-only

Монтирование файловой системы udf в режиме rw сломано, поэтому перемонтируем файловую в режим чтение/запись
# mount -o remount,rw /mnt/disk/
# mount|grep test
/root/tmp/test.udf on /mnt/disk type udf (rw,relatime,utf8)

Копируем файл clone.img в файловую систему udf образа test.udf
# cp ./tmp/clone.img /mnt/disk/

Файл удачно скопирован
# df -m /mnt/disk/
Файловая система 1M-blocks Использовано Доступно Использовано% Cмонтировано в
/dev/loop1            4481         4201      281           94% /mnt/disk
# ls -l /mnt/disk/
итого 4300800
-rw-r--r-- 1 root root 4404019200 окт 25 13:52 clone.img
drwxr-xr-x 2 root root         40 окт 25 13:44 lost+found
« Последнее редактирование: 04.11.2014 15:34:15 от Speccyfighter »

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
Hal Заготовка

Экскурс
# ps -eo args|grep hald-addon-storage|grep polling
hald-addon-storage: polling /dev/sr0 (every 2 sec)
# iotop
# man hal-disable-polling | less -p HISTORY

ВI
# hal-disable-polling --help

usage : hal-disable-polling [--udi <udi> | --device <device-file>]
                            [--enable-polling]
                            [--help] [--version]

        --udi            Unique Device Id
        --device         Device file
        --enable-polling Enable polling instead of disabling it
        --version        Show version and exit
        --help           Show this information and exit

This program is provided to make HAL stop polling a drive. Please read.
the entire manual page before using this program.
# hal-device |grep ' udi'|grep DVD
4: udi = '/org/freedesktop/Hal/devices/storage_serial_HL_DT_ST_DVD_RW_GWA_4082N_73888C357CAA'
# hal-disable-polling --device /dev/sr0
Polling for drive /dev/sr0 have been disabled. The fdi file written was
  /etc/hal/fdi/information/media-check-disable-storage_serial_HL_DT_ST_DVD_RW_GWA_4082N_73888C357CAA.fdi
# ps -eo args|grep hald-addon-storage|grep polling
hald-addon-storage: no polling on /dev/sr0 because it is explicitly disabled
# cat  /etc/hal/fdi/information/media-check-disable-storage_serial_HL_DT_ST_DVD_RW_GWA_4082N_73888C357CAA.fdi
<?xml version="1.0" encoding="UTF-8"?>

<deviceinfo version="0.2">
  <device>
    <match key="info.udi" string="/org/freedesktop/Hal/devices/storage_serial_HL_DT_ST_DVD_RW_GWA_4082N_73888C357CAA">
      <merge key="storage.media_check_enabled" type="bool">false</merge>
    </match>
  </device>
</deviceinfo>

# hal-disable-polling --device /dev/sr0 --enable-polling
Polling for drive /dev/sr0 have been enabled. The fdi file deleted was
  /etc/hal/fdi/information/media-check-disable-storage_serial_HL_DT_ST_DVD_RW_GWA_4082N_73888C357CAA.fdi
# ps -eo args|grep hald-addon-storage|grep polling
hald-addon-storage: polling /dev/sr0 (every 2 sec)


ВII
# ps -eo args|grep hald-addon-storage|grep polling
hald-addon-storage: polling /dev/sr0 (every 2 sec)
# cat  /etc/hal/fdi/information/media-check-disable-storage_serial_HL_DT_ST_DVD_RW_GWA_4082N_73888C357CAA.fdi
<?xml version="1.0" encoding="UTF-8"?>

<deviceinfo version="0.2">
  <device>
    <match key="info.udi" string="/org/freedesktop/Hal/devices/storage_serial_HL_DT_ST_DVD_RW_GWA_4082N_73888C357CAA">
      <merge key="storage.media_check_enabled" type="bool">false</merge>
    </match>
  </device>
</deviceinfo>

# ps -eo args|grep hald-addon-storage|grep polling
hald-addon-storage: polling /dev/sr0 (every 2 sec)
# /etc/init.d/haldaemon restart
Stopping HAL service:                            [ DONE ]
Starting HAL service:                            [ DONE ]
# ps -eo args|grep hald-addon-storage|grep polling
hald-addon-storage: no polling on /dev/sr0 because it is explicitly disabled
« Последнее редактирование: 29.10.2014 06:10:23 от Speccyfighter »

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
Определение типа файловых систем

Только на разделах
# file -s /dev/sd[a-z]?*
# file -s /dev/sd??*
$ /sbin/blkid
$ lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT /dev/sdb?

И на устройствах и на разделах
# file -s /dev/sd?*
$ /sbin/blkid /dev/sd[a-z]*
$ /sbin/blkid /dev/sd?*
$ lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT /dev/sd?

Только на устройствах
$ /sbin/blkid /dev/sd[a-z]
$ /sbin/blkid /dev/sd?
# file -s /dev/sd?
# file -s /dev/sd[a-z]

В образах
$ file -s /path/image [img|iso]
$ /sbin/blkid /path/image [img|iso]

Здесь не упоминались как не отвечающие требованию абсолютной надёжности:
- 'df -T | awk '{print $1,$2,$NF}' | grep ^/dev' и 'mount' - покажут тип только смонтированных файловых систем
- 'parted -l' - озадачится на нетиповых структурах разделов
- 'fsck -n' и '/etc/fstab' - первое опасно, второе бесполезно.
« Последнее редактирование: 09.11.2014 09:26:45 от Speccyfighter »

Оффлайн speccyfan

  • Завсегдатай
  • *
  • Сообщений: 522
  • CCNA
    • speccyfan (Примеры различных конфигураций сетевых сервисов)
Удалить старые файлы, оставив только измененные за последние 30 дней. (тут путь и число 30 для примера)
find /var/www/html/motion/cam1/video/* -mtime +30 -exec rm -rf {} \;
With best regards, Yury Konovalov aka 2:453/53

Оффлайн Skull

  • Глобальный модератор
  • *****
  • Сообщений: 19 903
    • Домашняя страница
    • Email
А чего не -delete ?
Андрей Черепанов (cas@)

Оффлайн speccyfan

  • Завсегдатай
  • *
  • Сообщений: 522
  • CCNA
    • speccyfan (Примеры различных конфигураций сетевых сервисов)
А чего не -delete ?
Потому что не знал, что так можно :) Спасибо за идею.
With best regards, Yury Konovalov aka 2:453/53

Оффлайн Skull

  • Глобальный модератор
  • *****
  • Сообщений: 19 903
    • Домашняя страница
    • Email
man find много что интересного рассказывает. :)
Андрей Черепанов (cas@)

Оффлайн Spanish ArCher

  • Завсегдатай
  • *
  • Сообщений: 1 234
man find много что интересного рассказывает. :)
Для find есть онлайн хелпер
http://ru.clihelper.com/find/
Если я попался вам навстречу, Значит вам со мной не по пути.
(С) Воскресение

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
Запуск приложения в DISPLAY=:1

$ startx /usr/local/games/SmokinGuns/smokinguns.start -- :1
$ cat /usr/local/games/SmokinGuns/smokinguns.start
#!/bin/bash

xgamma -gamma 1.5 && /usr/local/games/SmokinGuns/smokinguns.i386 && xgamma -gamma 1.0

Переключение между дисплеями по Ctrl+Alt+F7, Ctrl+Alt+F8 и т.д.

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
Просмотр утилизации ресурсов компьютера

Пакет
rpm -qf $(which sar)
sysstat-10.0.4-alt1

Старт сервиса
# /etc/init.d/sysstat start

Утилизация CPU за текущую дату
# sar -C
Linux 3.14.25-std-def-alt1 (host) 14.01.2015 _i686_ (1 CPU)

00:00:01        CPU     %user     %nice   %system   %iowait    %steal     %idle
...
03:40:01        all      0,68      0,01      0,63      0,24      0,00     98,44
03:50:02        all     23,79      0,01      2,60      1,25      0,00     72,35
...

Утилизация памяти за текущую дату
# sar -r
Linux 3.14.25-std-def-alt1 (host) 14.01.2015 _i686_ (1 CPU)

00:00:01    kbmemfree kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact
...
03:40:01       662552    358536     35,11     15568    244548    700900     23,27    140160    175632
03:50:02       194444    826644     80,96     20936    302896   1417236     47,06    552836    229544
...

Утилизация памяти за 13-е число текущего месяца
# sar -r -f /var/log/sa/sa13
Linux 3.14.25-std-def-alt1 (host) 13.01.2015 _i686_ (1 CPU)

01:50:01    kbmemfree kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact
...
05:30:02        37988    983100     96,28       292     85624   2308280     76,65    478604    467508
...

Активность блочных устройств за 13-е число
# sar -d -p -f /var/log/sa/sa13
Linux 3.14.25-std-def-alt1 (host) 13.01.2015 _i686_ (1 CPU)

01:50:01          DEV       tps  rd_sec/s  wr_sec/s  avgrq-sz  avgqu-sz     await     svctm     %util
...
05:30:02          sda     85,33   2465,94   1543,59     46,99      1,63     19,11      5,00     42,69
...

Использование swap за 13-е число
# sar -S -f /var/log/sa/sa13
Linux 3.14.25-std-def-alt1 (host) 13.01.2015 _i686_ (1 CPU)

01:50:01    kbswpfree kbswpused  %swpused  kbswpcad   %swpcad
...
05:30:02      1427444    563040     28,29     40012      7,11
...


Утилизация CPU за 13-е число
# sar -C -f /var/log/sa/sa13
Linux 3.14.25-std-def-alt1 (host) 13.01.2015 _i686_ (1 CPU)

01:50:01        CPU     %user     %nice   %system   %iowait    %steal     %idle
...
05:30:02        all     44,12      0,01      4,43     33,99      0,00     17,45
...

Поиск пяти самых ресурсоёмких по использованию памяти процессов
$ ps -eo rss,vsz,pcpu,pmem,args|sort -n|tail -n 5

Статистика утилизации (загрузки процессора) в bash shell
« Последнее редактирование: 26.01.2015 10:25:44 от Speccyfighter »

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
Сетевые мелочи

Поиск активных хостов в локальной сети по ip-адресам
$ echo 192.168.1.{1..254}|xargs -n1 -P0 ping -c1|grep "bytes from"
$ while true; do clear; \
echo 192.168.1.{1..254}|xargs -n1 -P0 ping -c1|grep "bytes from" \
|cut -f4 -d ' '| sed 's/.$//'; \
date +%H:%M:%S; \
sleep 50s; \
done

Просмотр статуса нод
$ nmblookup -S WORKGROUP

Просмотр списка шар на хосте
$ smbclient -L 192.168.xxx.yyy

Просмотр всех доменов, серверов в доменах и шар на серверах
$ smbtree

Гостевое монтирование шары
# mount -t cifs -o guest //192.168.xxx.yyy/share /mnt/disk
# mount -t cifs -o username=guest //192.168.xxx.yyy/share /mnt/disk
Password for guest@//192.168.xxx.yyyy/share:

« Последнее редактирование: 26.01.2015 09:57:23 от Speccyfighter »

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
Очистка буферов и кеша

https://www.kernel.org/doc/Documentation/sysctl/vm.txt
Цитировать
drop_caches

Writing to this will cause the kernel to drop clean caches, as well as
reclaimable slab objects like dentries and inodes.  Once dropped, their
memory becomes free.

To free pagecache:
   echo 1 > /proc/sys/vm/drop_caches
To free reclaimable slab objects (includes dentries and inodes):
   echo 2 > /proc/sys/vm/drop_caches
To free slab objects and pagecache:
   echo 3 > /proc/sys/vm/drop_caches

This is a non-destructive operation and will not free any dirty objects.
To increase the number of objects freed by this operation, the user may run
`sync' prior to writing to /proc/sys/vm/drop_caches.  This will minimize the
number of dirty objects on the system and create more candidates to be
dropped.

This file is not a means to control the growth of the various kernel caches
(inodes, dentries, pagecache, etc...)  These objects are automatically
reclaimed by the kernel when memory is needed elsewhere on the system.

Use of this file can cause performance problems.  Since it discards cached
objects, it may cost a significant amount of I/O and CPU to recreate the
dropped objects, especially if they were under heavy use.  Because of this,
use outside of a testing or debugging environment is not recommended.

You may see informational messages in your kernel log when this file is
used:

   cat (1234): drop_caches: 3

These are informational only.  They do not mean that anything is wrong
with your system.  To disable them, echo 4 (bit 3) into drop_caches.

# free -k
             total       used       free     shared    buffers     cached
Mem:       1021088     962972      58116          0       1340     120508
-/+ buffers/cache:     841124     179964
Swap:      1990484     262064    1728420
# sync && echo 3 > /proc/sys/vm/drop_caches
# free -k
             total       used       free     shared    buffers     cached
Mem:       1021088     850932     170156          0       1052      77016
-/+ buffers/cache:     772864     248224
Swap:      1990484     245856    1744628

Здесь, в команде очистки, применяется двойной амперсанд:
следующая команда после амперсандов будет выполнена, если предыдущая возвращает 0.
И не будет выполнена, если sync возвратит не 0.
Т.е. если sync по какой-то причине не сможет выполнить синхроницацию, следующая за ним команда очистки выполнена не будет.
« Последнее редактирование: 23.01.2015 18:51:45 от Speccyfighter »

Оффлайн rotkart

  • Завсегдатай
  • *
  • Сообщений: 661
    • Email
Поиск активных хостов в локальной сети по ip-адресам

[root@father ~]# apt-get install fping
...
[root@father ~]# fping -a -g 192.168.23.0/24 2>/dev/null
192.168.23.1
192.168.23.143
[root@father ~]#
Научить нельзя, научиться можно.

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
Извлечение аудиотрека из видеофайла

Анализ видеофайла:
$ mediainfo videofile.mp4  |grep 'Format\|Bit rate'
Format                                   : MPEG-4
...
Format                                   : AVC
Format/Info                              : Advanced Video Codec
...
Bit rate                                 : 547 Kbps
Format                                   : AAC
Format/Info                              : Advanced Audio Codec
...
Bit rate mode                            : Variable
Bit rate                                 : 96.0 Kbps
...
в котором, aac, это формат аудиотрека.

Извлечение аудиотрека без перекодирования:
$ avconv -i /path/input-videofile.mp4 -vn -acodec copy -y /path/output-audiofile.aac

Извлечение аудиотрека c перекодированием в mp3 формат:
$ avconv -i /path/input-videofile.mp4 -vn -acodec libmp3lame -y /path/output-audiofile.mp3

Извлечение аудиотрека c перекодированием в mp3 формат с изменением качества:
$ avconv -i /path/input-videofile.mp4 -vn -acodec libmp3lame -aq 1 -y /path/output-audiofile.mp3
$ ffmpeg -i "./author — name.mp4" -vn -acodec libmp3lame -aq 1 "./author - name.mp3"

-aq  - audio quality
1<=качество<=31  - меньше - лучше
« Последнее редактирование: 24.07.2021 20:39:10 от Speccyfighter »

Оффлайн Speccyfighter

  • Мастер
  • ***
  • Сообщений: 10 259
ALSA
Запись звука с выхода аудиокарты

$ mplayer -nocache -softvol http://us.ah.fm:9000
$ man arecord
$ arecord -L
null
    Discard all samples (playback) or generate zero samples (capture)
default:CARD=ICH6
    Intel ICH6, Intel ICH6
    Default Audio Device
sysdefault:CARD=ICH6
    Intel ICH6, Intel ICH6
    Default Audio Device
front:CARD=ICH6,DEV=0
    Intel ICH6, Intel ICH6
    Front speakers
surround40:CARD=ICH6,DEV=0
    Intel ICH6, Intel ICH6
    4.0 Surround output to Front and Rear speakers
surround41:CARD=ICH6,DEV=0
    Intel ICH6, Intel ICH6
    4.1 Surround output to Front, Rear and Subwoofer speakers
surround50:CARD=ICH6,DEV=0
    Intel ICH6, Intel ICH6
    5.0 Surround output to Front, Center and Rear speakers
surround51:CARD=ICH6,DEV=0
    Intel ICH6, Intel ICH6
    5.1 Surround output to Front, Center, Rear and Subwoofer speakers
$ arecord -D front:CARD=ICH6,DEV=0 out.wav
Recording WAVE 'out.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono
arecord: set_params:1233: Sample format non available
Available formats:
- S16_LE
$ man arecord
$ arecord -D front:CARD=ICH6,DEV=0 -f S16_LE out.wav
Recording WAVE 'out.wav' : Signed 16 bit Little Endian, Rate 8000 Hz, Mono
arecord: set_params:1239: Channels count non available
$ man arecord

Уровни Master, PCM, Front должны быть достаточно высокими! :
$ arecord -D front:CARD=ICH6,DEV=0 -f S16_LE -c2 -r44100 out.wav
Recording WAVE 'out.wav' : Signed 16 bit Little Endian, Rate 44100 Hz, Stereo
^CAborted by signal Прерывание...
$ mplayer -nocache -softvol out.wav
MPlayer 1.1-4.7.2 (C) 2000-2012 MPlayer Team
192 audio & 401 video codecs

Playing out.wav.
Cache fill:  0.00% (0 bytes)

libavformat version 54.6.100 (internal)
Audio only file format detected.
Load subtitles in ./
==========================================================================
Opening audio decoder: [pcm] Uncompressed PCM audio decoder
AUDIO: 44100 Hz, 2 ch, s16le, 1411.2 kbit/100.00% (ratio: 176400->176400)
Selected audio codec: [pcm] afm: pcm (Uncompressed PCM)
==========================================================================
AO: [alsa] 48000Hz 2ch s16le (2 bytes per sample)
Video: no video
Starting playback...
A:   8.7 (08.7) of 27.0 (27.0)  0.9% 39%

Exiting... (Quit)


Захват звука с выхода звуковой карты с перекодированием в файл

$ mplayer -nocache -softvol http://fr1.1mix.co.uk:8000
$ arecord -D front:CARD=ICH6,DEV=0 -f S16_LE -c2 -r44100 -t wav |lame - -b 192k -s 44.1 out.mp3
Recording WAVE 'stdin' : Signed 16 bit Little Endian, Rate 44100 Hz, Stereo
^CAborted by signal Прерывание...
$ mplayer -nocache -softvol out.mp3
MPlayer 1.1-4.7.2 (C) 2000-2012 MPlayer Team
192 audio & 401 video codecs

Playing out.mp3.
libavformat version 54.6.100 (internal)
Audio only file format detected.
Load subtitles in ./
==========================================================================
Opening audio decoder: [mpg123] MPEG 1.0/2.0/2.5 layers I, II, III
AUDIO: 44100 Hz, 2 ch, s16le, 192.0 kbit/13.61% (ratio: 24000->176400)
Selected audio codec: [mpg123] afm: mpg123 (MPEG 1.0/2.0/2.5 layers I, II, III)
==========================================================================
AO: [alsa] 48000Hz 2ch s16le (2 bytes per sample)
Video: no video
Starting playback...
A:  19.5 (19.4) of 19.0 (19.0)  3.5%

Exiting... (End of file)
« Последнее редактирование: 26.02.2015 20:22:43 от Speccyfighter »