您的位置:首页 > 其它

不输入密码自动通过 SSH 方式登录服务器

2010-05-03 16:42 871 查看
不输入密码自动通过 SSH 方式登录服务器

ChinaUnix 网友:Seaquester

看到 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 <Server IP>"

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: