Spawn multiple telnet with tcl and log the output separately

萝らか妹 提交于 2019-12-10 12:14:03

问题


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?


回答1:


Expect's logging support (i.e., what the log_file command controls) doesn't let you set different logging destinations for different spawn IDs. This means that the simplest mechanism for doing what you want is to run each of the expect sessions in a separate process, which shouldn't be too hard provided you don't use the interact command. (The idea of needing to interact with multiple remote sessions at once is a bit strange! By the time you've made it sensible by grafting in something like the screen program, you might as well be using separate expect scripts anyway.)

In the simplest case, your outer script can be just:

foreach host {foo.example.com bar.example.com grill.example.com} {
    exec expect myExpectScript.tcl $host >@stdout 2>@stderr &
}

(The >@stdout 2>@stderr & does “run in the background with stdout and stderr connected to the usual overall destinations.)

Things get quite a bit more complicated if you want to automatically hand information about between the expect sessions. I hope that simple is good enough…




回答2:


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 :)



来源:https://stackoverflow.com/questions/21508076/spawn-multiple-telnet-with-tcl-and-log-the-output-separately

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!