shell脚本实现ssh自动登录功能分享
文件名:ssh_auto_login
复制代码 代码如下:
#!/usr/bin/expect
##
# ssh模拟登陆器
#
# @author zhiyuan <hzyhouzhiyuan艾特gmail.com>
##
if {$argc<4} {
puts "Error params: $argv"
puts "Expect params :user passwd ip port [translate_id]"
exit 1
}
set default_passcode "这里填通道机的默认密码"
set user [lindex $argv 0]
set password [lindex $argv 1]
set ip [lindex $argv 2]
set port [lindex $argv 3]
set timeout 10
while 1 {
spawn ssh -p $port $user@$ip
#如果最后的字符匹配则执行命令\r结尾表示确定
expect {
"*yes/no" { send "yes\r";exp_continue}
"*password:" { send "$password\r" }
}
#这里是需要通过通道机登陆时的匹配流程,根据需要自行修改。
expect {
"*PASSCODE:" {
send_user "请输入通道机动态密码:";
expect_user -re "(.*)\n"
set random_passcode $expect_out(1,string)
send "$default_passcode$random_passcode\r"
expect {
"Access Denied" { continue }
"Enter:" { send "1\r" }
}
set translate_ip [lindex $argv 4]
if { $translate_ip != "" } {
expect "*):" { send "$translate_ip\r" }
}
}
#"Last login:*" { }
}
break
}
#无法匹配$,还不知道怎么解决
#expect -re "*\$" { puts "test123"; send "source /etc/profile\r" }
#expect "*\$" { send "cd ~\r" }
send_user "login success!"
interact
上边是ssh的自动登录,可以配合下边的shell使用,很方便。
文件名:xxx_launcher
复制代码 代码如下:
#!/bin/sh
##
# 服务器登陆器
#
# @author zhiyuan <hzyhouzhiyuan@gmail.com>
##
channel_user="user_namexxx"
channel_passwd="xxxx"
#内网通道机
internal_ip1=xxx.xxx.xxx.xxx
#联通
unicom_ip1=xxx.xxx.xxx.xxx
#电信
telecom_ip1=xxx.xxx.xxx.xxx
case "$1" in
ci)
expect ssh_auto_login $channel_user $channel_passwd $internal_ip3 22
cl)
expect ssh_auto_login $channel_user $channel_passwd $unicom_ip1 22
cd)
expect ssh_auto_login $channel_user $channel_passwd $telecom_ip1 22
149)
expect ssh_auto_login channel_user channel_passwd xxx.xx.xxx.xxx 22
49)
expect ssh_auto_login $channel_user $channel_passwd $unicom_ip1 22 需要通道机跳转的ipxxx.xxx.xx
*)
echo "帮助信息:"
echo "\tthere is not a server named [$1]"
echo "\t服务器149:\t149"
echo "\t服务器49:\t49"
esac
此时登陆某个服务器的时候就直接 用上述shell带要登录的服务器参数即可,如: ./xxx_launcher 49
下一篇:Linux base shell重定向详解