IT技术博客大学习 共学习 共进步

shell实现ssh自动登录

三江小渡 2016-03-21 22:57:30 浏览 1,562 次

mac下没有找到好用的类似secureCRT,就自己写了个自动登录的脚本,分享一下,如果是新浪的,就基本不用修改代码就直接能用。(其实是想表示虽然那么久没更新,但博主还活着~)

文件名: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


建议继续学习

  1. Linux shell脚本使用while循环执行ssh的注意事项 (阅读 8,061)
  2. 在ssh服务里使用chroot (阅读 5,841)
  3. 为什么要用公钥/私钥而不是密码去做SSH身份验证 (阅读 5,701)
  4. 如何让ssh登录更加安全 (阅读 5,602)
  5. ssh连接超时解决办法 (阅读 5,503)
  6. 懒人连ssh不输密码若干大法 (阅读 5,481)
  7. SSH无密码登录 (阅读 5,481)
  8. ssh命令 (阅读 5,223)
  9. 共享会话的ssh连接配置 (阅读 4,702)
  10. 一句话crontab实现防ssh暴力破解 (阅读 4,563)