1、背景
使用mac的终端直接ssh,但是每次都要输入密码,不堪其扰,我就想到了用shell脚本写出一个替我自动输入密码的一个脚本。这个脚本应该也适用于Linux。
2、源码
ssh_login.expect
#!/usr/bin/expect set ssh_name [lindex $argv 0] set timeout 1 if {$ssh_name == ""} { puts "输入的服务器名字不能为空!" exit } set fid [open "$env(HOME)/.ssh_info.txt" r] set flag 0 while {[gets $fid line] >= 0} { set name [lindex $line 0] set ip [lindex $line 1] set port [lindex $line 2] set user [lindex $line 3] set passwd [lindex $line 4] if {$name == $ssh_name} { set flag 1 break } } close $fid if {$flag == 0} { puts "没有找到该服务器名字!" exit } else { puts "即将连接>>>>>>>>>>>" } spawn ssh -p $port $user@$ip expect { "yes/no" { send "yes\n"; exp_continue } "assword:" { send "$passwd\n" } } expect { "assword:" { puts "密码错误,请检查配置文件!" exit } } expect $user interact
3、使用方法
需要在自己的用户目录下面创建一个文件名为 .ssh_info.txt
内容为以下的格式:
name ip port user password test 192.168.1.1 22 root root1234
解释:第一行为列名,写不写都可以,第一个字段是服务器的名字,需要保证不能重复,第二个是服务器ip,第三个是ssh端口,第四个是用户名,第五个是ssh密码。
然后执行:
./ssh_login.expect <name>