EK bio photo


Totally not a hacker

Email Twitter Github

Different Linux / Unix / IT tips, notes, howto part 2


Other parts

Part 1 Part 2 Part 3

MySQL log rotate

/logs/mysql/mysql /logs/mysql/mysql.err /logs/mysql/mysql-slow.log /logs/mysql/query.log {
        rotate 7
        # just if mysqld is really running
        if test -x /usr/bin/mysqladmin && \
           /usr/bin/mysqladmin ping &>/dev/null
           /usr/bin/mysqladmin flush-logs

MySQL dump with procedures/functions/triggers

mysqldump --routines --no-create-info --no-data --no-create-db --skip-opt <database> > outputfile.sql
mysql <database> < outputfile.sql

Show last login history

last -f  /var/log/wtmp.0
 -f file  Specifies a file to search other than /var/log/wtmp.

Enable PostgreSQL Vacuum

vacuum full VERBOSE analyze;

Create GEO DB for nginx

For use by the ngx_http_geo_module
wget http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip
unzip GeoIPCountryCSV.zip
wget https://raw.githubusercontent.com/simplegeo/nginx/master/contrib/geo2nginx.pl
perl geo2nginx.pl < GeoIPCountryWhois.csv > geo.conf

Connect to COM port from FreeBSD or Linux

tip -vs9600 com1
to disconnect  shift+~~+.

cu -l /dev/cuau0 -s9600

minicom -s
9600 8N1
sudo -u root minicom -s

Upload IOS to Cisco router\switch from CentOS tftp

centos# yum -y install tftp-server tftp
centos# /etc/xinetd.d/tftp
disable = no
centos# service xinetd start

switch# copy tftp: flash:
switch# dir flash:
switch#show boot
switch# configure terminal
switch# (config)#boot system flash:c3550-i5q3l2-mz.121-13.

Enable SSH on Cisco 2960 switch

You IOS must support K9, ex c2960s-universalk9-mz.122-55.SE3.bin

conf t
ip domain-name domain.com
crypto key generate rsa

line vty 0 4
transport input ssh
exec-timeout 0 0

Restore Cisco password

Connect COM port
Reboot router and wait «Self decompressing the image: » press Ctrl-C or Ctrl-Break
confreg 0x2142(default -  2102)
copy start run
make change with config
config-register 0x2102

Boot CentOS in a Single-User Mode

add to grub line that start with kernel - single

Delete MySQL binary logs

expire_logs_days = 7
PURGE BINARY LOGS TO 'mysqld-bin.000123';

Show memory map of a process

pmap PID

Show all packages files in CentOS

for i in `rpm -qa`; do echo $i; rpm -ql $i; done

Find duplicate files in Linux

for i in `find *`; do [ -f "$i" ] && echo "`md5sum \"$i\"`"; done | sort | awk -- '{ if (LAST==$1) print; else LAST=$1 }
find /dir -type f -print0 | xargs -0 md5sum | sort | uniq -w32 -D # |awk '{print $2}'

SSH+SVN error

ssh svn: Network connection closed unexpectedly
This mean that you dont have sshkey fingerprint in know_hosts
try ssh to server first

Kill all long MySQL request

mysql -e 'show full processlist'|grep -v Command |awk '{if ($6 >= 10) print "kill " $1 ";"}' |mysql


LAST_ACK - mean that remote host is disconnected and socker is closed, we are waiting acknowledgment

sysctl -a |grep last_ack
net.ipv4.netfilter.ip_conntrack_tcp_timeout_last_ack = 30
sysctl -w net.ipv4.netfilter.ip_conntrack_tcp_timeout_last_ack=10
netstat -ant | fgrep ":" | cut -b 77-90 | sort | uniq -c

cat /proc/sys/net/netfilter/nf_conntrack_count
cat /proc/sys/net/ipv4/netfilter/ip_conntrack_count
cat /proc/sys/net/ipv4/ip_conntrack_max
echo 131072 > /proc/sys/net/ipv4/ip_conntrack_max
sysctl net.ipv4.netfilter.ip_conntrack_max=1048576

or disable conntrack for port

iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -t raw -A PREROUTING -p tcp --dport 443 -j NOTRACK

SYN flood protection

echo "20000" > /proc/sys/net/ipv4/tcp_max_syn_backlog
echo "1" > /proc/sys/net/ipv4/tcp_synack_retries
echo "30" > /proc/sys/net/ipv4/tcp_fin_timeout
echo "5" > /proc/sys/net/ipv4/tcp_keepalive_probes
echo "15" > /proc/sys/net/ipv4/tcp_keepalive_intvl
echo "20000" > /proc/sys/net/core/netdev_max_backlog
echo "20000" > /proc/sys/net/core/somaxconn

iptables -N syn_flood
$IPT -A INPUT -p tcp --syn -j syn_flood
$IPT -A syn_flood -m limit --limit 500/s --limit-burst 1500 -j RETURN
$IPT -A syn_flood -j DROP

MegaCli on FreeBSD

Install linux compat from ports
mkdir -p /usr/compat/linux/proc
linsys          /compat/linux/sys       linsysfs        rw 0 0
linproc         /compat/linux/proc      linprocfs       rw 0 0
mount linsys
mount linproc
MegaCli -CfgDsply -a0

Convert MySQL db from cp1251 to Utf8

mysqldump --default-character-set=utf8 database > database.utf8.sql
mysql --default-character-set=utf8 database_new < database.utf8.sql

mysqldump -u admin --password=PASS --opt --default-character-set=latin1 --skip-set-charset -Q DB_NAME > database.sql
sed -i 's/character set cp1251 collate cp1251_bin/character set utf8 collate utf8_bin/' database.sql
sed -i 's/CHARSET=cp1251/CHARSET=utf8/' database.sql

Insert text in the top of file

perl -i~ -0777pe's/^/New first line\n/' yourfile

IPMI in Linux of FreeBSD

yum install OpenIPMI OpenIPMI-tools
/sbin/modprobe ipmi_devintf; /sbin/modprobe ipmi_si; /sbin/modprobe ipmi_msghandler
# Logging
ipmitool sel info
ipmitool sel list

# kldload ipmi
# dmesg | tail
ipmi0:  on isa0
ipmi0: KCS mode found at io 0xca2 alignment 0x1 on isa
ipmi0: IPMI device rev. 1, firmware rev. 0.2, version 2.0
ipmi0: Number of channels 2
ipmi0: Attached watchdog

# ipmitool chassis status
System Power         : on
Power Overload       : false
Power Interlock      : inactive
Main Power Fault     : false
Power Control Fault  : false
Power Restore Policy : always-on
Last Power Event     : command

Disable NginX\Apache server token

server_tokens off

ServerTokens ProductOnly
ServerSignature Off

Show installed perl modules

perl -MFile::Find=find -MFile::Spec::Functions -Tlwe \
'find { wanted => sub { print canonpath $_ if /\.pm\z/ }, no_chdir => 1 }, @INC'

Use strace\lsof

strace -e trace=network -p PID
strace $(pidof httpd |sed 's/\([0-9]*\)/\-p \1/g')

lsof -nPp PID
lsof -a -U -u username
lsof -F pcfn
lsof +d /mnt/DIR
lsof +D /mnt/DIR
lsof -i [46][protocol][@hostname|hostaddr][:service|port]

Create Patch

diff -crB tmpl_lib.c.orig tmpl_lib.c > tmpl_lib.patchс
patch -p1 -i tmpl_lib.patch

Create gstripe in FreeBSD

kldload geom_stripe
sysctl kern.geom.debugflags=16
gstripe lable -v st0 /dev/da1 /dev/da2 /dev/da3 /dev/da4 /dev/da5
gstripe create -v st0 /dev/da1 /dev/da2 /dev/da3 /dev/da4 /dev/da5
bsdlabel -wB /dev/stripe/st0
newfs -O 2 -U /dev/stripe/st0a
mount /dev/stripe/st0a /www

echo 'geom_stripe_load="YES"' >> /boot/loader.conf

/dev/stripe/st0a       /www           ufs     rw,noatime              2       2

tunefs -m 1 /dev/stripe/st0a

Delete trailing spaces in text with VIM

delete blank lines

Disable Apache dir listing

<Directory />
    Options -Indexes
    AllowOverride all
    Order allow,deny
    Allow from all

MySQL load data grant

grant file on *.* to user@localhost identified by 'P@ssw0rd';

MySQL grants for fields in table

GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO 'someuser'@'somehost';

Determine MAX MTU

ping ya.ru -v -M dont -s 1472 -W 1

Upgrade CentOS Password Hashing

authconfig --test | grep hashing
authconfig --passalgo=sha512 --update

Run echo cmd with sudo

for i in server;do echo $i; echo 'echo ""' >  /logs/test.log'|ssh $i sudo sh;done

Change percentage of root FS

tune2fs -m 0 /dev/sdc1

Disable Ipv6 on CentOS

echo "alias net-pf-10 off" >/etc/modprobe.conf
echo "alias ipv6 off" >>/etc/modprobe.conf
chkconfig ip6tables off
sed -i 's/NETWORKING_IPV6=yes/NETWORKING_IPV6=no/g' /etc/sysconfig/network

Fix chmod -x chmod

perl -e 'chmod 0755, "/bin/chmod"'
python -c 'import os; os.chmod("chmod", 0755)'


cp /bin/sh ~/chmod2
cat /bin/chmod > ~/chmod2
sudo ~/chmod2 +x /bin/chmod
rm ~/chmod2


sudo apt-get --reinstall install `dpkg -S /bin/chmod | cut -f1 -d:`

gcc -x c - <<CHMOD
#include <sys/stat.h>
main(){chmod("/bin/chmod", S_IXUSR | S_IXGRP | S_IXOTH);}
sudo ./a.out
rm a.out


/lib/ld-linux-x86-64.so.2 /bin/chown +x /bin/chown

Get webserver http code answer

wget --server-response -T 5 -t 1 http://ya.ru 2>&1 | awk '/^  HTTP/{print $2}'

Clone disk with DD by network

dd if=/dev/sdd1 bs=1M | ssh -c arcfour user@server "dd of=/dev/sdf1 bs=1M" ; echo "dd of disk1@server1 is finished" | mail -s "DD_CLONE" adm@server.net

disk with errors
dd if=/dev/sdd1 bs=1M conv=sync,noerror | ssh -c arcfour user@server "dd of=/dev/sdd1 bs=1M"

use nc
dd if=/dev/sde1 bs=1M | nc newserver 7000
nc -l 7000 | dd of=/dev/sde1 bs=1M

SSH x11 forwarding

yum install xorg-x11-xauth
apt-get install xauth
ssh -X

Extract RPM pkg

rpm2cpio myrpmfile.rpm | cpio -idmv

Create FFS snapshot

mksnap_ffs /www/.snap/1
mdconfig -a -t vnode -o readonly -f /www/.snap/1
mount -o ro /dev/md0 /mnt/
umount -f /mnt
mdconfig -d -u /dev/md0
rm -f /www/.snap/1

Exim cli commands

# remove from queue frozen messages
exiqgrep -z -i|xargs exim -Mrm
exipick -zi | xargs exim4 -Mrm
exim -bp | awk '$6~"frozen" { print $3 }' | xargs exim -Mrm
# view a message's headers
exim -Mvh <message-id>
# view a message's body
exim -Mvb <message-id>
# remove from queue messages older than week
exipick -io 86400 | xargs exim4 -Mrm
# remove all messages from queue
exipick -i | xargs exim4 -Mrm
# remove message by ID
exim -v -Mrm ID
# frozen message by email
exiqgrep -i -f email | xargs exim -Mf
# remove messages by email
exiqgrep -i -f email | xargs exim -Mrm

Clean Postfix queue

mailq|grep 'MAILER-DAEMON'|awk '{print $1}'|postsuper -d -

Find all notpkgs files FreeBSD

find /usr/local -type f | xargs -J% pkg_which -v "%" |  fgrep '?'

Display real LVM block devices

lvdisplay| awk '/LV Name/{n=$3} /Block device/{d=$3; sub(".*:","dm-",d); print d,n;}'
lvdisplay| awk '/LV Name/{blockdev=$3} /Block device/{bdid=$3; sub("[0-9]*:","dm-",bdid); print bdid,blockdev;}'

Mount ISO in FreeBSD

mdconfig -a -t vnode -f image.iso -u 0
mount -t cd9660 -o ro /dev/md0 /mount_point
umount /mount_point
mdconfig -d -u 0

Cisco CSS 1501 Tacacs

virtual authentication primary tacacs
virtual authentication secondary local
tacacs-server authorize config
tacacs-server authorize non-config
tacacs-server account non-config
tacacs-server account config
tacacs-server X.X.X.X primary frequency 10
tacacs-server key SecretKeyCisco

Show FreeBSD kernel config

sysctl -b kern.conftxt

HTTP redirect with HTML and JavaScript

<title>301 moved permanently</title>
<meta name="robots" content="noindex">
<meta http-equiv="refresh" content="0; url=http://example.ru/goto.html">
<!-- <a href="http://example.ru/goto.html">Moved permanently</a> -->
<script type="text/javascript"><!--
document.location = "http://example.ru/goto.html";
// --></script>