LINUX.ORG.RU

Сообщения CrownRU

 

Заделал пару функций.

Пока летел в самолете, наваял для bashrc парочку функций. Выложил все в github. https://github.com/mrAibo/bash/tree/main

В общем-то ничего особенного, за исключением пары функций из-за которых и выкладываю. Может кто-то оценит. Документацию составил ИИ. Тестируйте, если есть идеи, что добавить/улучшить - пишите. Будет время рассмотрю.

rcp (Remote Copy) Function

The rcp function is a versatile tool for copying files and directories, both locally and to/from remote systems. It supports both rsync and scp, offering various options for compression, moving files, and more.

Usage

rcp [OPTIONS] source destination

Key Features

  • Supports both local and remote file transfers
  • Option to use rsync (default) or scp
  • File compression during transfer
  • Move files instead of copying
  • Bandwidth limiting
  • Exclude patterns for selective file transfer
  • Verbose output option

Options

  • -z, --compress: Compress data during transfer
  • -m, --move: Move files (delete source after successful transfer)
  • -u, --user USERNAME: Specify remote username
  • -p, --port PORT: Specify SSH port
  • -i, --identity FILE: Use specific SSH identity file
  • -l, --limit RATE: Set bandwidth limit (KB/s, rsync only)
  • -e, --exclude FILE: Specify exclude file or pattern
  • -s, --use-scp: Force SCP instead of rsync
  • -v, --verbose: Enable verbose output
  • -h, --help: Show help message

Examples

  1. Basic copy:

    rcp /path/to/source user@remote:/path/to/destination
    
  2. Compressed transfer with verbose output:

    rcp --compress --verbose /path/to/source user@remote:/path/to/destination
    
  3. Move files using a specific SSH key and port:

    rcp -m -p 2222 -i ~/.ssh/my_key /path/to/source user@remote:/path/to/destination
    
  4. Use SCP with exclude patterns:

    rcp --use-scp --exclude '*.log' /path/to/source user@remote:/path/to/destination
    
  5. Limit bandwidth and use compression:

    rcp -z -l 1000 -e '**/*.tmp' /path/to/source user@remote:/path/to/destination
    

This function provides a flexible and powerful way to handle file transfers in various scenarios, combining the strengths of rsync and scp with additional features for improved usability.

ex (Extract and Compress) Function

The ex function is a versatile tool for extracting and compressing various types of archive files. It supports multiple formats and offers options for both extraction and compression operations.

Usage

ex [OPTIONS] file1 [file2 ...]

Key Features

  • Supports multiple archive formats (e.g., tar.gz, zip, 7z)
  • Can extract and compress files
  • Allows specifying a target directory for operations
  • Option to delete original files after successful operation
  • Supports excluding files/directories during compression
  • Verbose mode for detailed operation information

Options

  • -x, --extract: Extract mode (default)
  • -c, --compress FORMAT: Compress mode (specify format: tar.gz, tar.bz2, zip, 7z)
  • -v, --verbose: Enable verbose output
  • -t, --target DIR: Specify target directory for extraction or compression
  • -d, --delete: Delete original file(s) after operation
  • -e, --exclude PATTERN: Exclude files/directories matching the pattern or specified in a file
  • -h, --help: Show help message

Supported Formats

Extraction

  • .tar.bz2, .tar.gz, .bz2, .rar, .gz, .tar, .tbz2, .tgz, .zip, .Z, .7z, .xz, .exe, .tar.xz, .tar.zst

Compression

  • tar.gz, tar.bz2, zip, 7z

Examples

  1. Extract an archive:

    ex archive.tar.gz
    
  2. Compress files to a zip archive with verbose output:

    ex --compress zip --verbose --target /tmp file1 file2
    
  3. Extract files to a specific directory and delete the original archive:

    ex --extract --delete --target /path/to/extract archive.zip
    
  4. Compress directories to a tar.gz archive, excluding certain files:

    ex --compress tar.gz --exclude '*.log' --target /tmp dir1 dir2
    
  5. Compress using patterns from an exclude file:

    ex -c zip --exclude exclude.txt dir1 dir2
    

The ex function simplifies the process of working with archives by providing a unified interface for both extraction and compression tasks. It supports a wide range of formats and offers flexibility through various options, making it a powerful tool for file archiving and extraction operations.

duu (Enhanced Disk Usage) Function

The duu function is an enhanced version of the standard du (disk usage) command. It provides a colorful, easy-to-read summary of disk usage for directories and files.

Usage

duu [directory]

If no directory is specified, it will analyze the current directory.

Key Features

  • Color-coded output for easy reading
  • Sorts results by size in descending order
  • Displays sizes in human-readable format (K, M, G, T)
  • Shows percentage and graphical representation of disk usage
  • Summarizes total disk usage at the end

Output Format

The function displays the following information:

  1. Size: The amount of disk space used
  2. Unit: The unit of measurement (K, M, G, T)
  3. Usage: A graphical bar representing the percentage of usage
  4. Path: The file or directory path

Color Coding

  • Green: Kilobytes (K)
  • Yellow: Megabytes (M)
  • Cyan: Gigabytes (G)
  • Magenta: Terabytes (T)
  • Blue: Default color for other units

Example Output

  Disk Usage Summary  
Size       Unit   Usage    Path
---------- ------ --------- --------------------
   1.23    G      █████░░░░ /home/user/Documents
   856.45  M      ████░░░░░ /home/user/Downloads
   234.56  M      ██░░░░░░░ /home/user/Pictures
   45.67   M      █░░░░░░░░ /home/user/.config
----------------------------------------
Total:     2.34   G     

Benefits

  1. Visual Representation: The bar chart provides an immediate visual cue about the relative sizes of directories.
  2. Color-Coding: Different colors for different size units make it easy to quickly identify large consumers of disk space.
  3. Sorted Output: Results are sorted by size, placing the largest items at the top.
  4. Human-Readable: Sizes are converted to the most appropriate unit (K, M, G, T) for easy understanding.
  5. Total Summary: Provides a total at the end, giving an overview of the analyzed directory’s total size.

Use Cases

  • Quickly identify large files or directories consuming disk space
  • Analyze disk usage patterns in a visually appealing manner
  • Get a summarized view of disk usage in a specific directory

The duu function enhances the standard disk usage analysis by providing a more user-friendly and informative output, making it easier to understand and manage disk space usage.

 ,

CrownRU
()

Ошибка в Python VS Code

Привет всем. Столкнулся со следующей проблемой. Решил попробовать VS Code под Linux. При запуске какого нибудь .py скрипта получаю следующие ошибки:

ModuleNotFoundError: No module named ‘turtle’ NameError: name ‘requests’ is not defined

Причем в Code OSS все работает. Я так подозреваю, что причина в том, что VS тянет левую версию питона, да и терминал выглядит как-то не так. Если кто знает как побороть, подскажите пожалуйста.

На картинке все видно: Picture

 , ,

CrownRU
()

Не получается загрузить Windows из grub

Уважаемые коллеги, помогите решить следующую проблему. Проинсталлировал Linux Manjaro. Из GRUB не грузится Windows с ошибкой:

file /efi/Microsoft/Boot/bootmgfw.efi not found.

Что интересно, он существует:

sudo os-prober
/dev/nvme1n1p2@/efi/Microsoft/Boot/bootmgfw.efi:Windows Boot Manager:Windows:efi

И команда upgrade-grub находит его:

sudo update-grub
Windows Boot Manager auf /dev/nvme1n1p2@/efi/Microsoft/Boot/bootmgfw.efi gefunden

Дальше я заглянул в директорию

sudo ls -la /boot/efi/EFI/

и не увидел там директории Microsoft.

Дальше я замонтировал в tst /dev/nvme1n1p2 и вот тут я смог увидеть bootmgfw.efi :

ls EFI/Microsoft/Boot/bootmgfw.efi
EFI/Microsoft/Boot/bootmgfw.efi

Попробовал внести новый раздел в grub по инструкции https://wiki.archlinux.org/title/GRUB#Chainloading_a_unified_kernel_image К сожалению следующие шаги не привели меня к успеху:

grub-probe --target=fs_uuid EFI/Microsoft/Boot/bootmgfw.efi
grub-probe: Warnung: Platte existiert nicht, ersatzweise wird Partition des Geräts /dev/nvme1n1p2 verwendet.
grub-probe: Warnung: Platte existiert nicht, ersatzweise wird Partition des Geräts /dev/nvme1n1p2 verwendet.
grub-probe: Warnung: Platte existiert nicht, ersatzweise wird Partition des Geräts /dev/nvme1n1p2 verwendet.
grub-probe: Fehler: Laufwerk »hostdisk//dev/nvme1n1p2« wurde nicht gefunden..

Ладно, попробуем скопировать файл на место:

sudo cp -r ~/tst/EFI/Microsoft/ /boot/efi/EFI/
sudo grub-probe --target=fs_uuid /boot/efi/EFI/Microsoft/Boot/bootmgfw.efi
18B6-D501

Но я рано обрадовалсяs:

sudo grub-probe --target=hints_string /boot/efi/EFI/Microsoft/Boot/bootmgfw.efi
grub-probe: Warnung: Unbekannter Gerätetyp nvme0n1

Вот теперь не знаю, что дальше делать. Может кто сталкивался с данной проблемой?

 , ,

CrownRU
()

find - не удаляются файлы

Такой вопрос. Надо удалить логи, которые старше 30 дней. Написал такой find:

 find /var/log/ -mindepth 1 -type f -name *.log.* -o -name *.log-* -mtime +30 -delete

Заканчивается без ошибок. Смотрю в директорию - файлы не удалились. Запускаю команду без "-delete" -все файлы не тронуты.

Пробую дальше:

 find /var/log/ -mindepth 1 -type f -name *.log.* -o -name *.log-* -mtime +30 -exec rm -f {} \;

Та же хрень - файлы не удаляются. Да что же это такое?..

 find /var/log/ -mindepth 1 -type f -name *.log.* -o -name *.log-* -atime +30 -print0 | xargs -0 rm -f

Опять без результата. И ЧСХ, напрямую через rm файлы удаляются. Вот еще попробовал с -print0 -ничего не показывает, без -print все файлы выводятся. Никто не сталкивался с такими граблями?

Спасибо большое, заранее.

 , ,

CrownRU
()

Автоматическое создание $HOME для vsftpd

Доброе время суток! Помогите уговорить vsftpd создавать домашние директории виртуальным пользователям. Пользователей завожу в DB4, Berkley, то бишь. Прописываю в PAM

session    required     pam_mkhomedir.so skel=/etc/skel/ umask=0022 
А в /etc/pam.d/vsftpd.virtual -
session_support=YES
, как и пишут в мануалах. Проблема только в том, что если я в конфиге вставляю
session_support=YES
, то не могу вообще зайти на FTP - ошибка.
331 Please specify the password.
Password:
530 Login incorrect.
Login failed.
Убираю - могу зайти, но директории не создаются. Заранее спасибо за помощь!

 # cat /etc/pam.d/vsftpd.virtual
#%PAM-1.0
auth       required      pam_userdb.so db=/etc/vsftpd/vsftpd-virtual-user
account    required      pam_userdb.so db=/etc/vsftpd/vsftpd-virtual-user
session    required     pam_loginuid.so
session    required     pam_mkhomedir.so skel=/etc/skel/ umask=0022 
# cat vsftpd.conf
# enable background mode
# background=YES
# disables anonymous FTP
anonymous_enable=NO
# enables non-anonymous FTP
local_enable=YES
# enables uploads and new directories
write_enable=YES
# activates virtual users
guest_enable=YES
# virtual users to use local privs, not anon privs
virtual_use_local_privs=YES
# the PAM file used by authentication of virtual uses
pam_service_name=vsftpd.virtual
# in conjunction with 'local_root',
# specifies a home directory for each virtual user
user_sub_token=$USER
local_root=/tmp/ftp/$USER
# anon_root=/var/www/ftp
# the virtual user is restricted to the virtual FTP area
chroot_local_user=YES
# hides the FTP server user IDs and just display "ftp" in directory listings
hide_ids=YES

# the umask for file creation
local_umask=022
dirmessage_enable=YES
# Activate logging of uploads/downloads.
xferlog_enable=YES
connect_from_port_20=YES
xferlog_std_format=NO
# runs vsftpd in standalone mode
listen=YES

use_localtime=NO
# pam_service_name=vsftpd
# userlist_enable=YES
tcp_wrappers=YES

# SSL Properties
ssl_enable=YES
allow_anon_ssl=NO
force_local_data_ssl=NO
force_local_logins_ssl=NO
ssl_tlsv1=YES
ssl_sslv2=YES
ssl_sslv3=YES
ssl_ciphers=HIGH
rsa_cert_file=/etc/vsftpd/vsftpd.pem
rsa_private_key_file=/etc/vsftpd/vsftpd.key

# Restrict connections
# max_clients=20
# max_per_ip=10
log_ftp_protocol=YES
vsftpd_log_file=/var/log/vsftpd.log
session_support=YES
CrownRU
()

Что-то жрет CPU между 02:00 и 04:00

Всем доброго времени! У меня образовалась следующая проблема. В Solaris 10 что-то между 02:00 и 04:00 отъедает 100% CPU, потом все устаканивается. Как мне выявить процесс/сы, если никаких посторонних приложений для мониторинга, типа Zabbix, Nagios, устанавливать нельзя? П.С. О существовании команд: # mpstat # ps -e -o pcpu -o pid -o user -o args # prstat -avm # sar -u 10 60 знаю.

Спасибо заранее.

CrownRU
()

Скрипты, которые мы пишем...

Уважаемый All,
все мы по долгу службы или просто для своего удобства
вынуждены писать различные скрипты для различных целей, будь то
автоматическая инсталяция продуктов на несколько машин или вещи
попроще. Вот я и подумал, что зачем сто раз писать то, что уже
давно написано и во что вложено достаточно труда и времени.
Давайте устроим здесь своеобразный ⌠пункт обмена■, неопытные
пользователи скажут Вам спасибо и смогут сразу использовать
скрипты, а опытные смогут сэкономить себе немного времени,
головной боли, а также поучится новым программистским приемам.
Для затравки выложу здесь небольшой (большой в заголовке темы,
думаю могут не пропустить) скрипт, который упорядывачивает вывод
от стандартной команды df (для Линукса это, может не так актуально,
а мне на Солярисе 2.6 очень даже помогает.) внутри ещё чего покидаю...
Так что, продолжение следует?..

!/bin/ksh -p
if [ $# = 0 ] ; then
print - "`df -k | head -1 ;
df -k | tail +2 | egrep -v '^\/dev\/dsk|^\/dev\/md' | sort -k 1 ; \
df -k | egrep '^\/dev\/dsk|^\/dev\/md' | sort -k 1 ; \
df -k | \
awk '{a+=$2} {b+=$3} {c+=$4} END \
{printf \"TOTAL %-8d %-7d %-7d %5d%%\n\", \
a,b,c,100-((c/a)*100)}'`" | \
sed 's/Mounted on/MountPoint/' | \
nawk '{for (i=length($0);i;i--) printf "%c", substr($0,i,1); printf "\n"}' | \
sed -e "s/\([0-9][0-9][0-9]\)\([0-9][0-9][ 0-9]\)/\1,\2/g" -e \
"s/\([0-9][0-9][0-9]\)\([0-9][0-9]\ )/\1,\2/g" -e \
"s/\([0-9][0-9][0-9]\)\([0-9]\)/\1, \2/g" | \
nawk '{for (i=length($0);i;i--) printf "%c", substr($0,i,1); printf "\n"}' > \
/tmp/DF.$$
else
print - "`df -k $@ ; df -k $@ | \
awk '{a+=$2} {b+=$3} {c+=$4} END \
{printf \"TOTAL %-8d %-7d %-7d %5d%%\n\", \
a,b,c,100-((c/a)*100)}'`" | \
sed 's/Mounted on/MountPoint/' | \
nawk '{for (i=length($0);i;i--) printf "%c", substr($0,i,1); printf "\n"}' | \
sed -e "s/\([0-9][0-9][0-9]\)\([0-9][0-9][ 0-9]\)/\1,\2/g" -e \
"s/\([0-9][0-9][0-9]\)\([0-9][0-9]\ )/\1,\2/g" -e \
"s/\([0-9][0-9][0-9]\)\([0-9]\)/\1, \2/g" | \
nawk '{for (i=length($0);i;i--) printf "%c", substr($0,i,1); printf "\n"}' > \
/tmp/DF.$$
fi
while read Filesystem kbytes used avail capacity MountedOn ; do
printf "%-38.38s %11.11s %11.11s %11.11s %5.5s %-18.18s\n" \
$Filesystem $kbytes $used $avail $capacity $MountedOn | \
sed 's/MountPoint/Mounted on/g'
done < /tmp/DF.$$
rm -f /tmp/DF.$$

#df-sum

hostnm=`hostname`
dfbinary="/bin/df -kl"
disksum=`$dfbinary | grep dev | awk '{t += $2; u += $3} \
END { printf("%d %d",t,u) }'`
printf "================================== ======================================== ======================\n"
printf "TOTAL local for \033[1m%-8s\033[0m in kbytes\n" $hostnm
printf "%50d %11d\n" $disksum


exit 0

CrownRU
()

RSS подписка на новые темы