Search code examples
tclspawnlogfile

Spawn multiple telnet with tcl and log the output separately


I'm trying to telnet to multiple servers with spawn & i want to log the output of each in a separate files. If i use the spawn with 'logfile' then, it is logging into a same file. But i want to have it in different files. How to do this?


Solution

  • I have found something from the link

    http://www.highwind.se/?p=116

    LogScript.tcl

    #!/usr/bin/tclsh8.5
    
    package require Expect
    proc log_by_trace {array element op} {
        uplevel {
            global logfile
            set file $logfile($expect_out(spawn_id))
            puts -nonewline $file $expect_out(buffer)
        }
    }
    
    array set spawns {}
    array set logfile {}
    
    # Spawn 1
    spawn ./p1.sh
    set spawns(one) $spawn_id
    set logfile($spawn_id)  [open "./log1" w]
    
    # Spawn 2
    spawn ./p2.sh
    set spawns(two) $spawn_id
    
    set logfile($spawn_id)  [open "./log2" w]
    trace add variable expect_out(buffer) write log_by_trace
    
    proc flush_logs {} {
        global expect_out
        global spawns
        set timeout 1
        foreach {alias spawn_id} [array get spawns] {
            expect {
            -re ".+" {exp_continue -continue_timer}
            default {  }
            }
        }
    }
    exit -onexit flush_logs
    set timeout 5
    expect {
        -i $spawns(one) "P1:2" {puts "Spawn1 got 2"; exp_continue}
        -i $spawns(two) "P2:2" {puts "spawn2 got 2"; exp_continue}
    }
    

    p1.sh

    #!/bin/bash
    i=0
    
    while sleep 1; do
        echo P1:$i
        let i++
    done
    

    p2.sh

    #!/bin/bash
    i=0
    
    while sleep 1; do
        echo P2:$i
        let i++
    done
    

    It is working perfectly :)