我正在使用 Ubuntu 18.04(用于我的本地机器和服务器),当我离开一段时间后再返回打开的 SSH 会话时,终端会冻结。
我必须关闭终端窗口,然后通过 SSH 重新登录服务器才能再次访问。这变得相当烦人。
如果 SSH 会话正在显示一系列新信息,例如每隔几秒打印新信息的日志,则它不会冻结。只有当一段时间内没有在屏幕上打印任何内容时,终端才会冻结。
我怎样才能保持 SSH 会话登录状态而不会发生这种情况?
答案1
我使用以下命令保持 SSH 会话处于活动状态:
#!/usr/bin/perl
# Name: /usr/bin/bigben Author: Joe Smith
# Purpose: Outputs time, uptime, or message every N minutes to keep session up.
# Automatically terminates when STDIN is no longer connected to a terminal.
use strict; use warnings;
$| = 1;
my $period = 10; # Default minutes between outputs
@ARGV and $ARGV[0] =~ /^-(\d+)$/ and $period = 0-shift; # "-60" for 60 minutes
(@ARGV and $period) or die <<EOM;
Usage: bigben "Hello, World!" & # Output text & time every $period minutes
bigben -d & # Output date & time every $period minutes
bigben -q & # Output a null byte every $period minutes
bigben -u & # Output `uptime` every $period minutes
bigben -15 -d & # Output date & time every 15 minutes
Also outputs `date` at startup and at midnight.
Program automatically terminates upon logout or network disconnection.
EOM
my $string = "@ARGV";
my $today = 'first time';
# Sleep 1 second to start; continue while -t() is true; wake once a minute
for (sleep 1; -t(); sleep 60 - (time % 60)) { # Stop when /dev/tty disappears
next unless $today eq 'first time' or ((time/60) % $period) == 0;
my ($sec,$minutes,$hours,$day,$mon,$year,$weekdaynum) = localtime;
my $yyyymmdd = sprintf "%04d-%02d-%02d", $year+1900, $mon+1, $day;
my $hhmmss = sprintf "%02d:%02d:%02d", $hours, $minutes, $sec;
my $weekday = (qw(Sun Mon Tue Wed Thu Fri Sat))[$weekdaynum];
system 'date' unless $today eq $weekday; # First time or at midnight
if ($string eq '-d') { # Output date & time
printf "\r\t\t\t\t %s %s \r\n", $yyyymmdd, $hhmmss;
} elsif ($string eq '-q' or $string eq '-n' or $string eq '-0') {
print "\0"; # Quiet: output a null byte
} elsif ($string eq '-u') {
$_ = `uptime`; s/\s+/ /g; # Get uptime and squeeze it
s/^/$weekday/; s/ day(s?), /day$1_/;
s/_(\d) min/_00:0$1/; s/_(\d\d) min/_00:$1/; s/_(\d):/_0$1:/;
s/load average: (\S+) (\S+) (\S+)/LA:$1$2$3/;
print "\r\t\t $_\r\n"; # Output modified uptime
} else { # Output "string HH:MM"
printf "\r\t\t\t\t %s %s %02d:%02d %s\r\n",
$string,$weekday,$hours,$minutes,
($minutes == 0 ? $yyyymmdd : '');
}
$today = $weekday;
}
当我的 .login 文件检测到 SSH 会话时,它会在某些主机上运行“bigben -u &”。
另一种方法是使用“ssh -o TCPKeepAlive remotehost”来保持 NAT 转换处于活动状态。