tck/tl 以及expect脚本

最近有用到,利用expcet脚本自动登录到远程服务器并提权执行脚本。

搜集的知识如下:

tcl/tk参考——列表操作lindex

 expect脚本解释

代码如下

#!/usr/bin/expect --
if { $argc != 6 && $argc != 7 } { exit 20 }
set ip        [lindex $argv 0]
set port    [lindex $argv 1]
set proto    [lindex $argv 2] ;#0:ssh;1:telnet
set user    [lindex $argv 3]
set pwd        [binary format H* [lindex $argv 4]]
set cmds     [lindex $argv 5]

if { $argc == 7 } {
    set root_pwd [binary format H* [lindex $argv 6]]
    puts "root_pwd:$root_pwd"
}

puts
"ip:$ip";一些输出方便观察 puts "port:$port" puts "proto:$proto" puts "user:$user" puts "pwd:$pwd" puts "cmds:$cmds" set timeout 30;设置超时 #set default client set ssh "/usr/bin/ssh" #set default promptions set login_pmt "ogin:" set pwd_pmt "assword:" set user_pmt "$ " set root_pmt "# " set login_fail_pmt "error" set elevation_cmd "su -" set elevation_pmt "assword:" set elevation_ok_pmt "$root_pmt" set elevation_failed_pmt "$user_pmt" ;把$符号转义一下 if { $user_pmt == "$" } { set user_pmt "$" } if { $root_pmt == "$" } { set root_pmt "$" } #puts "login_ont is $login_pmt"
;函数 proc handle_cmds { } { global cmds user_pmt set hex_cmds [split $cmds
"|"] puts "into handle_cmds" foreach hex_cmd $hex_cmds { set cmd [binary format H* $hex_cmd] send -- "$cmd " expect { "$user_pmt" { } "not found" { } eof { exit 4} timeout { exit 5} } } } proc handle_cmds_root { } { global cmds root_pmt set hex_cmds [split $cmds "|"] puts "into handle_cmds_root" foreach hex_cmd $hex_cmds { set cmd [binary format H* $hex_cmd] send -- "$cmd " puts "root:$cmd" expect { "$root_pmt" { } eof { exit 4} timeout { exit 5} } } } proc handle_pwd { } { global pwd pwd_pmt user_pmt login_fail_pmt argc root_pwd root_pmt puts "into handle_pwd" puts "pwd:$pwd" puts "pwd_pmt:$pwd_pmt" send -- "$pwd " expect { "$user_pmt" { send -- "export LANG=en_US.UTF-8 " send -- "export LANGUAGE=en_US.UTF-8 " puts "argc $argc" if { $argc == 7} { send -- "su - " expect { "$pwd_pmt" { send -- "$root_pwd " expect { "$root_pmt" handle_cmds_root eof { exit 4} timeout { exit 5} } } eof { puts "-eof" ; exit 1 } timeout { puts "-timeout"; exit 2 } } } elseif { $argc == 6 } { handle_cmds } } timeout { puts "timeout" ; exit 7 } eof { puts "eof" ; exit 6 } } exit 0 } proc handle_user { } { global user pwd_pmt send -- "$user " expect { "$pwd_pmt" handle_pwd timeout { exit 9 } eof { exit 8 } } } puts "result:$result" if { $proto == "0" } { if { $result == "CONTINUE" || $result == "ERROR" } { spawn $ssh -p $port $user@$ip } else { send "$ssh -p $port $user@$ip " } } elseif { $proto == "1" } { if { $result == "CONTINUE" } { spawn -noecho $telnet $ip $port } else { send -- "$telnet $ip $port " } } expect { "$pwd_pmt" handle_pwd "$login_pmt" handle_user "(yes/no)?" { puts "yes/no?" send "yes " expect { "$pwd_pmt" { handle_pwd } timeout { exit 10 } eof { exit 11 } } } eof { exit 12 } timeout { exit 13 } }
原文地址:https://www.cnblogs.com/wliangde/p/3759384.html