Ssh断线自动登录

ssh出于安全考虑,设置了闲置后自动断开功能,这给长时间进行远程操作及利用ssh穿qiang的同学带来了极大的不便,参考了网上的N种方法,实现如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/expect
# Auto login ssh

set user "username";
set passwd "password";
set host "ip";
set id1 1;

while (1) {
set isconnected 0;
spawn /usr/bin/ssh -D7070 $user@$host;
set id1 $spawn_id
match_max 100000;
set timeout 60;
expect {
"password:" {
send "$passwd\r";
expect "jailshell" {
set isconnected 1;
puts "connected to $host succeed";
puts $spawn_id;
}
}

"closed" {
set isconnected 0;
#puts "connected to $host fail"

}

}

if { $isconnected == 0 } {
close;
puts "SSH server connect fail,retrying...";
continue;

}

while (1) {
set isconnected 0;
interact {
timeout 22 {
set timeout 10;
send "echo im active\r";
expect "*im active*" { set isconnected 1 }
if { $isconnected == 1 } {
puts "on line\r";
continue;
} else {
puts "off line\r"
break;
}
}
close;
puts "SSH server connect fails,retrying...";
}