ssh 自动登录脚本
27 March 2019
yum install -y expect

主要实现了自动 ssh 登录,自动登录后执行命令(例如登录数据库,进入到默认目录)
使用方式

/usr/bin/mylogin host1

cat /usr/bin/mylogin

#!/usr/bin/expect

set timeout 120

set type [lindex $argv 0]

set user "root"       # default user
set passwd "passwd"   # default passwd
set host $type        # default host
set port 22           # default port
set cmd "clear\n"     # default cmd

set user_host1      "root"
set passwd_host1    "passwd"
set host_host1      "192.168.10.111"
set port_host1      22
set cmd_host1       "cd /home/user/data/wwww && clear"

set user_host1db    "root"
set passwd_host1db  "passwd"
set host_host1db    "192.168.10.111"
set port_host1db    22
set cmd_host1db     "mysql -uroot -proot\nuse DATADASE"

set user_host2      "root"
set passwd_host2    "passwd"
set host_host2      "192.168.10.112"
set port_host2      22
set cmd_host2       "clear"


if { [info exists $user_type] } {
    set user [expr $$user_type]
}
if { [info exists $passwd_type] } {
    set passwd [expr $$passwd_type]
}
if { [info exists $host_type] } {
    set host [expr $$host_type]
}
if { [info exists $port_type] } {
    set port [expr $$port_type]
}
if { [info exists $cmd_type] } {
    set cmd [expr $$cmd_type]
}

if { [info exists $mosh_type] } {
    spawn mosh $user@$host
} else {
    spawn ssh -Y -p $port $user@$host
}

expect {
    "yes/no" {
        send "yes\n"; exp_continue
    }
    "password:" {
        send "$passwd\n"; exp_continue
    }
    "*@*" {
        send "$cmd\n"
    }
}

interact