Sunday, January 27, 2013

putty+screen: Close your putty session, without terminating the running script

Normally we connect to a remote UNIX (Linux) servers through putty. But when we disconnect a putty session, the remote shell terminates, as a result if any running script/command will end immediately.

How to continue running a script/command in putty even after closing the session?
You can use the 'screen' command, which will be available by default in most of the Linux distributions.

Screen command
  Screen command offers the ability to detach a long running process (or program, or shell-script) from a session and then attach it back at a later time.
  When the session is detached, the process that was originally started from the screen is still running and managed by the screen. You can then re-attach the session at a later time, and your terminals are still there, the way you left them.

Step by step guide
1) Login to a remote server, either through putty or secureshell.
2) Open a new screen session
     screen -S screen-name 
     Ex:   screen -S TestScreen
3) Start your command/script
     Ex: Run the below command, which will run for approx 1 min 40 secs.
     for (( c=1; c<=100;c++)) 
     do 
             echo "Hello $c"
              sleep 5
     done
4) Disconnect the current session by pressing CTRL + A + D ( or close your putty session) . Don't exit ( never run the command 'exit' or CTRL+C, CTRL+D).  

5) To check the status of previous command, open a new putty session. After login, type the below command
     screen -d -r TestScreen
     where 
        -r : Reattach to a detached screen process.
        -d: Detach the elsewhere running screen (and reattach here).
This will connect back you to the previous session and monitor the progress of your script. Again if command is not complete, don't exit.  Press CTRL A D or just close the putty session and proceed for other tasks.

     If you got only one screen session, you can also use below command to connect to it.
     screen -x TestScreen

6) Creating multiple screen tabs
     Ctrl + AC

7) Switching between screen tabs
    Ctrl + AN     ---> Switch to next tab
    Ctrl + AP      ---> Switch to previous tab
    Ctrl + AA     ---> Switch between your last 2 tabs

Note: You can use VNC sessions for the same functionality and also Citrix provides it. 
   The screen command will be useful if
      1) You don't have the commercial Citrix tool  
      2) Sometimes configuring VNC gives lots of issue. Instead of spending time on fixing this issue, you can quickly achieve this functionality using screen command. I personally still prefer VNC sessions. 

No comments: