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

搜集的知识如下:

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

expect脚本解释

代码如下

#!/usr/bin/expect --
if { $argc != && $argc != } { exit }
set ip [lindex $argv ]
set port [lindex $argv ]
set proto [lindex $argv ] ;#:ssh;:telnet
set user [lindex $argv ]
set pwd [binary format H* [lindex $argv ]]
set cmds [lindex $argv ] if { $argc == } {
set root_pwd [binary format H* [lindex $argv ]]
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\r"
expect {
"$user_pmt" { }
"not found" { }
eof { exit }
timeout { exit }
}
}
} 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\r"
puts "root:$cmd"
expect {
"$root_pmt" { } eof { exit }
timeout { exit }
}
}
} 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\r" expect {
"$user_pmt" {
send -- "export LANG=en_US.UTF-8\r"
send -- "export LANGUAGE=en_US.UTF-8\r"
puts "argc $argc"
if { $argc == } {
send -- "su -\r" expect {
"$pwd_pmt" {
send -- "$root_pwd\r" expect {
"$root_pmt" handle_cmds_root eof { exit }
timeout { exit }
} }
eof { puts "-eof" ; exit }
timeout { puts "-timeout"; exit }
}
} elseif { $argc == } {
handle_cmds
}
}
timeout { puts "timeout" ; exit }
eof { puts "eof" ; exit }
}
exit
} proc handle_user { } {
global user pwd_pmt
send -- "$user\r"
expect {
"$pwd_pmt" handle_pwd
timeout { exit }
eof { exit }
}
} puts "result:$result" if { $proto == "" } {
if { $result == "CONTINUE" || $result == "ERROR" } {
spawn $ssh -p $port $user@$ip
} else {
send "$ssh -p $port $user@$ip\r"
}
} elseif { $proto == "" } {
if { $result == "CONTINUE" } {
spawn -noecho $telnet $ip $port
} else {
send -- "$telnet $ip $port\r"
}
} expect {
"$pwd_pmt" handle_pwd
"$login_pmt" handle_user
"(yes/no)?" {
puts "yes/no?"
send "yes\r"
expect {
"$pwd_pmt" { handle_pwd }
timeout { exit }
eof { exit }
}
}
eof { exit }
timeout { exit }
}
05-28 12:11