不输入密码自动通过SSH方式登录服务器
冷胜魁(Seaquester)
lengshengkui@gmail.com
2009-7-1
看到ChinaUnix上面有一个网友的帖子,想在linux下使用ssh登录的时候不用每次都输入密码,又不能使用key的方式。
在网上搜索了一下,有网友用expect写了一个自动登录的脚本,但是我试过之后,却发现不能用。
后来看到有人说使用sshpass可以解决问题。所以自己写了一个脚本。脚本写的比较简单,没有考虑安全性的问题。要使用这个脚本必须安装sshpass这个软件。
sshlogin.sh:
#!/bin/bash
#===============================================================================
#
# FILENAME:
# sshlogin.sh
#
# DESCRIPTION:
# Script to use user and password from config file to login remote
# ssh server.
# This script needs 1 argument to login the remote ssh server:
# ipaddr = IP Addreess of remote ssh server.
#
# For example:
# ./sshlogin.sh 192.168.0.1
#
# You need to create a config file(pass.dat) with entries like:
# server1|user|password
# server2|user|password
#
# REVISION(MM/DD/YYYY):
# 07/01/2009 Shengkui Leng (shengkui.leng@advantech.com.cn)
# - Initial version
#
#===============================================================================
#------------------------------------------------------------------------------
# NAME:
# print_usage
#
# DESCRIPTION:
# Print usage information
#
# PARAMETERS:
# $1 - Program name
#
# RETURNS:
# None
#------------------------------------------------------------------------------
print_usage ()
{
echo "Usage: $1 "
exit 1
}
[ $# -eq 1 ] || print_usage $0
CONFIG_FILE=pass.dat
SERVER=$1
ipaddr=""
username=""
password=""
found=0
while read line ; do
ipaddr=$(echo $line | cut -d'|' -f1)
username=$(echo $line | cut -d'|' -f2)
password=$(echo $line | cut -d'|' -f3)
if [ "$SERVER" == "$ipaddr" ] ; then
#The server found!
found=1
break
fi
done < $CONFIG_FILE
if [ $found -eq 0 ] ; then
echo "The server not found!"
exit 2
fi
if [ -z "$password" ] || [ -z "$ipaddr" ] || [ -z "$username" ] ; then
echo "Invalid config file: $CONFIG_FILE!"
exit 3
fi
#Automatically add new host keys to user known hosts files(known_hosts)
AUTO_ADD_HOST_KEY="-oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no"
echo "Logining(ssh) $username@$ipaddr..."
sshpass -p "$password" ssh $username@$ipaddr $AUTO_ADD_HOST_KEY
exit 0
注1:需要建立一个记录密码、用户名和ssh server IP的文件pass.dat, 格式为:IP|UserName|Password。示例如下:
pass.dat:
192.168.0.1|root|a123B56
192.168.0.2|root|7X890Yz
注2:如果是第一次用ssh登录某一个server时,ssh会提示:
The authenticity of host '192.168.0.1 (192.168.0.11)' can't be established.
RSA key fingerprint is 7b:b9:c3:cd:01:cd:2f:19:4e:96:d3:66:27:55:7f:65.
Are you sure you want to continue connecting (yes/no)?
所以上面的脚本在调用ssh时指定了参数:
-oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no
这样ssh就不会出现上面的提示,详情请参考man ssh_config。
阅读(5606) | 评论(2) | 转发(0) |