我已将以下行(使用不同的 IP)添加到文件中/etc/hosts
:
192.168.0.4 my_pc
同样,该~/.ssh/config
文件中有以下条目:
Host 192.168.0.*
IdentityFile ~/id_rsa
ping
向发送一个my_pc
,会按预期向 发送一个 ping 192.168.0.4
。我还可以使用 ssh 进入机器。如果我尝试,身份验证会失败,因为未使用密钥。ssh [email protected]
ssh user@my_pc
如何设置 ssh 以便/etc/hosts
识别?我知道可以输入主机名,~/.ssh/config
但是有没有办法将主机名保留在该文件之外并使其与 IP 匹配/etc/hosts
?
答案1
您不需要使用/etc/hosts
文件进行连接user@my-pc
。将以下几行添加到~/.ssh/config
Host my-pc
Hostname 192.168.0.4
Port 22
User john
IdentityFile ~/id_rsa
所以现在当你输入ssh my-pc
它就会连接到[电子邮件保护]
我自己编写了一个小脚本,以便尽快添加新主机,您也可以使用它;)
#!/bin/bash
#Made by Gen Lee ^.^
#######
#Adds new host to ~/.ssh/config
ver="Ezy SSH v0.1"
#Colors:
red='\033[01;31m'
norm='\033[00m'
echo "Started $ver"
# Questions
echo -en "Enter ${red}host${norm}: "
read config_host
echo -en "Enter ${red}domain${norm}/${red}ip${norm}: "
read config_hostname
echo -en "Enter ${red}port${norm} (${red}22${norm}): "
read config_port
echo -en "Enter ${red}username${norm} (${red}root${norm}): "
read config_user
echo -en "Enter ${red}private key location${norm}: "
read config_key
# Checking information
check_host=$(awk "/^Host $config_host$/" ~/.ssh/config)
if [ ! $check_host ]; then
sleep 0
else
echo -e "You already have following host (${red}$config_host${norm})!"
exit 0
fi
if [ ! $config_port ]; then
config_port="22"
fi
if [ ! $config_user ]; then
config_user="root"
fi
test -f $config_key
if [ $? -eq 1 ]; then
echo "Private key location is invalid!"
exit 0
fi
# Adding parameters to ~/.ssh/config
echo "" >> .ssh/config
echo "Host $config_host" >> ~/.ssh/config
echo -e "\t Hostname $config_hostname" >> ~/.ssh/config
echo -e "\t Port $config_port" >> ~/.ssh/config
echo -e "\t User $config_user" >> ~/.ssh/config
if [ ! $config_key ]; then
sleep 0
else
echo -e "\t IdentityFile $config_key" >> .ssh/config
fi
echo "All done! ^.^"
exit 0