Search This Blog

Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Saturday, May 17, 2014

Linux Bash cheat sheet

I've spend some time googling for bash shortcats using phrases like: bash readline shortcat, copy and paste text to bash clipboard, etc  ... I always forget how to do this, especially when I don't work on Linux for a while.

Below is a list of my favorite (hard to remember) bash shortcats and tricks I like to use.

Bash shortcats

Ctrl + w  Cut the Word before the cursor to the clipboard
Ctrl + y  Paste the last thing to be cut (yank)
Alt + r  Cancel the changes and put back the line as it was in the history (revert).

Bash tricks to speed up typing 
  • How to copy the last command 
  • How to copy and paste the last command output
This one is my favorite because it allows me to refer to a previous command output text without having to copy and paste it with mouse.

# readline function
shell-expand-line (M-C-e)

Example 1:
$ myvar="/etc/passwd"
$ echo $myvar
$ ls $(echo $myvar)

Before you press enter press now (M-C-e) and the line will turn into

ls /etc/passwd-rrr

Example 2:
$ ls -l /etc/passwd
$ echo !!

Before you press enter press now (M-C-e) and the line will turn into

echo ls -l /etc/passwd

Example 3:

$ ls -l /etc/passwd
$ echo $(!!)

Before you press enter press now (M-C-e) and the line will turn into

echo -rw-r--r-- 1 root root 1399 May 17 02:19 /etc/passwd

References

http://ss64.com/bash/syntax-keyboard.html
http://superuser.com/questions/304519/how-to-copy-the-results-from-a-grep-command-to-the-bash-clipboard
http://superuser.com/questions/421463/why-does-ctrl-v-notpaste-in-bash-linux-shell
http://unix.stackexchange.com/questions/15850/how-to-use-keyboard-instead-of-mouse-middle-click-for-copy-paste
http://stackoverflow.com/questions/749544/pipe-to-from-clipboard
https://wiki.archlinux.org/index.php/Keyboard_Shortcuts
http://rtomaszewski.blogspot.co.uk/2013/06/linux-and-bash-cheat-sheet.html



Sunday, April 27, 2014

You can use bash shell instead of Cisco CLI on Nexus Switches

Every one who works on Linux and understand how to efficiently use Bash hates to work with the limited Cisco IOS CLI. The design objectives standing behind this CLI haven't changed for the last 20 years or so. It is obvious that this tools lacks plenty of features expected from a modern shell for many people.

But the evolution or even revolution that is happening in networking thanks to SDN is changing this terrible static network configuration landscape. The new generation of network devises like Cisco Nexus platform are going to support in the Cisco NX-OS :
  • Bash shell
  • Python shell 
  • API access
  • Linux containers for custom applications
For these who still don't believe you can read about this here:

References

http://www.cisco.com/c/en/us/products/switches/nexus-9000-series-switches/white-paper-listing.html
http://rtomaszewski.blogspot.co.uk/search/label/sdn
http://rtomaszewski.blogspot.co.uk/2013/09/cisco-cheat-sheet.html

Sunday, March 30, 2014

How to automatically prefill command on the Linux bash

Linux Bash is one of the most famous Linux shells. It offers a great number of features like for example spawning and controlling process, redirecting streams, supporting scripts and a flexible way to control you editing line.

Problem

How to automatically pre-populate a command on the shell after prompt.

Solution description

The shell has tree default streams: stdout, stdin and stderr. By manipulating the stdin of the process we can simulate typing a command.

Reference implementation

The original script can be found here: https://github.com/rtomaszewski/experiments/blob/master/type-command.c

Demonstration
  • Compile first the program
gcc -o type-command type-command.c
  • Run for the firs time
# ./type-command
type-command: the variable TYPE_CMD_ENABLED is not set, set it to 'no' to surpress this message; set the TYPE_CMD_TYPE for the command to type

Example: export TYPE_CMD_ENABLED=yes; export TYPE_CMD_TYPE=date
  • Export the variable to controls if the program should try to type a command or not
# export TYPE_CMD_ENABLED=yes
# ./type-command
#
  • Specify the command that you wish to be typed
# export TYPE_CMD_ENABLED=yes; export TYPE_CMD_TYPE=date
# ./type-command
# date
Sun Mar 30 19:27:55 UTC 2014>

References

http://stackoverflow.com/questions/10866005/bash-how-to-prefill-command-line-input
http://stackoverflow.com/questions/11198603/inject-keystroke-to-different-process-using-bash
http://unix.stackexchange.com/questions/48103/construct-a-command-by-putting-a-string-into-a-tty

http://fossies.org/linux/misc/old/console-tools-0.3.3.tar.gz%3at/console-tools-0.3.3/vttools/writevt.c

http://man7.org/linux/man-pages/man4/tty_ioctl.4.html
http://man7.org/linux/man-pages/man3/tcflush.3.html
http://www.tldp.org/LDP/lpg/node143.html

Sunday, January 5, 2014

How to divide and split file a part based on regex

We have a following file.
 
# cat text-to-split.txt
       1  aaa
       2  b1
       3  bb2
       4  bbb3
       5  c
       6  c1
       7  cc2
       8  aaa
       9  b1
      10  bb2
      11  c
      12  c1
      13  cc2
      14  aaa
      15  b1
      16  c
      17  cc2
      18  aaa
      19  b1
      20  aaa
      21  c1
      22  ccc

Problem

How to split and divide file based on its content?

Analisis and results description

Example 1 : Single split line in whole file

The file will be divided on each line matching a single patter.
 
# csplit -k text-to-split.txt '%aaa%' '/aaa/' '{*}'
74
62
41
22
35
root@perf1:~/split# for i in xx0*; do echo $i; cat -n $i; done
xx00
     1       1  aaa
     2       2  b1
     3       3  bb2
     4       4  bbb3
     5       5  c
     6       6  c1
     7       7  cc2
xx01
     1       8  aaa
     2       9  b1
     3      10  bb2
     4      11  c
     5      12  c1
     6      13  cc2
xx02
     1      14  aaa
     2      15  b1
     3      16  c
     4      17  cc2
xx03
     1      18  aaa
     2      19  b1
xx04
     1      20  aaa
     2      21  c1
     3      22  ccc

Example 2 : multiple split line

The csplit takes a variable number of regular expressions.
It scans the file and once a line matches the regex it splits the file at this point.
It evaluates then the next regular expression and continue to scan remaining file data.
When a match is found the file is split at this point again.
The last regex is used to split the remaining file until we read EOF.

In this example we:
  • Jump to line containing b1 (don't copy and save the data - %)
  • Continue searching for aaa and split when found.
  • Continue searching for c1 and split when found.
  • Use the last regex (c1) if file still have data.
csplit -k text-to-split.txt '%b1%' '/aaa/' '/c1/' '{*}'
63
41
96
23
root@perf1:~/split# for i in xx0*; do echo $i; cat -n $i; done
xx00
     1       2  b1
     2       3  bb2
     3       4  bbb3
     4       5  c
     5       6  c1
     6       7  cc2
xx01
     1       8  aaa
     2       9  b1
     3      10  bb2
     4      11  c
xx02
     1      12  c1
     2      13  cc2
     3      14  aaa
     4      15  b1
     5      16  c
     6      17  cc2
     7      18  aaa
     8      19  b1
     9      20  aaa
xx03
     1      21  c1
     2      22  ccc

References

http://rtomaszewski.blogspot.co.uk/2013/05/openssl-cheat-sheet.html

Wednesday, December 25, 2013

Howto pause bash loop execution and wait for any key

Problem

Howto pause bash loop execution and wait for any key (like ENTER for example) from user when running the script.
 
root@mongo2:~/tmp.loop# find -name '.bash*' | while read myfile; do echo "my variable is $myfile"; done
my variable is ./.bashrc
my variable is ./.bashrc_rado
my variable is ./.bash_history
my variable is ./.bash_tmp

Solution description and demonstration

We can use the standard 'read' bash built-in function (man bash). The problem is that it reads by default from the standard in (stdin, file descriptor 0).

We can use file redirection feature in bash to workaround this. Instead of reading from the stdin we can instruct the read to read from a different descriptor.
 
$echo -n 'ello' | ( read a; read -u1 b ; echo "1st read : - $a -"; echo "2th read : = $b =" )
test
1st read : - ello -
2th read : = test =

Unsuccessful version 1 showing the problem (read consumes our file names):
 
root@mongo2:~/tmp.loop# find -name '.bash*' | while read myfile; do echo "my variable is $myfile"; read ; done
my variable is ./.bashrc
my variable is ./.bash_history

Final solution (we press ENTER every time it pauses):
 
root@mongo2:~/tmp.loop# find -name '.bash*' | while read myfile; do echo "my variable is $myfile"; read -u1 ; done                     23:48
my variable is ./.bashrc

my variable is ./.bashrc_rado

my variable is ./.bash_history

my variable is ./.bash_tmp

References

http://www.catonmat.net/blog/bash-one-liners-explained-part-three/
http://www.tldp.org/LDP/abs/html/index.html
http://www.catonmat.net/download/bash-redirections-cheat-sheet.pdf


Sunday, October 27, 2013

Home directory and dotfiles management

In Linux you can customize your environment by creating custom aliases and various scripts. After some time this flexibility becomes difficult to managed if you work on many different machines. And if some of the hosts are cloud servers that are being deleted and recreated setting up your home directory can become a boring and annoying task.

Problem

How to customize and maintain your home directory config files on many servers.

Solution
  1. Create a repository for your configs on github. You can track your config files in a repository like mine: dotfiles on github. There are many existing repositories that that you can clone or simply reuse.
  2. On the server/cloud server install https://github.com/andsens/homeshick. This bash script will help us to maintain the config files.
  3. Download your dotfiles (config files) repository on the server
  4. Install it in your home directory
  5. Add the customization to .bashrc file

References

https://github.com/rtomaszewski/dotfiles
https://github.com/andsens/homeshick
http://dotfiles.github.io/

Wednesday, June 19, 2013

F5 Network BigIp cheat sheet

This post is a work in progress...
  • How to generate a list with one self ip and vlans per line 
# tmsh list /net self  | egrep 'self|vlan' | xargs -n 6 echo
net self 10.2.2.2/30 { vlan FAILOVER
net self 10.176.30.100/19 { vlan hybridServiceNet-140
net self 10.176.30.102/19 { vlan hybridServiceNet-140
net self 10.176.94.132/19 { vlan hybridServiceNet-142

Or 


# tmsh list net self | egrep -v 'floating|unit|allow-service' | xargs -n 7
net self 10.178.191.49/18 { vlan rackconnect110 }
net self 10.179.63.181/18 { vlan rackconnect112 }


  • How to simulate F5 health check requests with empty Host header
  • How to parse tmsh output
http://rtomaszewski.blogspot.co.uk/2013/07/ways-to-parse-tmsh-output-and-automate.html

Monday, June 17, 2013

Tables in Bash

There are many situation where a simple Bash script is more than enough to get a job done. But as much as I like Bash its primitive and quite sensitive syntax make me think twice before I code something more complex. Below is a nice trick I found how to deal with tables in Bash.

The most up to date gist can be found here: https://gist.github.com/rtomaszewski/5799274
 
#!/bin/bash
 
TESTS[0]=a,b,c
TESTS[1]=1,2,3
 
for row in "${TESTS[@]}"; do
    IFS=","
    set $row
    col1=$1
    col2=$2
    col3=$3
 
    echo "row was: $row"
    echo "col1 is $col1, col2 is $col2, col3 is $col3"
done

Openstack or Linux or bash cheat sheet

This post is a work in progress.
  • How to generate a list of commands base on input list. 
Per one input line one output command
# echo a b c | xargs -n 1 echo 'this is ' 
this is  a
this is  b
this is  c

Practical demo of how to delete all your cloud servers
# nova --no-cache list | grep '[|]' | awk '{print $2}' | tail -n +2 | xargs -n1 echo nova delete
nova delete 0dafascd-e7e5-4531-9542-25132338a3fc
nova delete ffasff56-ef5a-42e8-aa96-594d14538def
nova delete ad509afa-0cc8-111b-a681-7c56cc354957
nova delete b9bfafaf-073d-4732-a9c0-2e6720938357
  • Testing if you can establish a TCP session
$ nc -v -p 1185 92.52.111.222 80
Connection to 92.52.111.222 80 port [tcp/http] succeeded!
  • some of the useful CLIs
fold - Filter for folding lines. This breaks the lines to have a maximum of x width column position (or bytes).
column - columnate lists

  • How to check TCP / UDP network and socket statistics 
export file=/tmp/netstat.txt
netstat  -nntulpa &> $file

cat $file | grep tcp | awk ' { print $6 } ' | sort | uniq
cat $file 2 | grep udp

cat $file | grep tcp | awk ' { print $6 } ' | sort | uniq
CLOSE_WAIT
CLOSING
ESTABLISHED
FIN_WAIT1
FIN_WAIT2
LAST_ACK
LISTEN
SYN_RECV
SYN_SENT
TIME_WAIT

cat $file | grep tcp | awk ' { print $6 } ' | sort | uniq | while read STATE; do echo $STATE; grep $STATE $file | wc -l; done
CLOSE_WAIT
2
CLOSING
8
ESTABLISHED
53
FIN_WAIT1
15
FIN_WAIT2
0
LAST_ACK
136
LISTEN
20
SYN_RECV
166
SYN_SENT
0
TIME_WAIT
2

Other useful links: link1link2link3
  • How to sort files based on file size 
$ find . -mount -type f -ls|sort -rnk7 |head -30|awk '{printf "%10d MB\t%s\n",($7/1024)/1024,$NF}'

        52 MB   ./lib/libwireshark.so.2.0.2
        17 MB   ./lib/x86_64-linux-gnu/libicudata.so.48.1.1

  • How to cat and highlight a word in text
$ cat file | egrep --color=always "pattern|$"
$echo -n 'ello' | ( read a; read -u1 b ; echo "1st read : - $a -"; echo "2th read : = $b =" )
test
1st read : - ello -
2th read : = test =
  • How to truncated and shrink the text output to your terminal screen width
$ tcpdump -l -s0 -nn -i 0.0 'host 192.168.99.126 and port 443 and ( tcp[13]=2 )' | cut -c -$(tput cols)

  • How to print a file without the first line

  • $ cat tmp1
    a1
    a2
    a3
    a4
    

    Remove the fist line
    $ cat tmp1 | tail -n+2
    a2
    a3
    a4
    

    Remove the line #2 and #3
    cat tmp1 | sed '2,3d'
    a1
    a4
    

    Remove the first 2 lines
    $ cat tmp1 | tail -n+3
    a3
    a4
    

  • How to extract IP address from tcpdump output

  • $ tcpdump -nr attack.log
    21:35:49.553423 IP 162.13.0.27.22 > 82.44.149.5.51227: Flags [P.], seq 567291273:567291325, ack 2916928547, win 312, length 52
    21:35:49.573227 IP 82.44.149.5.51227 > 162.13.0.27.22: Flags [.], ack 52, win 16516, length 0
    

    Extract source IP and port
    $ tcpdump -nr attack.log | tmp.xt |awk '{print $3}'
    162.13.0.27.22
    82.44.149.5.51227
    

    Strip of the port number
    $ tcpdump -nr attack.log | awk '{print $3}' | grep -oE '[0-9]{1,}\.[0-9]{1,}\.[0-9]{1,}\.[0-9]{1,}'
    162.13.0.27
    82.44.149.5
    
  • How to count strings in a text using awk
$ cat  | awk '  { count+=NF } END { print count;}'
1 2 aaaa :rrr :ddjf -dd rrd ccc zz
1 2 3 4 444; -d df
16

Wednesday, April 24, 2013

How to find your public ip from bash

There are many sites that can show you your current public IP. But only a few of them are designed in a way so you can interact with them from command line using curl for example.

Below is a nice and elegant way to find out your public IP using curl
 
alias myip='curl --silent checkip.dyndns.org | egrep --only-matching "[0-9\.]+"'

root@server:~# myip
1.79.21.123

References
  1. https://github.com/pex/config/blob/master/bash/shortcuts.sh
  2. https://github.com/rtomaszewski/dotfiles
  3. http://dotfiles.github.io/

Friday, April 5, 2013

Powershell tutorial for Linux users

Powershell vs bash Linux commands
Description Linux Bash Powershell
list all available commands Tab Tab gcm
multiple commands with a name foo type -a foo gcm foo
print PATH variable  echo $PATH  echo $env:path
print PATH variable  echo $PATH  echo $env:path
set or export a variable export VARIABLE="foo" $env:VARIABLE="foo"
bash navigation shortcuts - Tab
- history
- Control+U
-Control+K
-Alt+B/Control left
-Alt+F/Control right
- Control+R

- [Tab] Autocomplete folder/file name.
- F7 Show history of previous commands
- F9 Run a specific command from the command history.
- Ctrl Home Erase line to the left.
- Ctrl End  Erase line to the right.
- Ctrl arrow left Move one word to the left (backward)
- Ctrl arrow right Move one word to the right (forward)
- F8 Move backwards through the command history, but only display
commands matching the current text at the command prompt.

References
  1. http://technet.microsoft.com/en-us/library/hh849711.aspx
  2. http://ss64.com/nt/syntax-keyboard.html
  3. http://technet.microsoft.com/en-us/library/ff730964.aspx

Wednesday, April 3, 2013

Powershell as Bash substitute on Windows

In Linux we have Bash shell that can be used to interact with the system or help to execute routine commands. There are couple of other alternatives in Windows. The cmd.exe is one of the interpreters that comes with every Windows since years.

A new one I'm learning is powershell.exe. The good part about powershell is that it provides many commands like in Linux that have the same name buy maybe a slightly different syntax  For a nice comparison list between the standard bash and powershell commands please take a look at BASH and PowerShell Quick Reference.

Problem

What is the Linux Path variable in powershell.

Solution

The variable is called $env:path.
 
PS C:\Users\radoslaw> echo $env:path
%SystemRoot%\system32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\AMD APP\bi
n\x86_64;C:\Program Files (x86)\AMD APP\bin\x86;C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
 Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files (x86)\Git\cm
d;c:\Python27;c:\HP\DriveKey;C:\Program Files (x86)\PuTTY;C:\Ruby193\bin

You can modify it when navigating to:
Start - Computer - Properties - Advance system settings - Advanced-Environment Variables -System variables - Path
Problem

How to use 'curl' from powershell.

Solution

You can install cygwin on Windows. Add to the system PATH the cygwin bin directory. Alternatively you can use this command below to download a file.

 
PS C:\Users\radoslaw\tmp> (New-Object System.Net.WebClient).DownloadFile("http://python-distribute.org/distribute_setup.py", "tmp\distribute_setup.py")
PS C:\Users\radoslaw\tmp> ls

    Directory: C:\Users\radoslaw\tmp

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          4/3/2013   9:12 PM      17319 distribute_setup.py
-a---          4/3/2013   8:20 PM      85929 get-pip.py

References
  1. http://www.cs.wright.edu/~pmateti/Courses/233/Labs/Scripting/bashVsPowerShellTable.html

Tuesday, October 30, 2012

How to install parallel Linux tool on Ubuntu or Debian

Parallel is a quite new tool created under the GNU foundation  As its name says it helps to execute jobs in parallel on one or many computers.

Problem

How to install parallel tool on Ubuntu 12.04 Precise [2]

Solution

As the package hasn't been debianised in Ubuntu yet we have to install it using the old school methods.

Follow link [3] and download the appropriate package. Once downloaded install it using dpkg.

wget http://download.opensuse.org/repositories/home:/tange/xUbuntu_12.04/all/parallel_20110422-1_all.deb
dpkg -i parallel_20110422-1_all.deb
type  -a parallel                                                                       22:51:35
parallel is /usr/bin/parallel

References
  1. http://www.gnu.org/software/parallel/
  2. https://wiki.ubuntu.com/DevelopmentCodeNames
  3. https://build.opensuse.org/package/show?package=parallel&project=home%3Atange

Tuesday, August 14, 2012

How to terminate a ssh session to a cloud server that hanged

When working with Rackspace cloud serves you run sometimes to an issue with the remote ssh session that it hangs.

This is expected behavior. The session after some time of inactivity timeouts and in my case this led to my bash terminal session to hang. As I didn't want to terminate and close my  terminal to resolve this issue and as well as I wanted to keep my previuos log still available I was looking for a possible solution.

Solution

To terminate a hanged ssh session please type the following keys: [enter]~. 

Example 

root@mycloud:~# ~?
Supported escape sequences:
  ~.  - terminate connection (and any multiplexed sessions)
  ~B  - send a BREAK to the remote system
  ~C  - open a command line
  ~R  - Request rekey (SSH protocol 2 only)
  ~^Z - suspend ssh
  ~#  - list forwarded connections
  ~&  - background ssh (when waiting for connections to terminate)
  ~?  - this message
  ~~  - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)
# we waiting now for the session to timeout 
root@rctest:~#

# no press the magica keys :)
root@rctest:~# Connection to 83.138.183.15 closed.

References
  1. http://www.thelinuxblog.com/ssh-escape/

Sunday, July 29, 2012

How to clean and delete multiple cloud servers after a failed test

The best think about open cloud API is that it is easy accessible and can be easily scripted around. For exmaple during one of my tests I created multiple cloud servers but my job failed and didn't delete them before the exception was thrownd.

Problem

How to extract cloud server names from the log file and how to delted all of them from the accout.

$ python performance-single-cs.py-t 1 -s 25 -u user -k key  run | tee log.$(date +%s).txt
$ cat log*.txt
[ 1][  ] starting test nr 1, creating 25 cloud server, please wait ...
[ 1][ 1] created image: {'flavor': 1, 'image': 112, 'name': 'test7945'}
[ 1][ 2] created image: {'flavor': 1, 'image': 112, 'name': 'test7948'}
[ 1][ 3] created image: {'flavor': 1, 'image': 112, 'name': 'test7951'}
[ 1][ 4] created image: {'flavor': 1, 'image': 112, 'name': 'test7954'}
[ 1][ 5] created image: {'flavor': 1, 'image': 112, 'name': 'test7958'}
[ 1][ 6] created image: {'flavor': 1, 'image': 112, 'name': 'test7961'}
[ 1][ 7] created image: {'flavor': 1, 'image': 112, 'name': 'test7965'}
[ 1][ 8] created image: {'flavor': 1, 'image': 112, 'name': 'test7969'}
[ 1][ 9] created image: {'flavor': 1, 'image': 112, 'name': 'test7972'}
[ 1][10] created image: {'flavor': 1, 'image': 112, 'name': 'test7976'}
[ 1][11] created image: {'flavor': 1, 'image': 112, 'name': 'test8050'}
[ 1][12] created image: {'flavor': 1, 'image': 112, 'name': 'test8054'}
[ 1][13] created image: {'flavor': 1, 'image': 112, 'name': 'test8059'}
[ 1][14] created image: {'flavor': 1, 'image': 112, 'name': 'test8063'}
[ 1][15] created image: {'flavor': 1, 'image': 112, 'name': 'test8068'}
[ 1][16] created image: {'flavor': 1, 'image': 112, 'name': 'test8072'}
[ 1][17] created image: {'flavor': 1, 'image': 112, 'name': 'test8077'}
[ 1][18] created image: {'flavor': 1, 'image': 112, 'name': 'test8082'}
[ 1][19] created image: {'flavor': 1, 'image': 112, 'name': 'test8086'}
[ 1][20] created image: {'flavor': 1, 'image': 112, 'name': 'test8091'}
[ 1][21] created image: {'flavor': 1, 'image': 112, 'name': 'test8117'}
[ 1][22] created image: {'flavor': 1, 'image': 112, 'name': 'test8192'}
[ 1][23] created image: {'flavor': 1, 'image': 112, 'name': 'test8197'}
[ 1][24] created image: {'flavor': 1, 'image': 112, 'name': 'test8202'}
[ 1][25] created image: {'flavor': 1, 'image': 112, 'name': 'test8208'}
[ 1][ 1] cloud server build [test7945] created in 298.427304 seconds / 4.9737884 minutes
[ 1][ 2] cloud server build [test7948] created in 298.331735 seconds / 4.97219558333 minutes
[ 1][ 3] cloud server build [test7951] created in 298.268271 seconds / 4.97113785 minutes
[ 1][ 4] cloud server build [test7954] created in 298.469954 seconds / 4.97449923333 minutes
[ 1][ 5] cloud server build [test7958] created in 298.202301 seconds / 4.97003835 minutes
[ 1][ 6] cloud server build [test7961] created in 297.702382 seconds / 4.96170636667 minutes
[ 1][ 7] cloud server build [test7965] created in 298.051012 seconds / 4.96751686667 minutes
[ 1][ 8] cloud server build [test7969] created in 297.3658 seconds / 4.95609666667 minutes
[ 1][ 9] cloud server build [test7972] created in 296.993362 seconds / 4.94988936667 minutes
[ 1][10] cloud server build [test7976] created in 296.810522 seconds / 4.94684203333 minutes
[ 1][11] cloud server build [test8050] created in 226.269396 seconds / 3.7711566 minutes
[ 1][12] cloud server build [test8054] created in 226.051247 seconds / 3.76752078333 minutes
[ 1][14] cloud server build [test8063] created in 225.04139 seconds / 3.75068983333 minutes
[ 1][15] cloud server build [test8068] created in 224.326799 seconds / 3.73877998333 minutes
[ 1][16] cloud server build [test8072] created in 223.051956 seconds / 3.7175326 minutes
[ 1][17] cloud server build [test8077] created in 221.830032 seconds / 3.6971672 minutes
[ 1][18] cloud server build [test8082] created in 219.514883 seconds / 3.65858138333 minutes
[ 1][19] cloud server build [test8086] created in 218.35139 seconds / 3.63918983333 minutes
[ 1][20] cloud server build [test8091] created in 216.172884 seconds / 3.6028814 minutes
[ 1][21] cloud server build [test8117] created in 193.915105 seconds / 3.23191841667 minutes
[ 1][13] cloud server build [test8059] created in 328.421036 seconds / 5.47368393333 minutes
[ 1][22] cloud server build [test8192] created in 197.893329 seconds / 3.29822215 minutes
[ 1][23] cloud server build [test8197] created in 196.71745 seconds / 3.27862416667 minutes
[ 1][24] cloud server build [test8202] created in 263.305984 seconds / 4.38843306667 minutes
[ 1][25] cloud server build [test8208] created in 260.425359 seconds / 4.34042265 minutes

Solution

For a single log file

$ cat log.*.txt | grep "image':" | cut -d':' -f5 | tr '}' ' ' | grep -v created > tmp
echo > 'set -x' >  delete-all-cs.sh
cat tmp | xargs -I cs_name echo 'cloudservers --username user --apikey key delete cs_name' >> delete-all-cs.sh
bash delete-all-cs.sh

When we have multiple log files

$ cat << END > aux_script.sh
cat $1 | grep "image':" | cut -d':' -f5 | tr '}' ' ' | grep -v created > tmp
cat tmp | xargs -I cs_name echo 'cloudservers --username user --apikey key delete cs_name' >> delete-all-cs.sh
END

$ for i in log.*.txt ; do echo $i; ./aux_script.sh $i;  done
$ bash -x delete-all-cs.sh

Summary and results discussion

The solution with 'xargs' works pretty well for relatively small number of servers to delete. As each cloud server is deleted in a single cloudserver run there is no parallelism involved.

An interesting solution could be built with a help of a parallel tool [3]. It could allow us to execute multiple commands in parallel and achieve a much better timing results. Of course to make it work we would have to take into consideration the API limitations and design some workarounds it.

References
  1. https://github.com/rtomaszewski/cloud-performance
  2. http://www.cyberciti.biz/faq/linux-unix-bsd-xargs-construct- argument-lists-utility/
  3. https://savannah.gnu.org/projects/parallel/

Saturday, July 28, 2012

My python script buffers the output and it causes delays before the text appiers on the console

Linux bash is exelent tool for every day use. It allows you to combine tools and chain them toggethr to achieve remarkable results. As one of my favorite I use this one when testing:
$ python some_script.py | tee log.$(date +%s).txt 

Problem

The problem is that althoug I get all the output on the console it appers to be bufffered and I can't monitor the logs in live when my script runs. An example code can be seen below.
 
Solution

You have to tell python to stop buffering the data sent the the stream you are using (stdin, stdout, stderr). On on the way I found convenient is by using the command line '-u' options.

References

Friday, February 10, 2012

The ssh session to Rackspace Cloud Servers timeouts automaticaly and hangs


Problem description

After provisioning a Linux Rackspace Cloud Servers you can login to the server using ssh client.
If the ssh session is inactive for some time the underlying tcp session of the ssh connection will be automaticaly closed.

Impact

Often you work on the some server from multiple terminals or multiple ssh client sessions. When the ssh session timeouts you have to loggin again.

Depending on the ssh client you use the console output you had may be lost.

After logging again the bash history maybe lost.

Workaround

We can avoid the session to be terminated by trying to print something on the screen at a regular interval. The simple command below is going to manipulate the screen cursor position and prints a current data in the right bottom corner of the ssh session screen.

To execute it  for every new ssh session opened we have to cusomise the bash .profile config file.

cat >> .profile <<DONE
while true; do 
  tput sc 
  tput cup $(tput lines) $(tput cols)
  tput cub 8 
  echo -n $(date +%T)
  tput rc 
  sleep 30 
done & 
DONE

References

man terminfo
How to: Change / Setup bash custom prompt (PS1)
Colours and Cursor Movement With tput
http://bashish.sourceforge.net/

Sunday, January 1, 2012

One line Bash script debugging

Working on the Bash shell can be very effective. You can combine various command line programs and chain (pipe) them together to accomplish a bigger task. Sometimes you have to debug your one line scripts although.

When working on the CLI I wrote in a hurry a small command to find and check the value of the sched_autogroup_enabled Linux  kernel variable [1] under the proc file system.

To my first surprise it didn't work at all.

root@udesktop:/proc# find . -name \*sched\* 2>/dev/null  | grep -v [0-9]
root@udesktop:/proc# 

It is easy to find this file manualy and I did it. Below is the prove that the file exist that I was looking for.

root@udesktop:/proc# ls -la ./sys/kernel/sched_autogroup_enabled
-rw-r--r-- 1 root root 0 2012-01-01 21:38 ./sys/kernel/sched_autogroup_enabled

Problem
How to debug one line bash scripts. Or in general how to debug any bash script.

Solution
The problem is easy to see once we enable more verbose debug output from the Bash

root@udesktop:/proc# set -v -x
root@udesktop:/proc# find . -name \*sched\* 2>/dev/null  | grep -v [0-9]
find . -name \*sched\* 2>/dev/null  | grep -v [0-9]
+ find . -name '*sched*'
+ grep --color=auto -v 1 2 3 5 6 7 8 9

We see that the string '[0-9]' is extended by the bash before the command chain is actually executed.

Once we know that the problem is how our regular expression [2] is evaluated the fix is simple:

root@udesktop:/proc# find . -name \*sched\* 2>/dev/null  | grep -v '[0-9]'
find . -name \*sched\* 2>/dev/null  | grep -v '[0-9]'
+ find . -name '*sched*'
+ grep --color=auto -v '[0-9]'
./schedstat
./sched_debug
./sys/kernel/sched_child_runs_first
./sys/kernel/sched_min_granularity_ns
./sys/kernel/sched_latency_ns
./sys/kernel/sched_wakeup_granularity_ns
./sys/kernel/sched_tunable_scaling
./sys/kernel/sched_migration_cost
./sys/kernel/sched_nr_migrate
./sys/kernel/sched_time_avg
./sys/kernel/sched_shares_window
./sys/kernel/sched_rt_period_us
./sys/kernel/sched_rt_runtime_us
./sys/kernel/sched_compat_yield
./sys/kernel/sched_autogroup_enabled
./sys/kernel/sched_domain

References
[1]
Benefiting of sched_autogroup_enabled on the desktop
http://unix.stackexchange.com/questions/9069/benefiting-of-sched-autogroup-enabled-on-the-desktop

The ~200 Line Linux Kernel Patch That Does Wonders
http://www.phoronix.com/scan.php?page=article&item=linux_2637_video&num=1

[2]
Bash Reference Manual
http://www.gnu.org/software/bash/manual/bashref.html#Filename-Expansion

Debugging Bash scripts
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html

Friday, December 30, 2011

How effectively use Linux system tools to find out the default Linux kernel I/O scheduler

In many troubleshooting situation we overview and check large numbers of logs generated by one or another application. Kernel is nothing special here. The kernel log files can  usually be found under /var/log/kern.log.

Problem
How to find out and confirm all names of the used io kernel scheduler in the last several reboots.

Solution
$ zcat kern.log.3.gz  | egrep 'io scheduler.*\(default\)' 
Oct  8 22:20:16 udesktop kernel: [    0.888090] io scheduler cfq registered (default)
Oct 10 20:30:33 udesktop kernel: [    0.688367] io scheduler cfq registered (default)
Nov  3 23:31:05 udesktop kernel: [    0.872053] io scheduler cfq registered (default)

$ zcat kern.log.1.gz  | egrep 'io scheduler.*\(default\)' | sed -r 's/ +/ /g' | cut -d' ' -f10 | sort | uniq
cfg

Explanation
We first grep for the names of the configured io scheduler. Next we pars it trought sed to repalce all multi space string with a single space and at the end we cut of the scheduler name.

References
Choosing an I/O Scheduler for Red Hat® Enterprise Linux® 4 and the 2.6 Kernel
http://www.redhat.com/magazine/008jun05/features/schedulers/

Sunday, May 1, 2011

Howto capture and record the console screen output to a file on disk

The basic of capturing a data to a file require simple redirection or using of 'tee' program for example.

Examples:

$ ls -la > /var/tmp/output.ls.txt
$ ls -la | tee /var/tmp/output.ls.txt

But sometimes programs can be interactive or we simply want to capture all our session without to worry to redirect the stdout to a file.

The solution is to use the 'screen' tool.

Example #1: Screen basic usage

# to start the session with a name 'example' run
$screen -h
$screen -S example

# to leave the screen session type: CONTROL-a d
# you are placed back in the original shell

# to reattach to the created session
$ screen -ls
$ screen -r example

Example #1: Enable screen logging

The options '-L' instruct screen to create a log file that will capture all the commands output in the screen session.

$ screen -S logexample -L

# inside the screen session
$ echo 'some output'

# to leave the screen session type: CONTROL-a d

# this is the default log file for screen
$ ls -la screenlog.0

$ cat screenlog.0