Friday, April 27, 2018

How to list all IPs belongs to a specific company/origin

How to list all IPs belongs to a specific company

 whois -h whois.radb.net -- '-i origin AS35995' | grep -Eo "([0-9.]+){4}/[0-9]+"


Origin name can be found here:

https://centralops.net/co/DomainDossier.aspx

Wednesday, August 23, 2017

Monitor missed calls (Asterisk)

There is a way to monitor, if your employees are missing some calls by having this pretty simply script

/usr/local/sbin/vm-mailer.sh
#!/bin/bash

EXTEN=$1
CID=$2
TEST=0
EMAILTO="boss@compamy.com"
[ "$TEST" -gt 0 ] && EMAILTO='developer@freelancer.br'
mfile='/tmp/mail-ab'
if [ -z "$2" ] || [ -z "$1" ]
then
    exit 1
fi

echo "Hello!" > $mfile
echo "" >> $mfile
echo "There is missed call from $CID to extension $EXTEN" >> $mfile
echo "" >> $mfile
echo "If there is any voicemail has been left by the caller, it will be mailed you soon" >> $mfile
echo "" >> $mfile
echo "-----------" >> $mfile
echo "Best regards" >> $mfile

then just simply add to your dialplan of the local extensions

exten => _XXX,1,Dial(SIP/${EXTEN},15)
exten => _XXX,n,NoOp(Voicemail for ${EXTEN})
exten => _XXX,n,System(/usr/local/sbin/vm-mailer.sh ${EXTEN} ${CALLERID(num)}) <--ADD THIS
exten => _XXX,n,Voicemail(${EXTEN},u)
exten => _XXX,n,Hangup

it has to be added before Voicemail, otherwise a caller may hangup during before voicemail is complete.

Now you'll be receiving email once a call to any of your local extensions got missed. To switch it into developer mode set TEST=1

Sunday, September 25, 2016

remove php spammer script from hosting

First enable logging

i.e. simple edit your php.ini

mail.add_x_header = On
mail.log = /var/log/phpmail.log

/root/remove_mailers.sh script (add it to cron)

#!/bin/bash
date=$(date)
logfile="${0%%.*}.log"
logfile="/var/log/${logfile##*/}"

echo $date >> $logfile
    for i in $(grep "eval()'d code" /var/log/phpmail.log | grep -oP '(?<=\[).*?(?=\()'| sort | uniq)
    do
        #echo "Spam script found: $i"
        #echo "removing..."
        echo $i >> $logfile
        rm -f $i
    done

:> /var/log/phpmail.log


ggg

Sunday, January 17, 2016

vicidial is not sending calls to the agents

I have experienced recently an issue on system built from scratch (Centos 7) . The issue was:

Asterisk is dialing number from the list. In the cli you can see, that they are being answered and then they become dropped right away without attempting to be transferred to an agent

This thread helped me a lot:

http://www.vicidial.org/VICIDIALforum/viewtopic.php?p=25156



In my case all cpan perl modules were installed into /root directory, so they couldn't be seen by perl.  The solution is either to add '/root/perl5/lib/perl5/' to the perl PATH or just to rsync these into:

rsync -avz /root/perl5/lib/perl5/ /usr/local/lib64/perl5/


And dont forget to always check your root mail:

tail -f /var/mail/root 

Tuesday, January 5, 2016

grep exception

Grep all BUT not starting with "#" and ";"

grep "^[^#;]" smb.conf

Saturday, August 8, 2015

tw_cli replace HDD in the hard raid

convert ata.X to sdX device

 ls -l /sys/block/sd* | sed -e 's@.*-> \.\.@/sys@' -e 's@/host@ @' -e 's@/target.*/@ @'   \
| while read Path HostNum ID
   do
      echo ${ID}: $(cat $Path/host$HostNum/scsi_host/host$HostNum/unique_id) 
   done

Or more simple version
ls -l /sys/block/sd* | sed -e 's@.*-> \.\..*/ata@/ata@' -e 's@/host@ @' -e 's@/target.*/@ @'

Result:
# ls -l /sys/block/sd* | sed -e 's@.*-> \.\..*/ata@/ata@' -e 's@/host@ @' -e 's@/target.*/@ @'
/ata3 3 sda
/ata3 3 sdb
/ata4 4 sdc



http://serverfault.com/questions/244944/linux-ata-errors-translating-to-a-device-name#

Wednesday, August 5, 2015

Thursday, June 25, 2015

nmap: scanning for conficker


nmap -p139,445 --script p2p-conficker,smb-os-discovery,smb-check-vulns --script-args=smbuser=*****,smbpass=*****,checkconficker=1,safe=1 -T4 192.168.1.100-254

Bad results look like this


Nmap scan report for 192.168.1.253
Host is up (0.00018s latency).
PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds
MAC Address: 70:71:BC:0E:00:92 (Pegatron)

Host script results:
| smb-check-vulns:
|   MS08-067: CHECK DISABLED (add '--script-args=unsafe=1' to run)
|   Conficker: Likely INFECTED (by Conficker.C or lower)
|   regsvc DoS: CHECK DISABLED (add '--script-args=unsafe=1' to run)
|   SMBv2 DoS (CVE-2009-3103): CHECK DISABLED (add '--script-args=unsafe=1' to run)
|   MS06-025: CHECK DISABLED (add '--script-args=unsafe=1' to run)
|_  MS07-029: CHECK DISABLED (add '--script-args=unsafe=1' to run)
| smb-os-discovery:
|   OS: Windows XP (Windows 2000 LAN Manager)
|   OS CPE: cpe:/o:microsoft:windows_xp::-
|   Computer name: E10
|   NetBIOS computer name: E10
|   Workgroup: *********
|_  System time: 2015-06-26T02:06:02-07:00

Wednesday, June 3, 2015

How to match newlines in sed

Original: http://backreference.org/2009/12/23/how-to-match-newlines-in-sed/

Lots of sed newcomers ask why the following snippets of code, or some variation thereof, don't work (they actually work as expected; it's just that the results are not what they think should be):
# All these do NOT produce the expected result!
sed 's/\n//g'             # remove all newline characters
sed 's/PATTERN\n//        # if the line ends in PATTERN, join it with the next line
sed 's/FOO\nBAR/FOOBAR/'  # if a line ends in FOO and the next starts with BAR, join them
To understand why those "don't work", it's necessary to look at how sed reads its input.
Basically, sed reads only one line at a time and, unless you perform special actions, there is always a single input line in the pattern space at any time. That line does NOT have a trailing newline characters, because sed removes it. When the line is printed at the end of the cycle, sed adds back a newline character, but while the line is in the pattern buffer, there's simply no \n in it. Now it's easy to see why none of the above programs will do what you think: the lhs (left hand side) will never match what's in the pattern space, so no replacement will be performed. However, sed does add a newline when you ask it to perform certain commands.
So the next question is: how to do the things that the above programs wrongly attempted to do?
Three not-so well-known commands that are useful for these applications are NP and D.
  • N reads in another line of input and appends it to the current pattern space, separated by a newline;
  • P prints the contents of the pattern space, up to the first newline (or to the end if there is no newline);
  • D deletes the contents of the patterns space, up to the first newline (or to the end if there is no newline), and starts a new cycle. The latter means that any commands that come after the D in the sed program will not be executed if D itself is executed.
So let's put these commands to good use:
sed ':begin;$!N;s/\n//;tbegin'                   # deletes all newlines except the last; see also tr -d '\n'
sed ':begin;$!N;s/\n/ /;tbegin'                  # same as before, but replaces newlines with spaces; see also tr '\n' ' '
sed ':begin;$!N;s/\(PATTERN\)\n/\1/;tbegin;P;D'  # if the line ends in PATTERN, join it with the next line
sed ':begin;$!N;/PATTERN\n/s/\n//;tbegin;P;D'    # same as above
sed ':begin;$!N;s/FOO\nBAR/FOOBAR/;tbegin;P;D'   # if a line ends in FOO and the next starts with BAR, join them
The programs that join lines, above, keep joining lines as long as the conditions for joining with the next line are true. Note that the mentioned solutions based on trare not exactly equivalent, in that they will remove or replace the very last newline of the input too, meaning that the output won't be terminated by \n.
For more information, see the sed FAQ, especially this section, and the sed oneliners.

tcpdump tutorial from danielmiessler.com


tcpdump is the premier network analysis tool for information security professionals. Having a solid grasp of this über-powerful application is mandatory for anyone desiring a thorough understanding of TCP/IP. Many prefer to use higher level analysis tools such as EtherealWireshark, but I believe this to usually be a mistake.
In a discipline so dependent on a true understanding of concepts vs.rote learning, it's important to stay fluent in the underlying mechanics of the TCP/IP suite. A thorough grasp of these protocols allows one to troubleshoot at a level far beyond the average analyst, but mastery of the protocols is only possible through continued exposure to them.
When using a tool that displays network traffic a more natural (raw) way the burden of analysis is placed directly on the human rather than the application. This approach cultivates continued and elevated understanding of the TCP/IP suite, and for this reason I stronglyadvocate using tcpdump instead of other tools whenever possible.
15:31:34.079416 IP (tos 0x0, ttl  64, id 20244, offset 0, flags [DF], 
proto: TCP (6), length: 60) source.35970 > dest.80: S, cksum 0x0ac1 
(correct), 2647022145:2647022145(0) win 5840 0x0000:  4500 003c 4f14 4000 
4006 7417 0afb 0257  E..  0x0010:  4815 222a 8c82 0050 9dc6 5a41 0000 
0000  H."*...P..ZA....  0x0020:  a002 16d0 0ac1 0000 0204 05b4 
0402 080a  ................  0x0030:  14b4 1555 0000 0000 0103 0302

Options

Below are a few options (with examples) that will help you greatly when working with the tool. They're easy to forget and/or confuse with other types of filters, i.e. ethereal, so hopefully this page can serve as a reference for you, as it does me.
First off, I like to add a few options to the tcpdump command itself, depending on what I'm looking at. The first of these is -n, which requests that names are not resolved, resulting in the IPs themselves always being displayed. The second is -X, which displays both hex and ascii content within the packet. The final one is -S, which changes the display of sequence numbers to absolute rather than relative. The idea there is that you can't see weirdness in the sequence numbers if they're being hidden from you. Remember, the advantage of usingtcpdump vs. another tool is getting manual interaction with the packets.
It's also important to note that tcpdump only takes the first 68 96 bytes of data from a packet by default. If you would like to look at more, add the -s number option to the mix, where number is the number of bytes you want to capture. I recommend using 0 (zero) for a snaplength, which gets everything. Here's a short list of the options I use most:
  • -i any : Listen on all interfaces just to see if you're seeing any traffic.
  • -n : Don't resolve hostnames.
  • -nn : Don't resolve hostnames or port names.
  • -X : Show the packet's contents in both hex and ASCII.
  • -XX : Same as -X, but also shows the ethernet header.
  • -v, -vv, -vvv : Increase the amount of packet information you get back.
  • -c : Only get x number of packets and then stop.
  • -s : Define the snaplength (size) of the capture in bytes. Use -s0to get everything, unless you are intentionally capturing less.
  • -S : Print absolute sequence numbers.
  • -e : Get the ethernet header as well.
  • -q : Show less protocol information.
  • -E : Decrypt IPSEC traffic by providing an encryption key.
[ The default snaplength as of tcpdump 4.0 has changed from 68 bytes to 96 bytes. While this will give you more of a packet to see, it still won't get everything. Use-s 1514 to get full coverage ]

Basic Usage

So, based on the kind of traffic I'm looking for, I use a different combination of options to tcpdump, as can be seen below:
  1. Basic communication // see the basics without many options
    tcpdump -nS

  2. Basic communication (very verbose) // see a good amount of traffic, with verbosity and no name help
    tcpdump -nnvvS

  3. A deeper look at the traffic // adds -X for payload but doesn't grab any more of the packet
    tcpdump -nnvvXS
  4. Heavy packet viewing // the final "s" increases the snaplength, grabbing the whole packet
    tcpdump -nnvvXSs 1514
Here's a capture of exactly two (-c2ICMP packets (a ping and pong) using some of the options described above. Notice how much we see about each packet.
hermes root # tcpdump -nnvXSs 0 -c2 icmp
tcpdump: listening on eth0, link-type EN10MB (Ethernet), 23:11:10.370321 IP 
(tos 0x20, ttl  48, id 34859, offset 0, flags [none], length: 84) 
69.254.213.43 > 72.21.34.42: icmp 64: echo request seq 0

        0x0000:  4520 0054 882b 0000 3001 7cf5 45fe d52b  E..T.+..0.|.E..+
        0x0010:  4815 222a 0800 3530 272a 0000 25ff d744  H."*..50'*..%..D
        0x0020:  ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213  .^..............
        0x0030:  1415 1617 1819 1a1b 1c1d 1e1f 2021 2223  .............!"#
        0x0040:  2425 2627 2829 2a2b 2c2d 2e2f 3031 3233  $%&'()*+,-./0123
        0x0050:  3435 3637                                4567
23:11:10.370344 IP (tos 0x20, ttl  64, id 35612, offset 0, flags [none], 
length: 84) 72.21.34.42 > 69.254.213.43: icmp 64: echo reply seq 0
        0x0000:  4520 0054 8b1c 0000 4001 6a04 4815 222a  E..T....@.j.H."*
        0x0010:  45fe d52b 0000 3d30 272a 0000 25ff d744  E..+..=0'*..%..D
        0x0020:  ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213  .^..............
        0x0030:  1415 1617 1819 1a1b 1c1d 1e1f 2021 2223  .............!"#
        0x0040:  2425 2627 2829 2a2b 2c2d 2e2f 3031 3233  $%&'()*+,-./0123
        0x0050:  3435 3637                                4567
2 packets captured
2 packets received by filter
0 packets dropped by kernel
hermes root # 

Common Syntax

Expressions allow you to trim out various types of traffic and find exactly what you're looking for. Mastering the expressions and learning to combine them creatively is what makes one truly powerful with tcpdump. There are three main types of expression: typedir, andproto.
Type options are hostnet, and port. Direction is indicated by dir, and there you can have srcdstsrc or dst, and src and dst. Here are a few that you should definitely be comfortable with:
  • host // look for traffic based on IP address (also works with hostname if you're not using -n)
    tcpdump host 1.2.3.4

  • srcdst // find traffic from only a source or destination (eliminates one side of a host conversation)
    tcpdump src 2.3.4.5
    tcpdump dst 3.4.5.6

  • net // capture an entire network using CIDR notation
    tcpdump net 1.2.3.0/24

  • proto // works for tcp, udp, and icmp. Note that you don't have to type proto
    tcpdump icmp

  • port // see only traffic to or from a certain port
    tcpdump port 3389

  • src, dst port // filter based on the source or destination port
    tcpdump src port 1025
    tcpdump dst port 389

  • src/dst, port, protocol // combine all three
    tcpdump src port 1025 and tcp
    tcpdump udp and src port 53
You also have the option to filter by a range of ports instead of declaring them individually, and to only see packets that are above or below a certain size.
  • Port Ranges // see traffic to any port in a range
    tcpdump portrange 21-23

  • Packet Size Filter // only see packets below or above a certain size (in bytes)
    tcpdump less 32
    tcpdump greater 128
  • [ You can use the symbols for less thangreater than, and less than or equalgreater than or equal signs as well. ]
    // filtering for size using symbols
    tcpdump > 32
    tcpdump <= 128

Writing to a File

tcpdump allows you to send what you're capturing to a file for later use using the -w option, and then to read it back using the -r option. This is an excellent way to capture raw traffic and then run it through various tools later.
The traffic captured in this way is stored in tcpdump format, which is pretty much universal in the network analysis space. This means it can be read in by all sorts of tools, including WiresharkSnort, etc.

Capture all Port 80 Traffic to a File

tcpdump -s 1514 port 80 -w capture_file
Then, at some point in the future, you can then read the traffic back in like so:

Read Captured Traffic back into tcpdump

tcpdump -r capture_file

Getting Creative

Expressions are nice, but the real magic of tcpdump comes from the ability to combine them in creative ways in order to isolate exactly what you're looking for. There are three ways to do combinations, and if you've studied computers at all they'll be pretty familar to you:
  1. AND
    and or &&
  2. OR
    or or ||
  3. EXCEPT
    not or !

More Examples

# TCP traffic from 10.5.2.3 destined for port 3389
tcpdump -nnvvS and src 10.5.2.3 and dst port 3389
# Traffic originating from the 192.168 network headed for the 10 or 172.16 networks
tcpdump -nvX src net 192.168.0.0/16 and dst net 10.0.0.0/8 or172.16.0.0/16
# Non-ICMP traffic destined for 192.168.0.2 from the 172.16 network
tcpdump -nvvXSs 1514 dst 192.168.0.2 and src net and not icmp
# Traffic originating from Mars or Pluto that isn't to the SSH port
tcpdump -vv src mars and not dst port 22
As you can see, you can build queries to find just about anything you need. The key is to first figure out precisely what you're looking for and then to build the syntax to isolate that specific type of traffic.

Grouping

Also keep in mind that when you're building complex queries you might have to group your options using single quotes. Single quotes are used in order to tell tcpdump to ignore certain special characters -- in this case the "( )" brackets. This same technique can be used to group using other expressions such as hostportnet, etc. Take a look at the command below:
# Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22(incorrect)
tcpdump src 10.0.2.4 and (dst port 3389 or 22)
If you tried to run this otherwise very useful command, you'd get an error because of the parenthesis. You can either fix this by escaping the parenthesis (putting a \ before each one), or by putting the entire command within single quotes:
# Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22 (correct)
tcpdump 'src 10.0.2.4 and (dst port 3389 or 22)'

Advanced

You can also filter based on specific portions of a packet, as well as combine multiple conditions into groups. The former is useful when looking for only SYNs or RSTs, for example, and the latter for even more advanced traffic isolation.
[ Hint: An anagram for the TCP flags: Unskilled Attackers Pester Real SecurityFolk ]
Show me all URGENT (URG) packets...
# tcpdump 'tcp[13] & 32!=0'
Show me all ACKNOWLEDGE (ACK) packets...
# tcpdump 'tcp[13] & 16!=0'
Show me all PUSH (PSH) packets...
# tcpdump 'tcp[13] & 8!=0'
Show me all RESET (RST) packets...
# tcpdump 'tcp[13] & 4!=0'
Show me all SYNCHRONIZE (SYN) packets...
# tcpdump 'tcp[13] & 2!=0'
Show me all FINISH (FIN) packets...
# tcpdump 'tcp[13] & 1!=0'
Show me all SYNCHRONIZE/ACKNOWLEDGE (SYNACK) packets...
# tcpdump 'tcp[13]=18'
[ Note: Only the PSH, RST, SYN, and FIN flags are displayed in tcpdump's flag field output. URGs and ACKs are displayed, but they are shown elsewhere in the output rather than in the flags field ]
Keep in mind the reasons these filters work. The filters above find these various packets because tcp[13] looks at offset 13 in the TCP header, the number represents the location within the byte, and the !=0 means that the flag in question is set to 1, i.e. it's on.
As with most powerful tools, however, there are multiple ways to do things. The example below shows another way to capture packets with specific TCP flags set.
Capture TCP Flags Using the tcpflags Option...
# tcpdump 'tcp[tcpflags] & & tcp-syn != 0'

Specialized Traffic

Finally, there are a few quick recipes you'll want to remember for catching specific and specialized traffic, such as IPv6 and malformed/likely-malicious packets.
IPv6 traffic
# tcpdump ip6
Packets with both the RST and SYN flags set (why?)
# tcpdump 'tcp[13] = 6'
Traffic with the 'Evil Bit' Set
# tcpdump 'ip[6] & 128 != 0'

Conclusion

Well, this primer should get you going strong, but the man pageshould always be handy for the most advanced and one-off usage scenarios. I truly hope this has been useful to you, and feel free tocontact me if you have any questions. ::

Recommended

shutdown a windows PC with PHP

$runcmd="net rpc SHUTDOWN -C \"This system was left on a fter hours and is being shutdown\" -f -I \"".$ip."\" -U ".$ldap_id."%".$ldap_pas s." 2>&1 /dev/null"; 

Cisco 2691 ADSL configuration

Cisco 2691 ADSL config (worked with PLDT )

vpdn-group pppoe
request-dialin
protocol pppoe
!
interface ATM0/0
 description PLDT ADSL
 no ip address
 no atm ilmi-keepalive
 dsl operating-mode auto 
 hold-queue 224 in
!
interface ATM0/0.1 point-to-point
 pvc 0/100 
  pppoe-client dial-pool-number 1
!
interface Dialer0
 mtu 1492
 ip address  
 ip nat outside
 ip virtual-reassembly
 encapsulation ppp
 ip tcp adjust-mss 1436
 dialer pool 1
 no cdp enable
 ppp chap hostname <pldt pppoe username>
 ppp chap password 7 <pldt password>
 ppp pap sent-username <pldt pppoe username> password 0 <pldt password>


Thursday, April 23, 2015

Emergency password reset Dell powerconnect 3248

For the 3248/5212/5224 products:

Note: This password recovery procedure involves rebooting the switch to the Factory Defaults. This will cause the loss of any current configuration on the switch. 

   1. Connect to the switch via the console port and manually reboot the switch
   2. As soon as power is applied, press and hold the <Ctrl> and <F> keys simultaneously
   3. At the menu, press R for the "[R]eturn to Factory Default" option
   4. The switch will reboot and all configuration changes and password information is cleared

then log in using admin/admin

Wednesday, January 21, 2015

Centos 7 PXE diskless

The guide is here:
http://www.server-world.info/en/note?os=CentOS_6&p=pxe&f=4

But I have installed Centos7 Desktop on PC(workstation) and rsynced files over to the server

ssh <workstation>
mount /dev/sda1 /mnt
rsync -avz /mnt/ <server>:/tftpboot/<Diskless Centos pxe root>

Problems:

dracut fatal don't know how to handle root=nfs

A start job is running for dev-nfs.device

And others like this could be fixed by using vmlinuz and initrd from here

( according to linuxquestions.org )


Working config:

[root@fox pxelinux.cfg]# cat default
default centos7


label centos7
   kernel pxeboot/centos7/sda/boot/vmlinuz
   append initrd=pxeboot/centos7/sda/boot/initrd.img root=nfs:192.168.44.10:/tftpboot/pxeboot/centos7/sda ip=dhcp rw selinux=0

Here is how to install Gnome on Centos 7 after Base installation
http://www.itzgeek.com/how-tos/linux/centos-how-tos/install-gnome-gui-on-centos-7-rhel-7.html#axzz3PTQP15yP

you can do it after you have copied the files to the server:

chroot /tftpboot/<Diskless Centos pxe root> 
yum groupinstall "GNOME Desktop" "Graphical Administration Tools"

Wednesday, September 17, 2014

use vim as default editor

echo "export EDITOR=vim" >> ~/.bashrc && export EDITOR=vim

Tuesday, August 19, 2014

Modify all LDAP users in one shot

Once I need to reset login shell for all users. Here is easy solution, one simple loop

SAVEIFS=$IFS;
IFS=$(echo -en "\n\b");
for i in $(ldapsearch -h localhost -p 389 -D "cn=Manager,dc=<yourdomain>,dc=com" -w "<Manager's passwd>" -s sub -b  "ou=Users,dc=<yourdomain>,dc=com" | grep -v root | grep "dn:")
do
LDIF_FILE=/tmp/loginShell.ldif;
echo "${i}" > $LDIF_FILE;
echo "changetype: modify" >> $LDIF_FILE;
echo "replace: loginShell" >> $LDIF_FILE;
echo "loginShell: /usr/sbin/user_shell" >> $LDIF_FILE;
/usr/bin/ldapmodify -h localhost -p 389 -D "cn=Manager,dc=<yourdomain>,dc=com" -w "<Manager's passwd>" -f $LDIF_FILE;
done;
IFS=$SAVEIFS;


Of course, you can put instead of  loginShell any other parameters. Don't forget, to change multiply parameters put  '-' separator:

*****
        echo "replace: userPassword" >> $LDIF_FILE
        echo "userPassword: $PASSWD_SSHA" >> $LDIF_FILE
        echo "-" >> $LDIF_FILE
        echo "replace: sambaNTPassword" >> $LDIF_FILE
        echo "sambaNTPassword: $sambaNTPassword" >> $LDIF_FILE
  

Friday, August 15, 2014

Asterisk(Bash): watching agents on call/waiting in color

#!/bin/bash
clear
while true
do
buffer=$(
clear
/usr/sbin/asterisk -rx "show queue <My_Queue>" \
| grep Agent \
| grep -v \(Unavailable\) \
| sort -t"(" -k 2 \
| GREP_COLOR='01;31' egrep -i --color=always '^.*[0-9] \(Not in use.*$|$' \
| GREP_COLOR='01;32' egrep -i --color=always '^.*[0-9] \(Busy.*$|$' \
| GREP_COLOR='01;34' egrep -i --color=always '^.*\(paused.*$|$' )

echo "$buffer"
sleep 2
done

exit 0

Thursday, August 14, 2014

ZFS::chmod: changing permissions of Operation not permitted

Problem: 

I can't change a folder permissions running on NFS client:

chmod: changing permissions of <somedir>: Operation not permitted


But from ZFS/NAS server the command is working


Solutiom: 


You need to add no_root_squash to your /etc/exports

But if you are running ZFS, you'll need to set

#sharemgr set -P nfs -p anon=0 zfs/data

Where zfs/data is name of your pool
Then you can check:

#sharemgr show -vp

Output:
default nfs=()

zfs

    zfs/rpool nfs=()
          /rpool
    zfs/data nfs=(anon="0")
          /data

read more:
http://prefetch.net/blog/index.php/2009/05/05/using-sharemgr-to-manage-nfs-file-systems-on-opensolaris-hosts/

Monday, August 11, 2014

GREP: colored output

http://stackoverflow.com/questions/17236005/grep-output-with-multiple-colors

EXAMPLE:  Colored output from asterisk CLI

 asterisk -rvvvvvvv | GREP_COLOR='01;36' egrep --color=always '^.*answered SIP.*$|$' | GREP_COLOR='01;31' egrep -i --color=always '^.*Got SIP response.*$|$' | grep -E '(answered SIP|Got SIP response)'

Thursday, August 7, 2014

BASH Shell: For Loop File Names With Spaces

http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html

BASH for loop works nicely under UNIX / Linux / Windows and OS X while working on set of files. However, if you try to process a for loop on file name with spaces in them you are going to have some problem. For loop uses $IFS variable to determine what the field separators are. By default $IFS is set to the space character. There are multiple solutions to this problem.

Set $IFS variable

Try it as follows:
#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in *
do
  echo "$f"
done
IFS=$SAVEIFS
OR
#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
# set me
FILES=/data/*
for f in $FILES
do
  echo "$f"
done
# restore $IFS
IFS=$SAVEIFS

More examples using $IFS and while loop

Now you know that if the field delimiters are not whitespace, you can set IFS. For example, while loop can be used to get all fields from /etc/passwd file:
....
while IFS=: read userName passWord userID groupID geCos homeDir userShell
do
      echo "$userName -> $homeDir"
done < /etc/passwd

Using old good find command to process file names

To process the output of find with a command, try as follows:
find . -print0 | while read -d $'\0' file
do
  echo -v "$file"
done
Try to copy files to /tmp with spaces in a filename using find command and shell pipes:
find . -print0 | while read -d $'\0' file; do cp -v "$file" /tmp; done

Processing filenames using an array

Sometimes you need read a file into an array as one array element per line. Following script will read file names into an array and you can process each file using for loop. This is useful for complex tasks:
#!/bin/bash
DIR="$1"
 
# failsafe - fall back to current directory
[ "$DIR" == "" ] && DIR="."
 
# save and change IFS 
OLDIFS=$IFS
IFS=$'\n'
 
# read all file name into an array
fileArray=($(find $DIR -type f))
 
# restore it 
IFS=$OLDIFS
 
# get length of an array
tLen=${#fileArray[@]}
 
# use for loop read all filenames
for (( i=0; i<${tLen}; i++ ));
do
  echo "${fileArray[$i]}"
done

Playing mp3s with spaces in file names

Place following code in your ~/.bashrc file:
mp3(){
 local o=$IFS
 IFS=$(echo -en "\n\b")
 /usr/bin/beep-media-player "$(cat  $@)" &
 IFS=$o
}
Keep list of all mp3s in a text file such as follows (~/eng.mp3.txt):
/nas/english/Adriano Celentano - Susanna.mp3
/nas/english/Nick Cave & Kylie Minogue - Where The Wild Roses Grow.mp3
/nas/english/Roberta Flack - Kiling Me Softly With This Song.mp3
/nas/english/The Beatles - Girl.mp3
/nas/english/John Lennon - Stand By Me.mp3
/nas/english/The Seatbelts, Cowboy Bebop - 01-Tank.mp3
To play just type:
$ mp3 eng.mp3.txt