Perl实现的命令行小工具sshfind:通过主机名称关键字搜索和筛选~/.ssh/config主机配置项

作用

读取SSH客户端配置文件~/.ssh/config,根据主机名称筛选对应的主机相关配置项,适用于~/.ssh/config主机信息过多,不便于查找的情况,如本人该文件配置了500+主机;

使用方法:

  sshfind racknerd    #根据racknerd作为主机名称关键字进行搜索,模糊匹配
  sshfind racknerd 2  #根据racknerd作为关键字搜索,仅列出两个结果

sshfind.pl脚本代码:

#!/usr/bin/perl -W
#用途:命令行传递主机名称关键字搜索~/.ssh/config的主机配置项
#参数说明:
#     $1 ---  主机名称搜索关键字
#     $2 ---  要显示主机的个数限制
#Usage:
#     sshfind.pl racknerd      #查找主机名包含racknerd的主机
#     sshfind.pl racknerd 1    #查找主机名包含racknerd的主机,仅列出一个
#     sshfind.pl . 5           #查找主任意关键字主机,仅列出前5个

use strict;

my $hostName=$ARGV[0]?$ARGV[0]:"";               #要搜索的SSH主机名
my $maxCount=$ARGV[1]?$ARGV[1]:0;                #至多列出的主机个数,默认为0即不限制(列出所有匹配的主机)
my $showLine=0;                                  #SSH Config行打印标记开关
my $foundCount=0;                                #查找到的主机个数,同一关键字可能匹配到多个主机
my $sshConfigFile="$ENV{'HOME'}/.ssh/config";    #SSH配置文件路径:(~/.ssh/config)

if(! "$hostName"){
	print "缺少搜索关键字,将列出 ~/.ssh/config 全部主机!\n";
}

open(SSHCONFIG,"<$sshConfigFile") or die "$sshConfigFile 文件无法打开, $!";

while (<SSHCONFIG>) {
	if(/^[\s\t]*Host[\s\t]+.*($hostName).*/i){
		$showLine=1;
		$foundCount+=1;
		printf "\n" if $foundCount>1;
	}
	elsif(/^[\s\t]*Host[\s\t]+.*$/i){
		$showLine=0;
	}
	last if $maxCount>0 and $foundCount==$maxCount+1 and $foundCount--;
	print if $showLine==1;	
}

print "\n找到主机 $foundCount 个\n";

使用效果:

sshfind 其他版本:

Python实现的版本:
https://www.cnblogs.com/cnhack/p/17009406.html

posted @ 2022-12-28 09:14  晴云孤魂  阅读(30)  评论(0编辑  收藏  举报